/**
 * WDR Verkehrsportal jQuery Scripts
 * 
 * @author Codevise Solutions Limited Bonn
 * @version 1.0
 * @date May 2009
 */

// Array Remove - By John Resig (MIT Licensed)
Array.prototype.remove = function(from, to) {
  var rest = this.slice((to || from) + 1 || this.length);
  this.length = from < 0 ? this.length + from : from;
  return this.push.apply(this, rest);
};

function in_array(needle, haystack) {
	for ( var i = 0; i < haystack.length; i++ ) {
		if (needle === haystack[i]) {
			return true;
		}
	}
	return false;
}

/**
 * document.onLoad funktionen
 */
$(function() {
	
	 /**
	  * hoverDelay - delay in ms
	  */
	 var hoverDelay = 700;
	 /**
	  * lastHash stores the last url hash
	  */
	 var lastHash = '';
	 
	 var hoverTimer = null; 
	 
	// zeige links auf die staukarte. 
	$(".staukarteLink").removeClass("inv");
	
	// initialize hash management
	if(location.hash !== null && location.hash !== undefined && location.hash !== '' && location.hash.indexOf(';') < 0) { 
		//$(location.hash).scrollSmooth();
		if(location.hash.indexOf("#") < 0) {
			location.hash = '#streets=' + location.hash + ",;";
		} else {
			location.hash = '#streets=' + location.hash.slice(location.hash.indexOf("#") + 1) + ",;";
		}
	} 
	
	var urlHashManager = new UrlHashManager(function(hash, isFirst) { 

		// startseite karten
		if (hash['toggleMaps'] === 'true' || 
				(document.cookie.indexOf('WDRVerkehrWebsiteTogglemapCookie=true') > -1 && hash['toggleMaps'] !== 'false')) {
			$('#statusstart').slideDown();
			$('#staukarte').slideUp('fast');
			$('#staudeutschland').slideUp('fast');
			document.cookie = 'WDRVerkehrWebsiteTogglemapCookie=true; path=/';	
			$('#minimize-map-text').html('Maximieren');
		} else {
			$('#statusstart').slideUp();
			$('#staukarte').slideDown('fast');
			$('#staudeutschland').slideDown('fast');
			document.cookie = 'WDRVerkehrWebsiteTogglemapCookie=false; path=/';
			$('#minimize-map-text').html('Minimieren');
		}
		
		// startseite meldungsbox visible toggle
		if ($("#stauaktuell").length > 0) {
			if ( hash['toggleInformation'] === 'true' ||
					(document.cookie.indexOf('WDRVerkehrWebsiteToggleInformationCookie=true') > -1 && hash['toggleInformation'] !== 'false')) {
					$('#meldungsbox').slideUp('fast');
					$("#minimizeInformation").html("Maximieren <span class=\"infobox\">Minimieren/Maximieren<br>Mit dieser Funktion k&ouml;nnen sie die Meldungsbox ein- bzw. ausblenden.</span>");
					document.cookie = 'WDRVerkehrWebsiteToggleInformationCookie=true; path=/';
			} else if ( $('#meldungsbox').css('display') != 'block' ) {
					$('#meldungsbox').slideDown('fast');
					$("#minimizeInformation").html("Minimieren <span class=\"infobox\">Minimieren/Maximieren<br>Mit dieser Funktion k&ouml;nnen sie die Meldungsbox ein- bzw. ausblenden.</span>");
					document.cookie = 'WDRVerkehrWebsiteToggleInformationCookie=false; path=/';
			}
		}
			
		// startseite: autobahn / bundesstrasse / andere Meldungen anzeigen
		if (hash['meldungen'] !== lastHash['meldungen'] && hash['meldungen'] !== undefined) {
			var tabs = [ 'autobahnen', 'bundesstrassen', 'andere' ];
			
			if ( $('#' + hash['meldungen']).css('display') !== 'block' ) {
				
				$('#strassenliste').fadeTo('fast',0, function(){
					for ( var i = 0; i < tabs.length; ++i ) {
						$('#' + tabs[i]).css('display','none');
					}
					$('#' + hash['meldungen']).css('display','block');
					$('#strassenliste').fadeTo('fast',1);
					
					// Navigations Reiter anpassen
					var lis = $('#streets > li');
					$.each(lis, function(i, n) {
						var li = $(n);
						if (li.attr("id").split("-")[1] === hash['meldungen']) {
							li.addClass('aktiv');
						} else {
							li.removeClass('aktiv');
						}
					});
					if (!$('#streets li').hasClass('aktiv')) { 
						$('#streets li:first').addClass('aktiv');
					}
				});
			}
		}
		
		// startseite: StreetView	
		if ( hash['streets'] && hash['streets'].length > 0) {
			var streets = hash['streets'];
			var streetItems = $('.strassen > li');
				
			$.each ( streetItems, function(i, o) {
				var street = $(o);
				var id = street.find('.strasse a').attr('id');
				var table = street.find("#" + id + "-messages");
				if ( in_array(id, streets)) {
					table.css('display','block');
					street.find('img.detailicon').attr('src','images/icons/pfeilrauf.gif');
					street.find('.detailtext').html("Zuklappen");
				} else {
					table.css('display', 'none');
					street.find('img.detailicon').attr('src', 'images/icons/pfeilrunter.gif');
					street.find('.detailtext').html("Aufklappen");					
				}
			});
			
			if (isFirst === true && streets.length > 0) { 
				$("#" + streets[0] + "-messages").scrollSmooth();
			}			
		} else {
			$('.strassen li').find('table').css('display','none');
			$('.strassen li').find('img.detailicon').attr('src', 'images/icons/pfeilrunter.gif');
			$('.strassen li').find('.detailtext').html("Aufklappen");
		}
		
		$('.prognose').css('display', 'none');
		$('.prognose-header .detailicon').attr('src', 'images/icons/pfeilrunter.gif');
		$('.prognose-header .detailtext').html("Aufklappen");
		if (hash['prediction']) { 
			var prediction = $('#' + hash['prediction'] + '-prognose');
			prediction.css('display', 'block'); 
			prediction.parent().find('img.detailicon').attr('src', 'images/icons/pfeilrauf.gif');
			prediction.parent().find('.detailtext').html("Zuklappen");
		}
		
		lastHash = jQuery.extend({}, hash);
	});
			
	// add street to hash 
	function addToOrRemove (key, value) {
		var values = urlHashManager.value(key) || [];
		
		for (var i = 0; i < values.length; i++) {		
			if ( value === values[i] ) {
				// remove existing entry from streetstring
				values.splice(i, 1);
				urlHashManager.add(key, values);
				return false;
			}
		}
		values.push(value); 
		urlHashManager.add(key, values);
		return true;
	}
	
	function addStreetToHash (street) {
		return addToOrRemove('streets', street);
	}
	
	function addPredictionToHash (prediction) { 
		return addToOrRemove('predictions', prediction);
	}
	
	/** -- end of URL Hash Management -- **/
	
	// Startseite: BRD & Bundesland Staukarten toggle
	$('#minimizeMaps').click( function() {
		if ( urlHashManager.value('toggleMaps') === 'false' ||
				document.cookie.indexOf('WDRVerkehrWebsiteTogglemapCookie=false') > -1 ) {
			document.cookie =  'WDRVerkehrWebsiteTogglemapCookie=true';
			urlHashManager.add('toggleMaps', 'true');
		} else {
			document.cookie = 'WDRVerkehrWebsiteTogglemapCookie=false';
			urlHashManager.add('toggleMaps','false');
		}
		return false;
	});
	
	// Startseite: Meldungsbox toggle
	$('#minimizeInformation').click( function() {
		if ( $('#meldungsbox').css('display') !== 'none' ) {
			urlHashManager.add('toggleInformation','true');
		} else {
			urlHashManager.add('toggleInformation','false');
		}
		return false;
	});
	
	// rewrite every '#'-anchor for smoothscrolling function and maybe even street view
	$('a[href*=#]').bind('click', function() {
		var id = $(this).attr('href').substr(($(this).attr('href').indexOf('#') + 1));
		if ( id !== '') {
			var a = $('a[name=' + id + ']'); 
			if(a.length === 0) { 
				a = $('#' + id); 				
			}
			a.scrollSmooth();
		}
		return false;
	});

	// Startseite: Meldungsbox Navigation
	$('#streets a').unbind('click');
	$('#streets li').click( function() {	
		if (!$(this).hasClass('aktiv')) {
			$('#meldungsbox .base li').removeClass('aktiv');
			$(this).addClass('aktiv');
			// URL Hash erweitern, HashManager übernimmt dann
			urlHashManager.add('meldungen', $(this).attr('id').split("-")[1].toLowerCase());
		}		
		return false;
	});
	
	// Akordeon Startseite
	function handleStreet(streetName) {
		var table = $("#" + streetName + "-messages");
		if (addStreetToHash(streetName)) {	
			table.scrollSmooth();
		} 			
		return false;	
	}	
	$('.strassen a.detailbutton').unbind('click');
	var strassen = $('.strassen .strasse');
	strassen.bind('click', function () {
		var streetName = $(this).find('> a').attr('id');
		handleStreet(streetName)
		return false;
	});
	strassen.css('cursor', 'pointer');
	$('.strassenauswahl a' ).unbind('click').bind('click', function() { 
		var id = $(this).attr('href').substr(($(this).attr('href').indexOf('#') + 1));
		handleStreet(id);
		return false;
	});
	
	// prognosen
	$('#prognosenliste a.detailbutton').unbind('click');
	var prognosenHeader = $('.prognose-header');
	prognosenHeader.bind('click', function() {
		var id = $(this).find('> a').attr('id');
		if(urlHashManager.value('prediction') !== id) {
			urlHashManager.add('prediction', id);
		} else {
			urlHashManager.rm('prediction');
		}
		return false;
	});
	prognosenHeader.css('cursor', 'pointer');
	
	
	$('#strecke .infos').hover(
		function() {
			if ( $('#verlaufinfo').is('*') ) { $('#verlaufinfo').remove(); }
			if ( hoverTimer != null ) clearTimeout(hoverTimer);
			var content = $(this).find('.meldungstext').html().split(':');
			var $parent = $(this);
			messages=content[1].split(' - ');
			contentString='<div class="infobox" id="verlaufinfo"><h5>'+content[0]+'</h5>';
			for (var i = 0; i < messages.length; i++) {contentString+='<p>'+messages[i]+'</p><br />';}
			contentString+='</div>';
			var $verlaufinfo = new jQuery(contentString);
			$verlaufinfo.css({top: ($(this).offset().top + $(this).height())});
			$(this).children().swapAttr('title','tempTitle');
			hoverTimer = setTimeout(
				function(){
					$('body').append($verlaufinfo);
					var offset = $parent.offset();
					if ( (offset.left + $verlaufinfo.width()) > $(window).width() ) {
						$verlaufinfo.css('left', offset.left - $verlaufinfo.width());
					} else {
						$verlaufinfo.css('left', offset.left);
					}
				}, hoverDelay);
		},
		function() {
			clearTimeout(hoverTimer);
			$('#verlaufinfo').remove();
			$(this).children().swapAttr('tempTitle','title');
		}
	); 

	// rewrite back links
	$('a.back').click(function () {
		window.history.back();
		return false;
	});
	
	// reload buttons
	$('a.reload').click(function(){ 
		window.location.reload(); 
		return false; 
	});
	
});


/**
 * jQuery Erweiterungen
 */

$.fn.stripTags = function() {
    return this.replaceWith( this.html().replace(/<\/?[^>]+>/gi, '') );
};

$.fn.scrollSmooth = function () {
	var pageHeight = $(document).height();
	var viewportHeight = $(window).height();
	var myOffset = $(this).offset().top;
	var diff = pageHeight - viewportHeight;
	myOffset = ( diff < myOffset ) ? diff : myOffset;
	$('html:not(:animated),body:not(:animated)').animate( {
		scrollTop : myOffset
	}, 1100);
}

/**
 * swapAttr
 * 
 * swaps one attribut to another name
 */
$.fn.swapAttr = function(source, destination, parent) {
	 parent = (parent == null) ? false : parent;
	 $(this).attr(destination, $(this).attr(source));
	 $(this).removeAttr(source);
	 if ( parent ) {
		 $(this).parent().swapAttr(source, destination);
	 }
}

