window.onunload = GUnload;

$(window).ready(function()
{
	Synergy.Options = {
		mapContainer : $('#wrapperContent, #leftSideBar, #rightSideBar'),
		mapCanvas : $('#mapCanvas'),
		minMapHeight : 508,
		filterContainer : $('#filters'),
		markerTypeArray : [ 'home', 'community' ],
		markerFeedUrl : '/json/suggestionList/',
		extraFilterUrl : '/json/likeFilters',
		filterTypeArray : [ 'all', 'new', '5 star' ],
		tileHostName : 'maps.letssaveenergy.com.au',
		tileHostNumber : 4,
		tileVersion : '8',
		boundry : new google.maps.LatLngBounds(new google.maps.LatLng(-34.819441, 114.88678), new google.maps.LatLng(-12.478349, 130.80542)),
		center : new google.maps.LatLng(-31.953573, 115.858619),
		defaultZoomLevel : 10,
		minZoomLevel : 7,
		maxZoomLevel : 10,
		animateZoomLevel : 10,
		advancedPointClass : Synergy.Suggestion,
		// This is the amount of metres moved in each step
		animationTravelSpeed : 2500,
		// The amount of ms spent after the popup has opened
		animationDelay : 10000,
		// The amount of idle ms before the animation restarts
		animationTimeout : 10000,

		groupedPinCalloutTitle : 'Energy Saving Tips'

	};
	
	if( $.browser.msie )
	{
		Synergy.Options.animationTravelSpeed = 5000;
	}

	// Overload so it works with both synergy sites.
	Synergy.Options.toolbox = {};
	Synergy.Options.toolbox.setDefault = function(){};

	if( $.browser.msie ) {
		Synergy.Options.animationTravelSpeed = 5000
	}

	Synergy.App.activateInterface();

	Synergy.App.setupResizer();

	Synergy.Options.map = new Synergy.Map();
	Synergy.Options.map.enableScrollWheelZoom();
	Synergy.Options.map.setCenter(Synergy.Options.center, Synergy.Options.defaultZoomLevel);
	Synergy.Options.map.enableContinuousZoom();

	setupTypes();

	Synergy.App.setupMapControls();

	Synergy.MapAnimation.startTimer();

	Synergy.App.removeFooterShadow();
	Synergy.App.addShadows();
	Synergy.App.setupOverlays();

	showStartingMessages();
//	showWelcomeMessage();
//	showLandingSurvey();

	updateDisplay(function()
	{
		$.history.init(Synergy.App.centerOnSuggestion);
	});
	updateTagCloud();

	setupShowMe();
	setupSearch();

});

function setupTypes()
{
	var baseIcon = new GIcon(G_DEFAULT_ICON);
	baseIcon.iconSize = new GSize(33, 42);
	baseIcon.shadowSize = new GSize(0, 0);

	$.each(Synergy.Options.markerTypeArray, function( counter, markerTypeName )
	{
		var imgType = '.png';
		if( $.browser.msie && $.browser.version == 6 )
		{
			imgType = '.gif';
		}
		var newIcon = new GIcon(baseIcon, '/images/icons/' + markerTypeName + imgType);

		Synergy.Options.map.addMarkerType(markerTypeName, newIcon);
	});
}

function setupShowMe()
{
	$('#leftSideBar .filter li a').click( function()
	{
		$('#leftSideBar .tagCloud a.tagSelected').removeClass('tagSelected');
		$('#leftSideBar .filter li.active').removeClass('active');
		$(this).parent().addClass('active');

		updateDisplay();

		return false;
	});
}

function setupSearch()
{
	var searchbox = $('#searchGo');
	
	searchbox.click(function()
	{
		updateDisplay()
		return false;
	});

	searchbox.keyup(function( e )
	{
		if( e.keyCode == 13 ) {
			updateDisplay();
		}
	});
}

function updateDisplay(callback)
{
	if( $('#leftSideBar .filter li.active').length > 0 )
	{
		var mode = 'all';
	
		switch( $('#leftSideBar .filter li.active a').attr('id') )
		{
			case 'latestTips':
				mode = 'new';
				break;
	
			case 'topTips':
				mode = '5 star';
				break;
		}
	}
	else
	{
		var mode = 'theme';
		
	}
	
	//var theme = ;

	var filterData = {
			listType : 'pins',
			mode : mode
		};

	if( mode == 'theme' )
	{
		filterData.theme = $('#leftSideBar .tagCloud a.tagSelected').attr('href').substring(24);
	}
	
	var searchbox = $('#search');
	if( searchbox.val() != '' && searchbox.val() != searchbox.attr('title')) {
		filterData.search = searchbox.val();
	}

	Synergy.App.populateData(filterData, callback);
}

function updateTagCloud()
{

	
	$('.tagCloud a').each( function()
	{
		var obj = $(this);
		obj.click( function()
		{
			$('#leftSideBar .tagCloud a.tagSelected').removeClass('tagSelected');
			$('#leftSideBar .filter li.active').removeClass('active');
			obj.addClass('tagSelected');
			updateDisplay();
			return false;
		});
	});
}


function showWelcomeMessage()
{
	if( readCookie('showWelcome') != 'false' ) {
		$("#welcome").appendTo('body');
		show();

		createCookie('showWelcome', 'false', 365);

		// Setup buttons in Welcome Window
		$("#welcome #welcomeBrowseButton").click(function( e )
		{
			e.preventDefault();
			Synergy.App.closeWelcomeMessage();
		});
	}

	function createCookie( name, value, days )
	{
		if( days ) {
			var date = new Date();
			date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
			var expires = "; expires=" + date.toGMTString();
		}
		else {
			var expires = "";
		}
		document.cookie = name + "=" + value + expires + "; path=/";
	}

	function readCookie( name )
	{
		var nameEQ = name + "=";
		var ca = document.cookie.split(';');
		for( var i = 0; i < ca.length; i++ ) {
			var c = ca[i];
			while (c.charAt(0) == ' ') {
				c = c.substring(1, c.length);
			}
			if( c.indexOf(nameEQ) == 0 ) {
				return c.substring(nameEQ.length, c.length);
			}
		}
		return null;
	}

	function show()
	{
		var api = $('#welcome').data("overlay");
		api.load();
	}
}


function showLandingSurvey( hash )
{		
	if( readCookie('showLandingSurvey') != 'false' ) {
		var hash = window.location.hash;
		
		croppedHash = hash.replace('#','');
		
		$landingSurveyFormFrame = '<iframe id="landingSurveyIFrame" name="landingSurveyIFrame" src="/html/landing_survey?simple&hashKey='+croppedHash+'" width="440" height="515" frameborder="0"><a href="html/landing_survey?simple">Landing Survey</a></iframe>';
		
		$('#landingSurveyDiv').append($landingSurveyFormFrame);
		
		$('#landingSurveyDiv').overlay( {
			load : false,
			mask : '#000000',
			left : 'center',
			oneInstance : false,
			top : 'center',
			onClose: function()
			{

			}
		});	
		
		var api = $('#landingSurveyDiv').data("overlay");
		api.load();
		
		createCookie('showLandingSurvey', 'false', 365);

		/**
		 * TODO: setup buttons in landing survey popup if necessary
		 */
	}
	
	function createCookie( name, value, days )
	{
		if( days ) {
			var date = new Date();
			date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
			var expires = "; expires=" + date.toGMTString();
		}
		else {
			var expires = "";
		}
		document.cookie = name + "=" + value + expires + "; path=/";
	}

	function readCookie( name )
	{
		var nameEQ = name + "=";
		var ca = document.cookie.split(';');
		for( var i = 0; i < ca.length; i++ ) {
			var c = ca[i];
			while (c.charAt(0) == ' ') {
				c = c.substring(1, c.length);
			}
			if( c.indexOf(nameEQ) == 0 ) {
				return c.substring(nameEQ.length, c.length);
			}
		}
		return null;
	}
}

function showStartingMessages()
{
	var hash = window.location.hash;
	//if hash = #000000, overwrite/delete existing cookie
	if(hash == "#000000")
	{
		document.cookie = 'showLandingSurvey' + '=; expires=Thu, 01-Jan-70 00:00:01 GMT;';
	}
	if(isValidHash( hash )){
		showLandingSurvey(hash);
	} else {
		showWelcomeMessage();
	}
}

function isValidHash( hash )
{	
	//Array of valid hashes
	var validHashes = ['#s10811','#s20811','#s30811'];
	
	for(var i = 0; i < validHashes.length ; i++){
		if(validHashes[i] === hash) {
			return true;
		}
	}
	return false;
}

