// main

// ToggleEffects for the widgetzone
function ToggleSlide (id1, id2) {
	position1 = "bottom";
	position2 = "top";
	
	if (id1 == "#lvb") {
		position1 = "top";
		position2 = "bottom";
	}

	var leftPosition = $(id1).outerWidth();

	if (parseInt($(id1).css("left")) == 0) {	

		$(id1).animate( { left: -leftPosition + "px" }, { queue:false, duration:1000 } );
		$(id2).animate( { left: -leftPosition + "px" }, { queue:false, duration:1000 } );
		
		$(id1).css('z-index', '1000');
		$(id2).css('z-index', '999');
		
		setTimeout(function() {
			$(id1 + " h4").css({'background-position' : 'left ' + position1});
			$(id2 + " h4").css({'background-position' : 'left ' + position2});		
			
			if ($.browser.msie && $.browser.version.substr(0,1) == 6 ) {
				$("#form_connection select").css('visibility' ,'visible')
			}
		}, 1000);
				
		$('.restricted_overlay').css('display', 'none');
		$(id1).removeClass('shadow');
		
	} else {	
		if ($.browser.msie && $.browser.version.substr(0,1) == 6 ) {
			$("#form_connection select").css('visibility' ,'hidden')
		}
			
		$(id1).animate( { left: "0" }, { queue:false, duration:1000 } );		
		$(id2).animate( { left: -leftPosition + "px" }, { queue:false, duration:1000 } );
		
		setTimeout(function() {
			$(id1 + " h4").css({'background-position' : 'right ' + position1});
			$(id2 + " h4").css({'background-position' : 'left ' + position2});
		}, 1000); 
		
		$(id1).css('z-index', '1000');
		$(id2).css('z-index', '999');

		$('.restricted_overlay').css('display', 'block');
		$(id1).addClass('shadow');
	}
}

// fade gallery
function gallerySlide() {

	if (!$('.image_showGalleryImages').cycle)
		return;
		
	$('.image_showGalleryImages').cycle({ 
		fx:    'fade', 
		timeout: 5000,
		delay: -2000,
		pause: 1
	});	
}


// fade news_showTop5
function top5Slide() {
	
	if (!$('.news_showTop5 ul').cycle)
		return;
	$('.news_showTop5 ul').cycle({ 
		fx:    'fade', 
		timeout: 5000,
		delay: -2000,
		pause: 1
	});	
}

// WidgetZone on the right side of the page 
function setWidgetZone() {

	// When a link is clicked
	$("ul.widgetzone a").click(function () {
		var closed = 0;
		if ($(this).hasClass("active")) {
			closed = true;
		}
		
		// switch all tabs off
		$(".active").removeClass("active");
		
		// slide all content up
		$(".widgetzone-content").slideUp();
		

		if (!closed) {	
			// switch this tab on
			$(this).addClass("active");
			if ($(this).hasClass("lnp_trigger"))
			{
				init_lnp();
			}
			
			// slide this content up			
			var content_show = $(this).attr("href");
			$(content_show).slideDown();
		}
					
		return false;
	});	
	
	$("ul.widgetzone a").hover( 
		function() {
			$(this).find("span").css({'z-index': '20'})
		}, 
		function() {
			$(this).find("span").css({'z-index': '10'})															
		}
	);
	
	if ($("#widgetTrafficInfo").css('display') =='block')	
	{
		$('#widgetStation').css('display','block');
	}
	
	$("ul.widgetzone li.fahrplan a").click(function () {
		$('#widgetStation').toggle();
	});
		

}

function setJammingSlide()
{
	$(".jamming_slide h5").click( function()
	{
		if ($($(this).next()).hasClass('open'))
		{
			$($(this).next()).animate({
				height: 'hide',
				opacity: 'hide'
			}, 'slow');
			
			$(this).removeClass('open');

			$($(this).next()).removeClass('open');
			
		}
		else
		{
			$(this).addClass('open');
			
			$($(this).next()).animate({
				height: 'show',
				opacity: 'show'
			}, 'slow');
			
			$($(this).next()).addClass('open');
		}
	});
}

// slide for the FAQ module
function setFaqSlide() {
	$("#faq_showSlide li div.content").hide();
	
	$("#faq_showSlide li h5").click( function() {
			if ($($(this).parent().find("div.content")).hasClass('open')) {
				$($(this).parent().find("div.content")).animate({
					height: 'hide',
					opacity: 'hide'
				}, 'slow');
				
				$("#faq_showSlide li div.content").removeClass('open');

				$('#faq_showSlide li h5').removeClass('open');
				
			} else {
					$('#faq_showSlide li h5').removeClass('open');
					$(this).addClass('open');
					
					$("#faq_showSlide li div.open").animate({
						height: 'hide',
						opacity: 'hide'
					}, 'slow');
					
					$($(this).parent().find("div.content")).animate({
						height: 'show',
						opacity: 'show'
					}, 'slow');
	
					$("#faq_showSlide li div.content").removeClass('open');	
					
					$($(this).parent().find("div.content")).addClass('open');
					
			}
																						
																						
	});
	
	
}

function init_lnp() {
	
	if (window.map_lnp)
	{
		return;
	}
	
	function mapsLoaded() {
		var that = this;

		var width_day  = 7057;
		var height_day = 4985;
		this.tiles_day = {
			"2": [3,2],
			"3": [6,4],
			"4": [13,9],
			"5": [27,19]
		}
		this.tiles_night = {
			"2": [3,2],
			"3": [7,5],
			"4": [15,10],
			"5": [31,20]
		}

		var lnp_min_zoom = 2;
		var lnp_max_zoom = 5;

		var lnp_layer_day = new google.maps.TileLayer(
			new google.maps.CopyrightCollection("(c) LVB 2009"), lnp_min_zoom, lnp_max_zoom);
		var lnp_layer_night = new google.maps.TileLayer(
			new google.maps.CopyrightCollection("(c) LVB 2009"), lnp_min_zoom, lnp_max_zoom);

		lnp_layer_day.getCopyright   = function(a,b) {
			return {prefix:"(c) LVB", copyrightTexts:["Copyrighted"]};
		};
		lnp_layer_night.getCopyright = function(a,b) {
			return {prefix:"(c) LVB", copyrightTexts:["Copyrighted"]};
		};

		lnp_layer_day.isPng   = function() {return false;};
		lnp_layer_night.isPng = function() {return false;};

		lnp_layer_day.getOpacity   = function() {return 1.0;};
		lnp_layer_night.getOpacity = function() {return 1.0;};

		lnp_layer_day.getTileUrl = function(point, zoom)
		{
			return that.asset_url + "/images/lnp/day/" + zoom + "/" + point.x + "/" + (that.tiles_day[zoom][1]-point.y) + ".jpg";
		};

		lnp_layer_night.getTileUrl = function(point, zoom)
		{
			return that.asset_url + "/images/lnp/night/" + zoom + "/" + point.x + "/" + (that.tiles_night[zoom][1]-point.y) + ".jpg";
		};

		var projection_day = {
			fromLatLngToPixel: function (latlng, zoom)
			{
				var factor = 1/Math.pow(2, lnp_max_zoom - zoom);
				return new google.maps.Point(latlng.lat()*100*factor, latlng.lng()*100*factor);
			},
			fromPixelToLatLng: function(pixel, zoom, unbounded)
			{
				var factor = 1/Math.pow(2, lnp_max_zoom - zoom);
				return new google.maps.LatLng(pixel.x/100/factor, pixel.y/100/factor);
			},
			tileCheckRange: function(tile, zoom, tilesize)
			{
				return tile.y >= 0 && tile.x >= 0 && tile.x <= that.tiles_day[zoom][0] && tile.y <= that.tiles_day[zoom][1];
			},
			getWrapWidth: function(zoom) {
				return 99999999999;
			}
		};
		var projection_night = {
			fromLatLngToPixel: function (latlng, zoom)
			{
				var factor = 1/Math.pow(2, lnp_max_zoom - zoom);
				return new google.maps.Point(latlng.lat()*100*factor, latlng.lng()*100*factor);
			},
			fromPixelToLatLng: function(pixel, zoom, unbounded)
			{
				var factor = 1/Math.pow(2, lnp_max_zoom - zoom);
				return new google.maps.LatLng(pixel.x/100/factor, pixel.y/100/factor);
			},
			tileCheckRange: function(tile, zoom, tilesize)
			{
				return tile.y >= 0 && tile.x >= 0 && tile.x <= that.tiles_night[zoom][0] && tile.y <= that.tiles_night[zoom][1];
			},
			getWrapWidth: function(zoom) {
				return 99999999999;
			}
		};
		
		var map_type_day = {
			de: "Tag",
			en: "Daytime",
			fr: "Jour"
		}
		var map_type_night = {
			de: "Nacht",
			en: "Night-time",
			fr: "Nuit"
		}
		
		var map_error_message = {
			de: "Keine Daten",
			en: "no data",
			fr: "no data"
		}
		
		var map_type_lnp_day = new google.maps.MapType(
			[lnp_layer_day],
			projection_day,
			map_type_day[window.lvb_lang],
			{maxResolution:lnp_max_zoom, minResolution:lnp_min_zoom, errorMessage: map_error_message[window.lvb_lang]}) ;

		var map_type_lnp_night = new google.maps.MapType(
			[lnp_layer_night],
			projection_night,
			map_type_night[window.lvb_lang],
			{maxResolution:lnp_max_zoom, minResolution:lnp_min_zoom, errorMessage: map_error_message[window.lvb_lang]}) ;

		window.map_lnp = new google.maps.Map2(document.getElementById("map_lnp_sidebar"), {backgroundColor: "#FFFFFF", mapTypes: [map_type_lnp_day, map_type_lnp_night]});
		window.map_lnp.addControl(new google.maps.LargeMapControl());    // erweiterte Zoom-Anzeige

		var lat = (width_day+350)  / (2*100);
		var lng = (height_day+2800) / (2*100);
		window.map_lnp.setCenter(new google.maps.LatLng(lat, lng), lnp_min_zoom);
		window.map_lnp.setMapType(map_type_lnp_day);
		
		GEvent.addListener(window.map_lnp, "movestart", function() {
			return false;
		});
		
		var lang = window.lvb_lang;
		{
			function MyMapTypeControl() {
			}
			
			MyMapTypeControl.prototype = new GControl();
			
			MyMapTypeControl.prototype.initialize = function(map) {
				var container = document.createElement("div");

				var mapDayDiv = document.createElement("div");
				mapDayDiv.style.position ="absolute";
				mapDayDiv.style.left ="-150px";
				this.setButtonStyle_(mapDayDiv);
				container.appendChild(mapDayDiv);
				mapDayDiv.appendChild(document.createTextNode(map_type_day[lang]));
				GEvent.addDomListener(mapDayDiv, "click", function() {
					map.setMapType(map_type_lnp_day);
				});

				var mapNightDiv = document.createElement("div");
				mapNightDiv.style.position ="absolute";
				mapNightDiv.style.left ="-75px";
				this.setButtonStyle_(mapNightDiv);
				container.appendChild(mapNightDiv);
				mapNightDiv.appendChild(document.createTextNode(map_type_night[lang]));
				GEvent.addDomListener(mapNightDiv, "click", function() {
					map.setMapType(map_type_lnp_night);
				});

				map.getContainer().appendChild(container);
				return container;
			}
		}

		MyMapTypeControl.prototype.getDefaultPosition = function() {
			return new GControlPosition(G_ANCHOR_TOP_RIGHT, new GSize(7, 7));
		}
		
		MyMapTypeControl.prototype.setButtonStyle_ = function(button) {
			button.style.color = "#333333";
			button.style.backgroundColor = "white";
			button.style.font = "small Arial";
			button.style.border = "1px solid #333333";
			button.style.padding = "2px 5px";
			button.style.marginBottom = "3px";
			button.style.textAlign = "center";
			button.style.width = "60px";
			button.style.cursor = "pointer";
			button.style.marginRight = "5px";
		}
		
		window.map_lnp.addControl(new MyMapTypeControl());


	}

	google.load("maps", "2", {"callback" : mapsLoaded});
}

//onload
$(function() {
					 	
	if ($('#search2_showForm-text')) {

		var query = {
			de: "Suchbegriff",
			en: "search query"
		}
		
		

		$('#search2_showForm-text').val(query[window.lvb_lang]);
		
		$('#search2_showForm-text').focus(function() {
			if (this.value == query[window.lvb_lang]) {
				this.value = "";	
			}
		});
		
		$('#search2_showForm-text').blur(function() {
			if (this.value == "") {
				this.value = query[window.lvb_lang];	
			}
		});
		
	}
	
	// change the labels on timetable form
	if ($(".lvb_maps_partial_connection_options").length) {
		changeLabel()
	}
	
	if ($(".lightbox").length) {
		$(".lightbox").colorbox({photo: true});
	}
	
	$("#lvb h4").click( function () {
		ToggleSlide('#lvb', '#help');	
	});
	
	$("#help h4").click( function () {
		ToggleSlide('#help', '#lvb');	
	});
	
	if ($('.widgetzone'))
		setWidgetZone();
		
	if ($('#faq_showSlide'))
		setFaqSlide();
		
	if($('.jamming_slide'))
		setJammingSlide();

	$('.restricted_overlay').click(function() {
		
		if (parseInt($('#lvb').css("left")) == 0) {
			ToggleSlide ('#lvb', '#help');
		} else {
			ToggleSlide ('#help', '#lvb');
		}
	});
	
	//news showTopX jQuery cycle
	$('.news_showTopX').each(function(index, element) {
		element = $(element);
		var slide_container = element.children('.slides');
		var regex = /([a-zA-Z]+)([0-9]+)/;
		var timeout = 5000;
		var rot_speed = 1000;
		
		if(element.attr('name'))
		{
			results = element.attr('name').split('_');
			if(results)
				for(var i = 0; i < results.length; i++)
				{
					var match = regex.exec(results[i]);
					if(match && match.length == 3)
						switch(match[1])
						{
							case 'rs':
								rot_speed = parseInt(match[2]);
								break;
							case 'to':
								timeout = parseInt(match[2]);
								break;
						}
				}
		}
		var slides = slide_container.children('li');
		// jQuery Cycle only initializes when more than 1 news item are present
		if(slides.length > 1)
		{
			slide_container.cycle({
				fx:    'fade',
				speed: rot_speed,
				timeout: timeout,
				delay: -2000,
				pause: 1,
				pauseOnPagerHover: 1,
				pager: '#' + $(element.children('.news-pager')[0]).attr('id'),
				activePagerClass: 'activeSlide',
				fastOnEvent: 100,
				pagerAnchorBuilder: function(s_index, slide){
					// using news headline as link title replacing double quotes 
					var regexp = new RegExp('"', 'g');
					var text = $(slide).children("h4").eq(0).text().replace(regexp, '&quot;');
					return '<li><a title="' + text + '" href="#">' + text + '</a></li>';
				}
			})
		}
		else
		{
			// set height and width correctly when showing only 1 news item
			if(slides.length == 1)
			{
				slide = $(slides[0]);
				var width = slide_container.parent().width();
				var height = slide.outerHeight();

				slide_container.css('height', height).css('width', width);
				slide.css('height', height).css('width', width);
			}
		}
	});		
	
	//timetable widget
	$('select.form_timetable_select').bind('change', function(){$("form.form_timetable").submit()});
});

function changeLabel() {
	$(".lvb_maps_partial_connection_options").change(function() {

		var label_station = {
			de: "Bhf./Haltestelle",
			en: "Station/Stop"
		}
		
		var label_address = {
			de: "Ort, Stra&szlig;e Nr.",
			en: "City/town, street, no."
		}
		
		var label_both = {
			de: "Bhf./Haltestelle oder Ort, Stra&szlig;e Nr.",
			en: "Station/Stop or City/town, street, no."
		}
	
		$(this).parent().next().find('label').removeClass('err');
	
		switch(parseInt($(this).val())) {
			case 1:
				$(this).parent().next().find('label').html(label_station[window.lvb_lang]);
				break;
			case 2:
				$(this).parent().next().find('label').html(label_address[window.lvb_lang]);
				break;
			default:
				$(this).parent().next().find('label').html(label_both[window.lvb_lang]);
				break;
		}
	});
}


// Verkehrsmittel
var selectCheckList = {
	container: "container",
	checkbox_container: "checkbox_container",
	init: function(container, checkbox_container) {
	
		this.container = container;
		this.checkbox_container = checkbox_container;
		
		var that = this;
		$(this.container+ " .select-overlay").click(function(){
			$(that.container + " " + that.checkbox_container).removeClass('initially_hidden');
		});		
	
		// hide overlay on outsideclick
		$(document).click(function(event) {
			if (event.target.id == $(that.container).attr('id'))
				return;
	
			var is_in_container = false;
				$(event.target).parents().each(function(index, element) {
					if (element.id == $(that.container).attr('id')) {
						is_in_container = true;
						return;
					}
			});
	
			if (is_in_container)
				return;
	
			$(that.container + " " + that.checkbox_container).addClass('initially_hidden');
			$('iframe').css('display', 'none');
		});
	
		var selectbox = $(this.container + " select")
		$(this.container + " " + this.checkbox_container + " input").click(function() {
		
			var select_val = new Array()
	
			$(that.container + " " + that.checkbox_container + " input:checked").each(function() {
				select_val.push($(this).next().html());
			});
			
			if (select_val.length == $(that.container + " " + that.checkbox_container + " input").length) {
				$(selectbox).find('option').html("Alle");
			}	else if (select_val.length > 2) {
				$(selectbox).find('option').html(select_val.length + " ausgewählt");
			} else {
				$(selectbox).find('option').html(select_val.join(", "));
			}
			
		});
		
		if (jQuery.browser.msie) {
			$(selectbox).mousedown(function() {
			
				var select_val = new Array()
		
				$(that.container + " " + that.checkbox_container).removeClass('initially_hidden');
				$('iframe').css('display', 'block');
		
				$(that.container + " " + that.checkbox_container + " input:checked").each(function() {
					select_val.push($(this).next().html());
				});
				
				if (select_val.length == $(that.container + " " + that.checkbox_container + " input").length) {
					$(selectbox).find('option').html("Alle");
				}	else if (select_val.length > 2) {
					$(selectbox).find('option').html(select_val.length + " ausgewählt");
				} else {
					$(selectbox).find('option').html(select_val.join(", "));
				}
				
			});
		}
		
		

}
};

function flickerFix() {
	try {
		 document.execCommand('BackgroundImageCache', false, true);
	} catch(e) {}
}

//let me try something else
$(function () {
	var widgetLinks = $('ul.widgetzone li a');
	
	//unbind everything, i don't like this mess
	widgetLinks.unbind('click');
	
	//renew the binds
	widgetLinks.click(function() {
		// switch all tabs off
		
		//we check the rel attribute, it becomes our object of concern
		var slideDiv = $(this).attr('rel');
		if (slideDiv) {
			$slideDiv = $(slideDiv);
		} else {
			return;
		}
		widgetLinks.each(function() {
			//this is not very elegant but should work	
			if ($(this).attr('rel') != slideDiv) {
				$($(this).attr('rel')).hide();
				//remove the active class from everything but the chosen link
				$(this).removeClass("active");
			}
		});
		
		// switch this tab on or off (depending on status 
		if ($(this).hasClass('active')) {
			$(this).removeClass('active');
		} else {
			$(this).addClass('active');
            
            if(typeof widgetAjaxRefresh === "function")
            {
                widgetAjaxRefresh();
            }
		}
		
		if ($(this).hasClass("lnp_trigger"))
		{
			init_lnp();
		};
		
		//we do a faster animation for the first tab
		if (slideDiv == '#widgetStationTraffic') {
			$slideDiv.animate({height:'toggle'}, 30);
		} else {
			$slideDiv.slideToggle();
		};
		
	});
});
