var GAFFALIVE = function() {
	GAFFALIVE.tabs.init();
	GAFFALIVE.detsker.init();
	GAFFALIVE.recommends.init();
	GAFFALIVE.planahead.init();
}

GAFFALIVE.cookie_settings = {
	expires: 14,
	domain: window.location.host.replace('www.', '')
};

GAFFALIVE.cookie_settings_session = {
	domain: window.location.host.replace('www.', '')
};

GAFFALIVE.tabs = {
	current: "#planahead",
	init: function() {
		$("#livetabs a.tab").click(function() {
			location.hash = $(this).attr('href');
			GAFFALIVE.tabs.watchUrl();
			return false;
		});
		GAFFALIVE.tabs.watchUrl();
		setInterval(GAFFALIVE.tabs.watchUrl, 1000);
	},
	watchUrl: function() {
		if(!location.hash || location.hash == GAFFALIVE.tabs.current){
			return false;
		}
		var tab_name = "planahead";
		var hash_parts = location.hash.split("/");
		switch(hash_parts[0]) {
			case '#kort':
				tab_name = "map";
				if(!GAFFALIVE.map.initialized) {
					google.load("maps", "2", {
						callback : function() {
							$.getScript('/js/markerclusterer_packed.js', function() {
								GAFFALIVE.map.init();
							});
						}
					});
				} else {
					GAFFALIVE.map.init();
				}
				break;
			case '#forside':
				tab_name = "planahead";
				GAFFALIVE.detsker.refresh();
				break;
			case '#kalender':
				tab_name = "calendar";
				GAFFALIVE.calendar.month = hash_parts[1];
				GAFFALIVE.calendar.year = hash_parts[2];
				GAFFALIVE.calendar.init();
				break;
			default:
				return false;
				break;
		}
		GAFFALIVE.tabs.current = location.hash;
		$("#livetabs a.tab").removeClass('active')
			.filter("#" + tab_name + "-tab").addClass('active').blur();
		$('.tabcontent').hide().filter('#' + tab_name).show();

		return true;
	}
};

GAFFALIVE.filterState = {
	area: function(newArea) {
		if(typeof newArea != 'undefined') {
			$.cookie('live_area', newArea, GAFFALIVE.cookie_settings);
			return;
		}
		area = $.cookie('live_area');
		if(!area || !GAFFALIVE.map.areas[area]) {
			area = 'all';
		}
		return area;
	},
	interval: function(newInterval) {
		if(typeof newInterval != 'undefined') {
			$.cookie('live_interval', newInterval, GAFFALIVE.cookie_settings);
			return;
		}
		interval = $.cookie('live_interval');
		if(!interval) {
			interval = '7';
		}
		return interval;
	}
};

GAFFALIVE.calendar = {
	month: false,
	year: false,
	init: function(){
		if(!GAFFALIVE.calendar.month) {
			GAFFALIVE.calendar.month = new Date().getMonth() + 1;
		}
		if(!GAFFALIVE.calendar.year) {
			GAFFALIVE.calendar.year = new Date().getFullYear();
		}

		var areaSelect = $("#calendar_select");
		var areaSelectOptions = $('#calendar_select option');
		if (GAFFALIVE.filterState.area() != areaSelect.val()){
			areaSelect.val(GAFFALIVE.filterState.area());
			areaSelect.change();
		}
		areaSelect.val(GAFFALIVE.filterState.area());
		
		month = GAFFALIVE.calendar.month;
		year = GAFFALIVE.calendar.year;
		if(month != $("#cal_currentmonth").val() || year != $("#cal_currentyear").val()) {
			location.hash = '#kalender/' + month + '/' + year;
			$("#calendar").load(
				"/live/ajaxCalendar/"+ month +"/"+  year, 
				function() {
					setupAreaSelect();
				}
			);
			return;
		}

		setupAreaSelect();
		function setupAreaSelect(){
			var areaSelect = $("#calendar_select");
			var areaSelectOptions = $('#calendar_select option');
			if (areaSelectOptions.length == 0){
				$.each(GAFFALIVE.map.areas, function(key, val) {
					areaSelect.append($('<option />').val(key).text(val['name']));
				});
				areaSelect.val(GAFFALIVE.filterState.area());
			}
			areaSelect.change(function() {
				GAFFALIVE.filterState.area($(this).val());
				GAFFALIVE.detsker.refresh();
				$("#calendar" + " .ajaxload").fadeIn(200);
				$("#calendar").load(
					"/live/ajaxCalendar/"+ month +"/"+ year, 
					function() {setupAreaSelect();}
				);
			});
		}
	},
	changeMonth: function(month, year, caller) {
		$("#livecal_nav_months a").removeClass('active').filter('#' + month + '_' + year).addClass('active');
		$(caller).blur();
		$("#calendar .ajaxload").fadeIn(200);
		GAFFALIVE.tabs.watchUrl();
	}
}

GAFFALIVE.map = {
	areas: areas,
	initialized: false,
	init: function() {
		var markers = [];
		if(GAFFALIVE.map.initialized || !GBrowserIsCompatible()) {
			return false;
		}

		// genereret med http://www.powerhut.co.uk/googlemaps/custom_markers_v2_API.php
		var venueMarker = new GIcon();
		venueMarker.image = 'http://static.gaffa.com/images/newdesign/live/gmarker/image.png';
		venueMarker.image_highlight = 'http://static.gaffa.com/images/newdesign/live/gmarker/image_highlight.png';
		venueMarker.shadow = 'http://static.gaffa.com/images/newdesign/live/gmarker/shadow.png';
		venueMarker.iconSize = new GSize(19,18);
		venueMarker.shadowSize = new GSize(28,18);
		venueMarker.iconAnchor = new GPoint(10,18);
		venueMarker.infoWindowAnchor = new GPoint(10,0);
		venueMarker.printImage = 'http://static.gaffa.com/images/newdesign/live/gmarker/printImage.gif';
		venueMarker.mozPrintImage = 'http://static.gaffa.com/images/newdesign/live/gmarker/mozPrintImage.gif';
		venueMarker.printShadow = 'http://static.gaffa.com/images/newdesign/live/gmarker/printShadow.gif';
		venueMarker.transparent = 'http://static.gaffa.com/images/newdesign/live/gmarker/transparent.png';
		venueMarker.imageMap = [9,0,11,1,12,2,13,3,14,4,14,5,14,6,14,7,14,8,14,9,13,10,13,11,17,12,18,13,17,14,15,15,13,16,11,17,3,17,2,16,1,15,2,14,1,13,1,12,0,11,0,10,0,9,0,8,0,7,0,6,0,5,0,4,0,3,1,2,2,1,4,0];

		
		var map = new GMap2(document.getElementById("maparea"));
		map.enableScrollWheelZoom();
		map.disableDoubleClickZoom();
		map.addControl(new GSmallZoomControl3D());
		new GKeyboardHandler(map);
		area = GAFFALIVE.map.areas[GAFFALIVE.filterState.area()];
		center = new GLatLng(area['mapCenter'][0], area['mapCenter'][1]);
		zoom = area['mapZoom'];

		map.setCenter(center, zoom);
		var markerClusterer = null;
		
		function showVenueOverlay(venue_div) {
			var marker = venue_div.data('marker');
			var page = $("#mapvenues").data('page');
			map.savePosition();
			map.setCenter(marker.getLatLng(), Math.max(map.getZoom(), 13));
			marker.setImage(venueMarker.image_highlight);
			marker.openInfoWindowHtml(venue_div.data('venue').name);
			var ajaxload = $("#mapoptions .ajaxload").fadeIn();

			$('#venue_eventlist').load('/live/ajaxVenueDetails/'+ venue_div.data('venue').id, function(data) {
				function close() {
					try {
						marker.setImage(venueMarker.image);
					} catch(e){}
					map.returnToSavedPosition();
					$("#mapvenues").trigger('repaginate', {page: page});
					$('#venue_eventlist').fadeOut();
				}
				$("#map_venuelist_venuedata a#closelist").click(function() {
					try {
						marker.closeInfoWindow();
					} catch(e){}
					close();
					return false;
				});
				GEvent.addListener(map.getInfoWindow(), 'closeclick', close);
				$('#venue_eventlist').fadeIn();
				ajaxload.fadeOut();
			});
		}
		
		function loadMarkers() {
			var ajaxload = $("#mapoptions .ajaxload").fadeIn();

			$.getJSON('/live/ajaxVenueMarkers/'+ new Date().getTime(), null, function(data) {
				markers = [];
				var venuesDiv = $('#mapvenues');
				// venuesDiv.html('<p>Klik på et spillested for at se koncertkalender</p>');
				$.each(data, function(key, venue) {
					// Lav en marker til kortet
					var marker = new GMarker(new GLatLng(venue['lat'], venue['long']), venueMarker);
					markers.push(marker);
					
					// Lav div til venue-listen
					var div = $("<div></div>");
					div.data('marker', marker);
					div.data('venue', venue);
					div.addClass('venue_item');
					venuesDiv.append(div).after($("<div></div>")); // .after() gør 'noget' for IE
					$('<a></a>').html(venue.name).appendTo(div);

					// Highlight af venue i listen og dens marker på kortet
					function highlight() {
						try {
							marker.setImage(venueMarker.image_highlight);
						} catch(error) {
							// markeren var del af et cluster
						}
						div.addClass('highlight');
					}
					function highlightOff() {
						try {
							marker.setImage(venueMarker.image);
						} catch(error) {
							// markeren var del af et cluster
						}
						div.removeClass('highlight');
					}
					div.hover(highlight, highlightOff);
					GEvent.addListener(marker, 'mouseover', function() {
						div.data('timeout', setTimeout(function() {
								venuesDiv.trigger('scroll_to', div);
								highlight();
							}, 200)
						);
					});
					GEvent.addListener(marker, 'mouseout', function() {
						highlightOff();
						if(div.data('timeout')) {
							clearTimeout(div.data('timeout'));
							div.data('timeout', null);
						}
					});
					
					// Visning af venue detaljer ved klik i listen eller på kortet
					div.click(function() { showVenueOverlay(div); });
					GEvent.addListener(marker, 'click', function() {div.trigger("click")});
				});
				if(markerClusterer) {
					markerClusterer.clearMarkers();
				}
				markerClusterer = new MarkerClusterer(map, markers, {
					maxZoom: 8,
					gridSize: 25
				});
				listVisibleVenues();
				ajaxload.fadeOut();
			});
		}
		
		function listVisibleVenues() {
			// console.log("'mapCenter' => array(\"" + map.getCenter().lat() + "\", \"" + map.getCenter().lng() + "\"),");
			// console.log("'mapZoom' => " + map.getZoom() + ",");
			bounds = map.getBounds();
			$('#mapvenues div').each(function() {
				$(this).toggleClass('on_map', bounds.containsLatLng($(this).data('marker').getLatLng()));
			});
			$("#mapvenues").trigger('repaginate', {force: true});
		}
		var venuesPerPage = 21;
		$("#mapvenues").bind('repaginate', function(event, data) {
			if(data && data.page >= 0) {
				page = data.page;
			} else {
				page = $(this).data('page');
			}
			if(data && data.offset) {
				page += data.offset;
			}
			if(page == $(this).data('page') && !data.force) {
				return;
			}
			var on_map = $(this).children('div').hide().filter('.on_map');

			var num_pages = Math.ceil(on_map.length / venuesPerPage);
			page = Math.min(num_pages - 1, page);
			page = Math.max(0, page);

			on_map.slice(page * venuesPerPage, (page + 1) * venuesPerPage)
				.show().removeClass('odd')
				.filter(':odd').addClass('odd');
			$("#mapvenues_nav").find("div#cur_page").html('Side '+ (page + 1));
			$("#mapvenues_nav").find("div#num_pages").html('&nbsp; / ' + Math.max(1, num_pages));
			$(this).data('page', page);
		}).bind('scroll_to', function(event, data) {
			index = $(this).children('div.on_map').index(data);
			var newPage = Math.floor(index / venuesPerPage);
			$(this).trigger('repaginate', {page: newPage});
		}).data('page', 0);
		$("#mapvenues_nav a#prev_page").click(function () {
			$("#mapvenues").trigger("repaginate", {offset: -1});
			$(this).blur();
			return false;
		});
		$("#mapvenues_nav a#next_page").click(function () {
			$("#mapvenues").trigger("repaginate", {offset: 1});
			$(this).blur();
			return false;
		});
		

		GEvent.addListener(map, 'moveend', listVisibleVenues);
		var areaSelect = $('#venues_map_area');
		if (areaSelect.children('option').length == 0){
			$.each(GAFFALIVE.map.areas, function(key, val) {
				var option = $('<option />').val(key).text(val['name']).appendTo(areaSelect);
			});
		}
		areaSelect.change(function() {
			area = GAFFALIVE.map.areas[$(this).val()];
			var newCenter = new GLatLng(area['mapCenter'][0], area['mapCenter'][1]);
			if(!map.getCenter().equals(newCenter) || map.getZoom() != area['mapZoom']) {
				GAFFALIVE.filterState.area($(this).val());
				map.setCenter(newCenter, area['mapZoom']);
			}
		});
		var area = GAFFALIVE.filterState.area();
		areaSelect.val(area);
		
		interval = GAFFALIVE.filterState.interval()
		$('#map_interval a').click(function() {
			GAFFALIVE.filterState.interval($(this).attr('id').split("_")[1]);
			$("a.intervallink").removeClass('active');
			$(this).addClass('active');
			loadMarkers();
			return false;
		});

		loadMarkers();
		$("#map_interval a#mapdays_"+GAFFALIVE.filterState.interval()).addClass('active');
		GAFFALIVE.map.initialized = true;
	}
};

GAFFALIVE.detsker = {
	refresh: function() {
		var contentDiv = $('#detsker_content');
		if (!$.browser.msie){
			contentDiv.fadeTo('fast', 0.0);
		} else {
			contentDiv.html('');
		}
		var rand1 = new Date().getTime();
		contentDiv.parent().css('background', 'white url("/images/newdesign/ajax-loader-search.gif") top center no-repeat');
		contentDiv.load('/live/ajaxDetSker/'+ rand1, function() {
			contentDiv.fadeTo('fast', 1.0);
			contentDiv.parent().css('background', '');
			GAFFALIVE.detsker.setupPaginate();
		});
		$("#detsker_select").val(GAFFALIVE.filterState.area());
		$("#detsker_interval a#days_" + GAFFALIVE.filterState.interval()).addClass('active');
	},
	init: function () {
		var areaSelect = $("#detsker_select");
		$.each(GAFFALIVE.map.areas, function(key, val) {
			 areaSelect.append($('<option />').val(key).text(val['name']));
		});
		areaSelect.change(function() {
			GAFFALIVE.filterState.area($(this).val());
			GAFFALIVE.detsker.refresh();
		});
		areaSelect.val(GAFFALIVE.filterState.area());
		
		$("#detsker_interval a").click(function() {
			GAFFALIVE.filterState.interval($(this).attr('id').split("_")[1]);
			$("a.intervallink").removeClass('active');
			$(this).addClass('active');
			$(this).blur();
			GAFFALIVE.detsker.refresh();
			return false;
		});
		$("#detsker_interval a#days_" + GAFFALIVE.filterState.interval()).addClass('active');
		GAFFALIVE.detsker.setupPaginate();
	},
	setupPaginate:function(){
	 var colums = $('.detsker_page').length;
	 if(colums>1){
	    $('#detsker_pagecontainer').width(182*colums);
	    var paginateLinks ="<div class=\"detsker_pagination\" style=\"clear:both\">";
	    for(var i =1;i<=colums;i++){
		if(i==1){
		paginateLinks += '<a href="" class="selected">'+i+'</a>';
		}else{
		paginateLinks += '<a href="">'+i+'</a>';
		}
	    }
	    paginateLinks +="</div>"

	    $(paginateLinks).children('a').click(function(evt,item){
		$('.detsker_pagination .selected').removeClass('selected');
		$(this).addClass('selected');
		$('#detsker_pagecontainer').animate({left:-182*($(this).text()-1)});
		return false;
	    }).end().prependTo('#detsker_content');

	 }	 
	}
};

GAFFALIVE.recommends = {
	init: function() {
		var anbefalerHref = $.cookie('#box_gaffa_anbefaler-href-new');
		if(anbefalerHref){
			loadPiece(anbefalerHref, "#box_gaffa_anbefaler");
		}
		setupPaginationLinks('#box_gaffa_anbefaler');
	}
};

GAFFALIVE.planahead = {
	init: function() {
		var planaheadHref = $.cookie('#box_plan_ahead-href-new');
		if(planaheadHref){
			loadPiece(planaheadHref, "#box_plan_ahead");
		}
		setupPaginationLinks('#box_plan_ahead');
		setupSortmodeLinks();
		if ($.cookie("live_phsortmode") == null){
			$.cookie("live_phsortmode", "newest", GAFFALIVE.cookie_settings_session);
		}
	}
}

function setupPaginationLinks(divName) {
	var divPaginationLinks = divName+" #pagination a";
	$(divPaginationLinks).click(function(){
		$(divName + " .left").fadeOut(200);
		$(divName + " .right").fadeOut(200);
		$(divName + " .pagecount").fadeOut(200);
		$(divName + " .ajaxload").fadeIn(200);
		//$(divName +" .inner").slideUp(200);
		var thisHref = $(this).attr("href");
		loadPiece(thisHref, divName);
		return false;
	});
}

function setupSortmodeLinks(){
	
	$("#sortmode_newest").click(function(){
		planAheadSort("newest");
		$("#phsortmodes" + " .ajaxload").fadeIn(200);
		$("#box_plan_ahead").load("/live/ajaxPlanahead/", {}, function(){
			setupPaginationLinks("#box_plan_ahead");
			setupSortmodeLinks();
			$(".lbutton").removeClass("lbutton_on");
			$("#sortmode_newest").addClass("lbutton_on");
			$("#phsortmodes" + " .ajaxload").fadeOut(200);
		});
		return false;
	});
	
	$("#sortmode_upcoming").click(function(){
		planAheadSort("upcoming");
		$("#phsortmodes" + " .ajaxload").fadeIn(200);
		$("#box_plan_ahead").load("/live/ajaxPlanahead/", {}, function(){
			setupPaginationLinks("#box_plan_ahead");
			setupSortmodeLinks();
			$(".lbutton").removeClass("lbutton_on");
			$("#sortmode_upcoming").addClass("lbutton_on");
			$("#phsortmodes" + " .ajaxload").fadeOut(200);
		});
		return false;
	});
	$("#sortmode_"+$.cookie("live_phsortmode")).addClass('lbutton_on');

}

function loadPiece(href, divName){
	$(divName).load(href, {}, function(){
		setupPaginationLinks(divName);
		if (divName == "#box_plan_ahead") setupSortmodeLinks();
		$.cookie(divName+'-href-new', href, GAFFALIVE.cookie_settings_session);
	});
}

function planAheadSort(sortmode){
	$.cookie("live_phsortmode", sortmode, GAFFALIVE.cookie_settings_session);
}


