﻿var layers =[];
var map;

$(document).ready(function()
{
	if (!GBrowserIsCompatible())
	{
		alert("Sorry, the Google Maps API is not compatible with this browser");
		return null;
	}

	$('#message_bar').displayMessage({
		message       : 'Site under development',
		background    : '#111111',
		color         : '#FFFFFF',
		speed         : 'fast',
		skin          : 'plain',
		position      : 'absolute',
		autohide      : true
	});

	//don't allow caching to be used
	$.ajaxSetup({cache: false});

	map = new GMap2(document.getElementById("map"));

	map.enableScrollWheelZoom();

	map.addControl(new GLargeMapControl());

	map.removeMapType(G_NORMAL_MAP);
	map.removeMapType(G_SATELLITE_MAP);
	map.removeMapType(G_HYBRID_MAP);

	map.addMapType(G_HYBRID_MAP);
	map.addMapType(G_SATELLITE_MAP);
	map.addMapType(G_NORMAL_MAP);
	map.addMapType(G_PHYSICAL_MAP);
	map.addMapType(G_SATELLITE_3D_MAP);
	map.setMapType(G_SATELLITE_MAP);

	// Enable the additional map types within
	// // the map type collection
	//map.enableRotation();

	var mapControl = new GMapTypeControl();
	map.addControl(mapControl);

	map.addControl(new TextualZoomControl());

	map.setCenter(new GLatLng(52.469397000000001, 5.5096439999999998), 7);

	SelectTracks();

	//Preventing click event with jQuery drag and drop
	//http://stackoverflow.com/questions/1771627/preventing-click-event-with-jquery-drag-and-drop

	//$('#note').draggable();
	/*
	$('#trackmenubutton').draggable({
	start: function(event, ui) {
			ui.helper.bind("click.prevent",
				function(event) { event.preventDefault(); });
		},
	stop: function(event, ui) {
	  setTimeout(function(){ui.helper.unbind("click.prevent");}, 300);
	}
	});*/

	if (ReadCookie('notehidden') == undefined)
	{
		$('#note').show();
	}

	$('#note').click(function()
	{
		$(this).hide();
		var days = 365;
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "expires=" + date.toGMTString();
		document.cookie = 'notehidden=1; ' + expires + '; path=/'
	});

	$('#clearbutton').click(function()
	{	
		FillDatePickers();
		$('#searchfield').val('').focus();
		LoadTracks('', '', false, '', '');		
		return false;
	});

	$('#searchfield').keyup(function (e)
	{
		var searchfield = $.trim($('#searchfield').val().toLowerCase());
		if (e.which == '13') 
		{
			e.preventDefault();
		}
		LoadTracks('', searchfield, false, '', '');
		return true;
	});
  
	$('#closemenulink').click(function()
	{
		$('#trackmenu').hide();
		$('#trackmenubutton').show();
	});

	$('#trackmenubutton').click(function()
	{
		$('#trackmenu').show();
		$('#trackmenubutton').hide();
	});

	$('#trackmenurefresh').click(function()
	{
		$("input.checkboxlink:checked").attr('checked', false).triggerHandler('click');
	});

	$('select#minDate, select#maxDate').change(function()
	{
		var searchfield = $.trim($('#searchfield').val().toLowerCase());
		var minDate = $('select#minDate').val();
		var maxDate = $('select#maxDate').val();		
		LoadTracks('', searchfield, false, minDate, maxDate);
	});
	
	FillDatePickers();
	
});
//end of document.ready

function LoadTracks(trackdate, tracktitle, select, mindate, maxdate)
{
	var searchParams = '';
	if (trackdate != '')
	{
		if (searchParams != '')
		{
			searchParams += "&trackdate=" + trackdate;
		}
		else
		{
			searchParams += "?trackdate=" + trackdate;
		}		
	}
	
	if (tracktitle != '')
	{
		if (searchParams != '')
		{
			searchParams += "&tracktitle=" + tracktitle;
		}
		else
		{
			searchParams += "?tracktitle=" + tracktitle;
		}
	}
	
	if (mindate != '')
	{
		if (searchParams != '')
		{
			searchParams += "&mindate=" + mindate;
		}
		else		
		{
			searchParams += "?mindate=" + mindate;
		}
	}
	
	if (maxdate != '')
	{
		if (searchParams != '')
		{
			searchParams += "&maxdate=" + maxdate;
		}
		else		
		{
			searchParams += "?maxdate=" + maxdate;
		}
	}
	
	$("#sortable").empty();
	$('#searchresponse').empty();

	$.getJSON('/filelist.php' + searchParams, function(data)
	{
		var count = 0;
		$.each(data, function(i, row) 
		{
			var newhead = '';
			newhead += '<div class="sectionhead">';
			newhead += '<div class="sectionheadtitle" selected="false">';
			newhead += '<img class="bullet" src="/images/icons/bullet_toggle_plus.png">' + row.tracktype + ' <small>(' + row.count + ')</small></div>';
			newhead += '<div class="section" style="display: none;"><div class="sectiontracks">';
			$.each(row.tracks, function(i2, row2)
			{
				count++;
				var infoBlock = '';
				infoBlock += 'onmouseover="return overlib(\'<br/>';
				infoBlock += '<img src=""/images/icons/map.png""/> ' + row2.file + '<br/><br/>';
				infoBlock += '<img src=""/images/icons/date.png""/>&nbsp;<strong>Date:</strong> ' + row2.date + '<br/><br/>';
				infoBlock += '<img src=""/images/icon_kml_med.gif"" alt="" ""/>&nbsp;<strong><a href=""' + row2.path + '/' + row2.file + '"">Download KML</a></strong><br/><br/>';
				infoBlock += '';
				infoBlock += '\', WIDTH, 500, DELAY, 10, MOUSEOFF, STICKY, CLOSECLICK, TIMEOUT, 1500, CAPTION, \'' + row2.title.replace(/\'/gi, '\'') + '\');"';
				infoBlock += ' onmouseout=""return nd();""';
				infoBlock += ' onfocus=""this.blur()"" ';

				newhead += '<div class="track" trackname="' + row2.path + '/' + row2.file + '">';
				newhead += '<input class="checkboxlink" type="checkbox" />';
				newhead += '<a class="menulink" href="javascript:void(0);" title="" ' + infoBlock.replace(/\"\"/gi, '&quot;') + '>' + row2.date + ' ' + row2.title.substring(0, 30) + '</a>';
				newhead += '</div>';
			});
			newhead += '</div></div></div>';
			$(newhead).appendTo($("#sortable"));			
		});
		
		var html = 'Found ' + count + ' matches';
		$('#searchresponse').html(html);

		ApplyTrackMenuLayout();

		if (select)
		{
			$("input.checkboxlink").attr('checked', true); //.triggerHandler('click');
			$("input.checkboxlink:checked").triggerHandler('click');
		}
	});
}

function SelectTracks()
{
	var searchTerm = GetPathstring('select', '') + GetPathstring('track', '');

	if (searchTerm != '')
	{
		$('#searchfield').val(searchTerm);
		LoadTracks(searchTerm, '', true, '', '');
	}else
	{
		LoadTracks('', '', false, '', '');
	}
}

var monthName = new Array(12);
monthName[0]="Jan";
monthName[1]="Feb";
monthName[2]="Maa";
monthName[3]="Apr";
monthName[4]="Mei";
monthName[5]="Jun";
monthName[6]="Jul";
monthName[7]="Aug";
monthName[8]="Sep";
monthName[9]="Okt";
monthName[10]="Nov";
monthName[11]="Dec";

function ZeroPad(num, places) 
{
	var zero = places - num.toString().length + 1;
	return Array(+(zero > 0 && zero)).join("0") + num;
}

function FillDatePickers()
{
	$('select#minDate').empty();
	$('select#maxDate').empty();

	var d = new Date();
	var baseYear = 2005;
	var endYear = d.getFullYear();
	var endMonth = d.getMonth() + 2;
	var currentDateValue = endYear + '' + ZeroPad(endMonth, 2) + '01';
	for (var year = baseYear; year <= endYear; year++)
	{			
		var yearlabel = year;
		$('select#minDate').append('<optgroup label="' + yearlabel + '">');
		$('select#maxDate').append('<optgroup label="' + yearlabel + '">');
		for (var month = 1; month <= 12; month++)
		{
			var datestringValue = year + '' + ZeroPad(month, 2) + '01';
			var datestringText = monthName[month-1] + ' ' + year;
			
			if (year != endYear || (year == endYear && month <= endMonth))
			{			
				$('select#minDate').append('<option value="' + datestringValue + '">' + datestringText + '</option>');
				$('select#maxDate').append('<option value="' + datestringValue + '">' + datestringText + '</option>');
			}
		}
		$('select#minDate').append('</optgroup>');
		$('select#maxDate').append('</optgroup>');		
	}
	$('select#maxDate').val(currentDateValue);
}

function GetBaseURL() 
{
	var url = location.href;  // entire url including querystring - also: window.location.href;
	var baseURL = url.substring(0, url.indexOf('/', 14));
	return baseURL;
}

function ApplyTrackMenuLayout()
{
	//Apply colors
	$('div.sectionheadtitle:even').css('background-color', '#FFFFCC');
	$('div.sectionheadtitle:odd').css('background-color', '#CCFFCC');
	$('div.track:even').css('background-color', '#E8E8E8');
	$('div.track:odd').css('background-color', '#D0D0D0');

	//hide all sections by default
	$('.sectionheadtitle').next('div.section').hide();

	$('.sectionheadtitle').click(function()
	{
		if ($(this).find('img.bullet').attr('src') == '/images/icons/bullet_toggle_minus.png')
		{
			$(this).find('img.bullet').attr('src', '/images/icons/bullet_toggle_plus.png');
			$(this).attr('selected', 'false');
		} else 
		{
			$(this).find('img.bullet').attr('src', '/images/icons/bullet_toggle_minus.png');
			$(this).attr('selected', 'true');
		}
			
		//hide all sections
		$('.sectionheadtitle').next('div.section:visible').hide();
		$('.sectionheadtitle').find('img.bullet').attr('src', '/images/icons/bullet_toggle_plus.png');

		//enable the selected section
		if ( $(this).attr('selected') == 'true')
		{
			$('div.section:visible').hide();
			$(this).find('img.bullet').attr('src', '/images/icons/bullet_toggle_minus.png');
			$(this).next('div.section:hidden').slideDown('fast').siblings('div.section:visible').slideUp('fast');
		}
	});

	$('.checkboxlink').click(function()
	{
		var fullTrackUrl = GetBaseURL() + '/' + $(this).parent().attr('trackname');
		ToggleMap(fullTrackUrl, true);
	});
	
	$('.menulink').click(function()
	{
		var checkbox = $(this).prev();
		SwitchCheckbox(checkbox);
		var fullTrackUrl = GetBaseURL() + '/' + $(this).parent().attr('trackname');
		ToggleMap(fullTrackUrl, true);
	});

	/* Apply tooltips */
	/*$('.menulink').cluetip({
		splitTitle: '|',
		cluetipClass: 'default',
		dropShadow: false,
		width: 400,
		height: 'auto',
		cluezIndex: 100,
		sticky: true,
		closeText: 'Sluiten',
		closePosition: 'top',
		delayedClose: 4000
	}); */
}

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;
}

/**
* Delay for a number of milliseconds
*/
function Sleep(delay)
{
	var start = new Date().getTime();
	while (new Date().getTime() < start + delay);
}

function ToggleMap(trackurl, centerLayer)
{
	//cache the geoXml object
	var geoXml;
	var id = trackurl;
	if (layers[id] == null)
	{
		geoXml = new GGeoXml(trackurl);
		layers[id] = geoXml;
			
   		//make the new layer visible
    	map.addOverlay(geoXml);

    	if(centerLayer)
    	{
			CenterOnLayer(id);
		}
	}else
	{
		map.removeOverlay(layers[id]);   	
		layers[id] = null;
	}
}

function CenterOnLayer(id)
{
    if (layers[id] != null)
    {
		var geoXml = layers[id];

		//auto center and zoom
		geoXml.gotoDefaultViewport(map);
    }
    return true;
}

function SwitchCheckbox(elem)
{
	if (elem.attr('checked') == true)
	{
		elem.removeAttr('checked');
	} else {
		elem.attr('checked', 'true');
	}
}

/* function NewButtonDiv(map, container, name, id)
{
	var newDiv = document.createElement("div");
	TextualZoomControl.prototype.setButtonStyle_(newDiv);
	container.appendChild(newDiv);
	newDiv.appendChild(document.createTextNode(name));
	GEvent.addDomListener(newDiv, "click", function() 
	{
		map.zoomOut();
	});
}*/

function CenterEurope()
{
	map.setCenter(new GLatLng(54, 5.5), 4);
}

function TextualZoomControl() {
}

function GetPathstring(key, default_)
{
	if (default_ == null) default_="";
	//key = key.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
	var regex = new RegExp("\/" + key + "\/(.*$)");
	var qs = regex.exec(window.location.href);
	if(qs == null)
		return default_;
	else
		return qs[1];
}

function GetQuerystring(key, default_)
{
	if (default_==null) default_=""; 
	key = key.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
	var regex = new RegExp("[\\?&]"+key+"=([^&#]*)");
	var qs = regex.exec(window.location.href);
	if(qs == null)
		return default_;
	else
		return qs[1];
}

// To "subclass" the GControl, we set the prototype object to
// an instance of the GControl object
TextualZoomControl.prototype = new GControl();

// Creates a one DIV for each of the buttons and places them in a container
// DIV which is returned as our control element. We add the control to
// to the map container and return the element for the map class to
// position properly.
TextualZoomControl.prototype.initialize = function(map)
{
	var container = document.createElement("div");

	var centerGL = document.createElement("div");
	this.setButtonStyle_(centerGL);
	container.appendChild(centerGL);
	centerGL.appendChild(document.createTextNode("Zoom Veluwe"));
	GEvent.addDomListener(centerGL, "click", function() {
		map.setCenter(new GLatLng(52.08, 5.88), 11);
	});

	var centerGL = document.createElement("div");
	this.setButtonStyle_(centerGL);
	container.appendChild(centerGL);
	centerGL.appendChild(document.createTextNode("Zoom Gelderland"));
	GEvent.addDomListener(centerGL, "click", function() {
		map.setCenter(new GLatLng(52.1, 6.1), 9);
	});

	var centerNL = document.createElement("div");
	this.setButtonStyle_(centerNL);
	container.appendChild(centerNL);
	centerNL.appendChild(document.createTextNode("Zoom Benelux"));
	GEvent.addDomListener(centerNL, "click", function() {
		map.setCenter(new GLatLng(51.5, 5.55), 7);
	});

	var centerEurope = document.createElement("div");
	this.setButtonStyle_(centerEurope);
	container.appendChild(centerEurope);
	centerEurope.appendChild(document.createTextNode("Zoom Europa"));
	GEvent.addDomListener(centerEurope, "click", function() {
		CenterEurope();
	});

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

TextualZoomControl.prototype.getDefaultPosition = function()
{
  return new GControlPosition(G_ANCHOR_BOTTOM_RIGHT, new GSize(7, 7));
}

// Sets the proper CSS for the given button element.
TextualZoomControl.prototype.setButtonStyle_ = function(button)
{
  button.style.textDecoration = "underline";
  button.style.color = "black";
  button.style.backgroundColor = "white";
  button.style.font = "small Verdana";
  button.style.border = "2px solid black";
  button.style.padding = "3px";
  button.style.marginBottom = "3px";
  button.style.textAlign = "right";
  button.style.width = "10em";
  button.style.cursor = "pointer";
}

