var default_select_content = false;

$(document).ready(function()
{

	$(".no_javascript").hide();
	$(".only_javascript").show();
	$(".country_dates h3").hide();
	
	
	$('table.dates tr a').click(function(event)
	{
		event.stopPropagation();
	})
	
	$('table.dates tr').click(function()
	{
		if(!$(this).hasClass("noclick"))
		{
			var link = $(this).find("a");

			if(link.attr("target") == "_blank")
			{
				window.open(link.attr("href"));
			}
			else
			{
				document.location = link.attr("href")
			}
		}
		
	})

	$('#online_tickets select.ticket_count').change(function()
	{
		var count = 0;
		$('#online_tickets select.ticket_count').each(function()
		{
			count = count + parseInt(this.value);
		});

		if($('select.discount').length > 0)
		{
			if(default_select_content === false)
			{
				default_select_content = $('select.discount').html();
			}
	
			var i = 0;
			var html = default_select_content;
			while(i < count)
			{
				html += "<option value=\""+(i+1)+"\">"+(i+1)+"x</option>";
				i++;
			}
	
			$('select.discount').html(html);
		}

		if(free_tickets-count < 0)
		{
			$('#ticket_notice').show();

			$('#ticket_notice_count').text(count);
			$('#ticket_notice_free').text(free_tickets);
	
			$('#submit_button').attr("disabled", "disabled");
		}
		else
		{
			$('#submit_button').attr("disabled", "");
			$('#ticket_notice').hide();
		}
	});

	var active_tab = false;
	var active_tab_url = document.location.hash.substr(1).split("/");
	var active_maps_tab = active_tab_url[0];

	if($.cookie('map_info_window'))
	{
		loadMap();
		$('#list_div').hide();
		$('#map_div').show();
	
		active_maps_tab = "map";
	
		document.location = "#map";
		active_tab = "map";
	
		if($.cookie('personalize_map_location') && $.cookie('personalize_map_country'))
		{
			$('#location').val($.cookie('personalize_map_location'));
			$('#country').val($.cookie('personalize_map_country'));
			$('.personalize_map').submit();
		
			$.cookie('personalize_map_location', null);
			$.cookie('personalize_map_country', null);
		}
	}
	else if(active_tab_url[0] == "list" || !$('.map_select').length)
	{
		$('#list_div').show();
		$('#map_div').hide();
	
		//clear cookies for map view
		$.cookie('map_zoom', null);
		$.cookie('map_center_lat', null);
		$.cookie('map_center_lng', null);
		$.cookie('map_info_window', null);
	}
	else
	{
		loadMap();
	
		$('#list_div').hide();
		$('#map_div').show();
	}

	if($('.dates_tabs').length)
	{
	
		if(active_tab_url[0] == "list" && active_tab_url[1])
		{
			active_tab = active_tab_url[1];

			if(active_tab.indexOf("dates_") == -1)
			{
				active_tab = "dates_"+active_tab;
			}
		}
		else
		{
			if(language == "de")
			{	
				active_tab = "dates_deutschland";
				$("select option[selected]").removeAttr("selected");
				$("select option[value='Wednesday']").attr("selected", "selected");
			}
			else if(language == "nl")
			{	
				active_tab = "dates_niederlande";
			}
			else if(language == "it")
			{	
				active_tab = "dates_italien";
			}
		}
	
		if($('#'+active_tab).length == 0)
		{
			active_tab = false;
		}
	
		$('.dates_tabs a').each(function()
		{
			var item_id = this.href.split("#");
			item_id = item_id[1];
			if(active_tab == false || active_tab == item_id)
			{
				$(this).addClass("active");
				active_tab = item_id;
			}
			else
			{
				$('#'+item_id).hide();
			}
		});
	
		$('.dates_tabs a').click(function()
		{
			var item_id = this.href.split("#");
			item_id = item_id[1];
		
			$('#'+active_tab).hide();
		
			$('.dates_tabs a').removeClass("active");
		
			$(this).addClass("active");
			$('#'+item_id).show();
		
			active_tab = item_id;
		
			document.location = "#list/"+item_id.replace(/dates_/, "");
			return false;
		});
	}


	if($('.map_select').length)
	{
		$('.map_select a').each(function()
		{
			var item_id = this.href.split("#");
			item_id = item_id[1];
		
			$(this).removeClass("active");
		
			if(active_maps_tab == false || active_maps_tab == item_id)
			{
				$(this).addClass("active");
				active_maps_tab = item_id;
			}
		});
	
		$('.map_select a').click(function()
		{
			var item_id = this.href.split("#");
			item_id = item_id[1];
		
			$('#'+active_maps_tab+"_div").hide();
		
			$('.map_select a').removeClass("active");
			$(this).addClass("active");

			$('#'+item_id+"_div").show();
		
			if(item_id == "map") {
				loadMap();
			} else {
				//clear cookies for map view
				$.cookie('map_zoom', null);
				$.cookie('map_center_lat', null);
				$.cookie('map_center_lng', null);
				$.cookie('map_info_window', null);
			}
		
			active_maps_tab = item_id;
		
			document.location = "#"+item_id;
			return false;
		});
	}

	//personalize map menu
	if(language == "de")
	{	
		$(".personalize_map select option[selected]").removeAttr("selected");
		$(".personalize_map select option[value='deutschland']").attr("selected", "selected");
	}
	else if(language == "nl")
	{	
		$(".personalize_map select option[selected]").removeAttr("selected");
		$(".personalize_map select option[value='niederlande']").attr("selected", "selected");
	}
	else if(language == "it")
	{	
		$(".personalize_map select option[selected]").removeAttr("selected");
		$(".personalize_map select option[value='italien']").attr("selected", "selected");
	}


	$('#country').change(function()
	{
		$('.personalize_map').submit();
	})

	$('#location').focus(function()
	{
		if(this.value == current_location_caption)
		{
			this.value = "";
		}
	})

	$('.personalize_map').bind('reset', function()
	{
		resetMap();
	});

	$('.personalize_map').submit(function()
	{
		var address = $('#location').val();
		var country = $('#country').val();
	
		$.cookie('personalize_map_location', address);
		$.cookie('personalize_map_country', country);
	
		if(address.toLowerCase() == current_location_caption.toLowerCase())
		{
			geoLocate();
		}
		else
		{
			getCoordinates(address, country, centerMap);
		}
	
		return false;
	});

	$('.infowindow a').live('click', function()
	{
		if(map) {
			$.cookie('map_zoom', map.getZoom());
			$.cookie('map_center_lat', map.getCenter().lat());
			$.cookie('map_center_lng', map.getCenter().lng());
			$.cookie('map_info_window', openInfoWindow);
		}
	})
});

function loadMap()
{
	if(!map && $('#googlemap').length) {
		//load google maps api
		var e = document.createElement("script");
		e.type = "text/javascript";
		e.src = "https://maps.googleapis.com/maps/api/js?sensor=false&language="+language+"&callback=initializeMap";
		document.body.appendChild(e);
	}
}

function resetMap()
{
	map_center = new google.maps.LatLng(map_default_center_lat, map_default_center_lng);
	map.setCenter(map_center);
	map.setZoom(map_default_zoom);

	if(location_marker)
		location_marker.setMap(null);

	if(openInfoWindow)
		events[openInfoWindow].infoWindow.close();
}

function getCoordinates(address, country, callback)
{
	$.getJSON("/tickets/get_cooridnates_of_address/", { address: address+","+country }, function(data)
	{
		if(typeof(callback) == "function")
		{
			callback(data, (address ? true : false));
		}
	});
}


var map = null;
var openInfoWindow = false;
var location_marker = false;
var mapOptions = null;
var pin_icon = false;
var pin_icon_past = false;

function initializeMap() 
{ 
	if($.cookie('map_zoom') && $.cookie('map_center_lat'))
	{
		map_zoom = $.cookie('map_zoom')*1;
		map_center = new google.maps.LatLng($.cookie('map_center_lat'), $.cookie('map_center_lng'));
		$.cookie('map_zoom', null);
		$.cookie('map_center_lat', null);
		$.cookie('map_center_lng', null);
	} else {
		map_center = new google.maps.LatLng(map_default_center_lat, map_default_center_lng);
		map_zoom = map_default_zoom;
	}
	
	mapOptions = {
		zoom: map_zoom,
		panControl: false,
		center: map_center,
		mapTypeId: google.maps.MapTypeId.ROADMAP
	};
	
	pin_icon = (typeof(pin_icon_path) != "undefined" && pin_icon_path) ? pin_icon_path : "/custom/designs/eoft/media/eoft_pin.png";
	pin_icon_past = (typeof(pin_icon_past_path) != "undefined" && pin_icon_past_path) ? pin_icon_past_path : "/custom/designs/eoft/media/eoft_pin_past.png";
	
  	map = new google.maps.Map(document.getElementById("googlemap"), mapOptions);

	for(var i in events)
	{
		var event = events[i];
		
		var markerpos = new google.maps.LatLng(parseFloat(event.lng), parseFloat(event.lat));
		var text = event.loc + ', ' + event.city;
		
		var marker_pin_icon = pin_icon;
		
		if(event.dates[event.dates.length-1].past == true)
		{
			marker_pin_icon = pin_icon_past;
		}
		
		markerOptions = {
			'map': map,
			'position': markerpos,
			'title': text,
			'icon': marker_pin_icon,
			'index': i
		};
		
		events[i].marker = new google.maps.Marker(markerOptions);
		
		google.maps.event.addListener(events[i].marker, 'click', function() 
		{	
			var event = events[this.index];
			var text = '<h3>' + event.loc + ', ' + event.city + '</h3>';
			text += '<ul>';
			
			var subtext = "";
			
			if(event.dates[event.dates.length-1].past == false)
			{
				for(var i in event.dates) {
					var date = event.dates[i];

					if(!date.past)
					{
						if(event.external && event.external.name && event.external.url)
						{
							subtext = "<small>Tickets via "+event.external.name+".</small>";
							text += '<li>' + date.date + '<a target="_blank" href="'+event.external.url+'">'+details_link_caption+' &raquo;</a></li>'
						}
						else
						{
							text += '<li>' + date.date + '<a href="' + base_path + '/tickets/details/' + date.id + '">'+details_link_caption+' &raquo;</a></li>'
						}
					}
				}
				text += '</ul>';

				text += subtext;
			}
			else
			{
				text += "The event has already passed.";
			}
		
			
			if(openInfoWindow)
				events[openInfoWindow].infoWindow.close();
			
			if(!events[this.index].infoWindow)
			{
				events[this.index].infoWindow = new google.maps.InfoWindow({
					'content': '<div class="infowindow">' + text + '</div>',
					'maxWidth': 200
				});
			}
			
			events[this.index].infoWindow.open(map, this);
			openInfoWindow = this.index;
		});
		
		if($.cookie('map_info_window'))
		{
			if(i == $.cookie('map_info_window'))
			{
				my_id = $.cookie('map_info_window');
				google.maps.event.trigger(events[my_id].marker, 'click');
				$.cookie('map_info_window', null);
			}
		}
	}
	
	// try to use the geolocation api
	geoLocate();
}

function geoLocate()
{
	if(navigator.geolocation)
	{
		navigator.geolocation.getCurrentPosition(function(position)
		{
			centerMap([position.coords.longitude, position.coords.latitude], true, true);
		})
	}
}

function centerMap(latlong, zoom, geolocation)
{
	if(geolocation)
	{
		$('#location').val(current_location_caption);
	}
	
	
	if(latlong)
	{
		var googlelatlng = new google.maps.LatLng(latlong[1], latlong[0]);
		map.setCenter(googlelatlng);
		
		if(location_marker)
			location_marker.setMap(null);
			
		if(zoom)
		{
			map.setZoom(8);

			setTimeout(function()
			{
				markerOptions = {
					'map': map,
					'position': googlelatlng,
					'animation': google.maps.Animation.DROP,
					'icon': install_path+"/modules/tickets/media/pin_you.png",
					'zIndex': 5000
				};

				location_marker = new google.maps.Marker(markerOptions);
			}, 500);
		}
		else
		{
			map.setZoom(mapOptions.zoom);
		}
	}
}
