﻿//
//  preload some images
//

btn_ort = [ new Image(), new Image() ];
btn_ort[0].src = "img/map/rightbar/btn_platz.png";
btn_ort[1].src = "img/map/rightbar/btn_platz_a.png";
btn_areal = [ new Image(), new Image() ];
btn_areal[0].src = "img/map/rightbar/btn_bereich.png";
btn_areal[1].src = "img/map/rightbar/btn_bereich_a.png";
btn_strasse = [ new Image(), new Image() ];
btn_strasse[0].src = "img/map/rightbar/btn_verkehr.png";
btn_strasse[1].src = "img/map/rightbar/btn_verkehr_a.png";
btn_geb = [ new Image(), new Image() ];
btn_geb[0].src = "img/map/rightbar/btn_gebaeude.png";
btn_geb[1].src = "img/map/rightbar/btn_gebaeude_a.png";

btn_unsolved = [ new Image(), new Image() ];
btn_unsolved[0].src = "img/map/rightbar/unort_p.png";
btn_unsolved[1].src = "img/map/rightbar/unort.png";
btn_solved = [ new Image(), new Image() ];
btn_solved[0].src = "img/map/rightbar/ort_p.png";
btn_solved[1].src = "img/map/rightbar/ort.png";

suchen_a = new Image();
suchen_a.src = "img/n/header_suchen_a.gif";
suchen_b = new Image();
suchen_b.src = "img/n/header_suchen_b.gif";


var today = getDate();
var mySlideInit = false;
var mySlideInit2 = false;

var slideToRight = false;
var slideToLeft = true;

var fxknopfc = []; 

// timeline anlegen
var timeline_dates = [];
var timeline_dates_steps = 0;
var timeline_center = 0;
var timeline_left;
var timeline_right;
var timeline_diff;
var timeline_active = "";

// calendar
var calendar_active = 0;
var calendar;
calendar = new dynCalendar( 'calendar', 'calendarCallback' );

// filter defaults setzen
var filter = [];
filter['sonst']		 = true;
filter['geb']			 = true;
filter['areal']		 = true;
filter['ort']			 = true;
filter['strasse']	 = true;
filter['from']		 = '0000-00-00';
filter['to']			 = '9999-99-99';
filter['solved']	 = true;
filter['unsolved'] = true;


browser_width = 0;
browser_height = 0;
var rutsche_pos =0;
var pixel_per_tick = 11;

//
//		formular variablen
//

var store_edit_lat 			= "0";
var store_edit_lng 			= "0";
var store_edit_title 		= "";
var store_edit_type 		= "";
var store_edit_datum  		= "";
var store_edit_text   		= "";
var store_edit_kategorien	= new Array;


//
// Sliders for the timeline
//
var mySlideC = [];
var mySlide  = [];
var mySlide2 = [];
var scroll = [];

var userid = -1;

function initGui() {
	
	window.addEvent( 'domready', 
			function( ) {
				// document.getElementById("rutsche").style.width = browser_width+"px";
				
				scroll = new Fx.Scroll(
						'rutsche', {
								wait: false,
								duration: 250,
								offset: {'x': 0, 'y': 0},
								transition: Fx.Transitions.Quad.easeInOut
							}
					);
					
				$('pull_left').addEvent('click', 
					function( event ) {
							event = new Event(event).stop();
							// 1 day = 11px -> 165px = 15 days
							rutsche_pos = rutsche_pos - 165;
							slideToRight = true;
							if (rutsche_pos <= 0) {
								rutsche_pos=0;
								// change icon
								slideToLeft = false;
								timelinePuller(true, 'left');
							} else {
								slideToLeft = true;
							}
							//scroll.toElement('content1');
							scroll.scrollTo( rutsche_pos, 0 );
						}
					);
				
				
				$('pull_right').addEvent('click', 
						function(event) {
							event = new Event(event).stop();
							//scroll.toElement('content1');
							// 1 day = 11px -> 165px = 15 days
							rutsche_pos=rutsche_pos + 165;
							slideToLeft = true;
							if (rutsche_pos >(timeline_size-browser_width)) {
								rutsche_pos = (timeline_size-browser_width);
								// change icon
								slideToRight = false;
								timelinePuller(true, 'right');
							} else {
								slideToRight = true;
							}
							scroll.scrollTo(rutsche_pos,0);        
						}
					);
				
				// effects for fading in and out the timeline controls when switching on and off the timeline
				fxknopf = new Fx.Style($('knopf'), 'opacity', {duration: 100, wait: false});
				fxknopf2 = new Fx.Style($('knopf2'), 'opacity', {duration: 100, wait: false});
				fxknopfc = new Fx.Style($('knopfc'), 'opacity', {duration: 100, wait: false});
				fxzahl = new Fx.Style($('zahl'), 'opacity', {duration: 100, wait: false});
				fxzahl2 = new Fx.Style($('zahl2'), 'opacity', {duration: 100, wait: false});
				fxdiff = new Fx.Style($('diff'), 'opacity', {duration: 100, wait: false});
				
				
				var xmlDoc1 = "";
				var xmlDoc2 = "";
				
				// ajax request for getting the data about the unorts
				var xhr1 = new Ajax(
						'sys/filterunorte.php', 
						{
							method: 'get',
							evalScripts: true,
							onComplete: 
									function(response, responseXML) {
										xmlDoc1 = responseXML
									}
						}
					);
			
				// ajax request for getting the data about the timeline
				var xhr2 = new Ajax(
						'sys/gettimeline.php',
						{
							method: 'get',
							evalScripts: true,
							onComplete: 
									function(response, responseXML) {
										xmlDoc2 = responseXML
									}
						}
					);
				
				var group = new Group(xhr1, xhr2);
				group.addEvent('onComplete', 
						function() {
							// When both Ajax calls are finished the results are processed by the following functions.
							//log('before refreshAllMarker()');
							refreshAllMarker( xmlDoc1 );
							//log('before refreshTimelineDates()');
							refreshTimelineDates( xmlDoc2 );
							//log('before adaptSliders()');
							adaptSliders();
							
							if (globalStatus.timeline) {
								// show the timeline controls
								fxknopf.start.pass([0,1], fxknopf).delay(100);
								fxknopf2.start.pass([0,1], fxknopf2).delay(100);
								fxknopfc.start.pass([0,1], fxknopfc).delay(100);
								fxzahl.start.pass([0,1], fxzahl).delay(100);
								fxzahl2.start.pass([0,1], fxzahl2).delay(100);
								fxdiff.start.pass([0,1], fxdiff).delay(100);
							} else {
								fxknopf.start.pass([1,0], fxknopf).delay(100);
								fxknopf2.start.pass([1,0], fxknopf2).delay(100);
								fxknopfc.start.pass([1,0], fxknopfc).delay(100);
								fxzahl.start.pass([1,0], fxzahl).delay(100);
								fxzahl2.start.pass([1,0], fxzahl2).delay(100);
								fxdiff.start.pass([1,0], fxdiff).delay(100);
							}
							
						}
						
					);
				xhr1.request();
				xhr2.request();
			}
		);
}

function toggleFilter(what) {
	if (filter[what] == true) {
		filter[what] = false;
		i = 0;
	} else {
		filter[what] = true;
		i = 1;
	}
	if (what == "ort")
		document.getElementById( "filter_"+what ).src = btn_ort[i].src;
	if (what == "areal")
		document.getElementById( "filter_"+what ).src = btn_areal[i].src;
	if (what == "strasse")
		document.getElementById( "filter_"+what ).src = btn_strasse[i].src;
	if (what == "geb")
		document.getElementById( "filter_"+what ).src = btn_geb[i].src;

	if (what == "solved")
		document.getElementById( "filter_"+what ).src = btn_solved[i].src;
	if (what == "unsolved")
		document.getElementById( "filter_"+what ).src = btn_unsolved[i].src;
		
		// filter anzeigen
	filterMarker();
}

// Get the HTTP Object
function getHTTPObject() {
	if (window.ActiveXObject) 
		return new ActiveXObject("Microsoft.XMLHTTP");
	else if (window.XMLHttpRequest) 
		return new XMLHttpRequest();
	else {
		showMessage("Ihr Browser unterst&uuml;tzt kein AJAX.");
		return null;
	}
}

//
//		alle marker neueladen (z.b. bei page reload oder addUnort)
//

// called from init.js
// now called from initGui()
function refreshAllMarker( xmlDoc1 ) {

	//log('refreshAllMarker: process marker information');

	// Clear all overlays	
	map.clearOverlays();
	// Add the double click for adding a new unort
	// GEvent.addListener(map, "dblclick", 
	// 		function( overlay, point ) {
	// 			createNewUnortMarker(point);
	// 		}
	// 	);
	// 
	GEvent.addListener( map, "move", 
			function() {
				var allowedBounds = new GLatLngBounds( new GLatLng( 50.8, 6.7 ), new GLatLng( 51.05, 7.2 ) );
				if (allowedBounds.contains( map.getCenter() )) {
					return;
				}
				var C = map.getCenter();
				var X = C.lng();
				var Y = C.lat();
				var AmaxX = allowedBounds.getNorthEast().lng();
				var AmaxY = allowedBounds.getNorthEast().lat();
				var AminX = allowedBounds.getSouthWest().lng();
				var AminY = allowedBounds.getSouthWest().lat();
				if (X < AminX) { X = AminX; }
				if (X > AmaxX) { X = AmaxX; }
				if (Y < AminY) { Y = AminY; }
				if (Y > AmaxY) { Y = AmaxY; }
				map.setCenter( new GLatLng( Y, X ) );
			}
		);
	GEvent.addListener( map, "moveend", 
			function() {
				var center = map.getCenter();
				globalStatus.lng = center.lng();
				globalStatus.lat = center.lat();
				saveMapStatus();
			}
		);
	GEvent.addListener( map, "dragend", 
			function() {
				var center = map.getCenter();
				globalStatus.lng = center.lng();
				globalStatus.lat = center.lat();
				saveMapStatus();
			}
		);
	GEvent.addListener( map, "zoomend", 
			function() {
				var allowedZoom = 11;
				if (map.getZoom() < allowedZoom)
					map.setZoom( allowedZoom );
				globalStatus.zoom = map.getZoom();
				saveMapStatus();
			}
		);
	GEvent.addListener( map, "maptypechanged", 
			function() {
				var mapType = map.getCurrentMapType();
				saveMapStatus();
			}
		);
	
	// Load the existing unorts
	readMap( xmlDoc1 );
	// Filter them
	//filterMarker();
}

function createNewUnortMarker( point ) {
	// check login
	if (getUserID() != -1) {
		
		if (dragmarker != null){
			dragmarker.hide();
			dragmarker = null;
		}
	
		// create the dragmarker for
		dragmarker = new GMarker(point, {icon: icon_dragmarker, draggable: true});
		map.addOverlay(dragmarker);
		
		if (overlayWindow != null){
			//overlayWindow.hide();
			globalStatus.open_window = false;
			//overlayWindow.remove();
			map.removeOverlay( overlayWindow );
			overlayWindow = null;
		}
		globalStatus.open_window = true;
		overlayWindow = new EWindow(map,UNORT_STYLE);
		map.addOverlay( overlayWindow );
				
		AU_initAndOpenNewUnortWindow( dragmarker, point.lat(), point.lng() );
		FU_panMap(point);
	
		// Behaviour on clicking on the marker
		GEvent.addListener(dragmarker, "click", 
				function() {
					if (overlayWindow.isHidden())
						AU_restoreAddUnortStep();
				}
			);
		
		// Behaviour on start dragging
		GEvent.addListener(dragmarker, "dragstart", 
				function() {
					AU_saveState();
					overlayWindow.hide();
				}
			);
		
		// Behaviour on end of dragging
		GEvent.addListener(dragmarker, "dragend", 
				function(point) {
					AU_restoreDraggedMarker( dragmarker, dragmarker.getPoint().lat(), dragmarker.getPoint().lng() );
					FU_panMap(point);
				}
			);
	}
	// if not logged in
	else {
		// showMessage('Sie m&uuml;ssen registriert und angemeldet sein, um einen Unort anzulegen!');
		
		//TODO Registration as Modal Window
		self.location.href = 'sys/register.php';
	}
}

function disableDragging() {
	if (map.draggingEnabled())
		map.disableDragging();
}

function enableDragging() {
	if (!map.draggingEnabled())
		map.enableDragging();
}

//
// prüft ob ein eingabefeld seinen infotext entspricht
//

function checkIfEmpty(orig,data) {
	if (data == orig) {
		return "";
	}
	return data;
}

function filterMarker() {
	for (var i=0; i<unorte.length; i++) {
		u = unorte[i];
		if (filter[u['type']] && filter[u['solved']]) {
			if (globalStatus.timeline) {
				if ((filter['from'] > u['datum']) || (filter['to'] < u['datum'])) {
					if (u['id'] == OPEN_UNORT) {
						unortMarkers[i].show();
					} else {
						unortMarkers[i].hide();
					}
				} else {
					unortMarkers[i].show();
				}
			} else {
				unortMarkers[i].show();
			}
		} else {
 			unortMarkers[i].hide();
		}
	}
}

function toggleClustering() {
	if (globalStatus.clustering) {
		globalStatus.clustering = false;
		document.clustering.cluster.checked = false;
	} else {
		globalStatus.clustering = true;
		document.clustering.cluster.checked = true;
	}
	showMarkers();
}
function showMarkers() {
	map.clearOverlays();
	if (globalStatus.clustering) {
			cluster = new ClusterMarker(map, {markers:unortMarkers});
			cluster.refresh();
	} else {
		if (cluster != null) {
			cluster.removeMarkers();
			cluster = null;
		}
		for (var i = 0; i < unortMarkers.length; i++) {
			map.addOverlay(unortMarkers[i]);
		}
	}
	if (globalStatus.open_marker != -1) {
		manualOpen( globalStatus.open_marker, globalStatus.open_marker_id );
	}
}

// Loads all unort data onto the map
// called from refreshAllMarker()
function readMap( xmlDoc1 ) {
	//log('readMap() -> actual processing of the markers, but no ajax call anymore');
	
	//var request = GXmlHttp.create();
	//var query = "sys/filterunorte.php";
	
	//request.open("GET", query, true);
	//request.onreadystatechange = function() {
	//	if (request.readyState == 4) {
	//		var xmlDoc = request.responseXML;
			//var xmlDoc = xhr1.response.text;
			// obtain the array of markers and loop through it
			
			var markers = xmlDoc1.documentElement.getElementsByTagName("marker");
			 
			// hide the info window, otherwise it still stays open where the removed marker used to be
			//map.getInfoWindow().hide();
			//map.clearOverlays();
			// empty the array
			//gmarkers = [];
			// unorte löschen!
			unortMarkers = [];
			unorte = [];
			unortMarkersByID = {};
			// reset the side_bar
			
			for (var i = 0; i < markers.length; i++) {
				// obtain the attribues of each marker
				var lat = parseFloat(markers[i].getAttribute("lat"));
				var lng = parseFloat(markers[i].getAttribute("lng"));
				var user_name = markers[i].getAttribute("nickname");
				var datum = markers[i].getAttribute("datum").substring(0,10);
				var text = markers[i].getAttribute("text");
				var point = new GLatLng(lat,lng);
				var solved = markers[i].getAttribute("solved");
				var type = markers[i].getAttribute("type");
				var featured = markers[i].getAttribute("featured");
				var title = markers[i].getAttribute("title_ort");
				var icon = "";
				if (featured) {
					icon = icon_featured;
				} else {
					if (solved == "1") {
						switch (type) {
							case "geb": icon = icon_geb_s; break;
							case "ort": icon = icon_ort_s; break;
							case "areal": icon = icon_areal_s; break;
							case "strasse": icon = icon_strasse_s; break;
							default: icon = icon_other;
						}
					} else {
						switch (type) {
							case "geb": icon = icon_geb; break;
							case "ort": icon = icon_ort; break;
							case "areal": icon = icon_areal; break;
							case "strasse": icon = icon_strasse; break;
							default: icon = icon_other;
						}
					}
				}
				
				unorte[i] = {
						'id'				: markers[i].getAttribute("id"),
						'title'			: title,
						'type'			: type,
						'solved'    : solved,
						'lat'				: lat,
						'lng'				: lng,
						'datum'			: datum,
						'text'			: text,
						'icon'			: icon,
						'point'			: point,
						'user_name'	: user_name
					};
				unorte[i].solved = (solved == "1") ? 'solved' : 'unsolved';
				
				// unorteByID['u'+markers[i].getAttribute("id")] = i;
				
				//var html = DU_composeDetailUnortWindow(user_name,datum,text,markers[i].getAttribute("id"));
				unortMarkers[i] = createMarker( point, icon, markers[i].getAttribute("id"), title );
				unortMarkers[i].disableDragging();
				unortMarkersByID['u'+markers[i].getAttribute("id")] = unortMarkers[i];
				//map.addOverlay(unortMarkers[i]);
			}
			showMarkers();
		
			// refresh timeline here instead of within init.js as the timeline depends on the data about the unorte 
			// that is retrieved in this function and might not be available otherwise, resulting in information
			// that is sometimes shown and sometimes not
			//refreshTimelineDates();
		//}
	//}
	//request.send(null);
}

// Called from the main search on the inte rface
function showAddress( address ) {
	if (address == IN_defText( "in1" ))
		return;
		
	address += ", Köln";
	if (geocoder) {
		geocoder.getLatLng( address,
				function( point ) {
					if (!point) {
						showMessage( address + " wurde nicht gefunden!" );
					} else {
						// Pan and zoom
						var p = new GLatLng(point.lat(), point.lng());
						
						window.setTimeout( 
								function() { 
									map.panTo( p ); 
								}, 500
							);
						map.setZoom( 14 )
						
						// TODO open unort info if available
						if (GL_searchMarker != null)
						map.removeOverlay( GL_searchMarker );
						
						GL_searchMarker = new GMarker( point, {icon: icon_dragmarker, draggable: true} );
						
						map.addOverlay(GL_searchMarker);
						// register a listener so that you can add an unort by clicking on the search marker
						GEvent.addListener(GL_searchMarker, "click", 
								function() {
									if (getUserID() != -1)
									map.removeOverlay( GL_searchMarker );
									createNewUnortMarker( point );
								}
							);
					}
				}
			);
	}
}

// Function for creating markers on all unorts
function createMarker( point, icon, id, title ) {
	// var marker = new GMarker( point, icon );
	var options = { draggable:true, bouncy:true, icon:icon, title:title };
	var marker = new GMarker( point, options );
	// Add a listener for opening a detail window
	GEvent.addListener( marker, "click", 
			function() {
				if (overlayWindow != null) {
					map.removeOverlay( overlayWindow );
					overlayWindow = null;
				}
				if (last_clicked_marker != marker) {
					// Store the marker that was clicked
					last_clicked_marker = marker;
					globalStatus.open_window = true;
					globalStatus.place_id = id;
					overlayWindow = new EWindow( map,UNORT_STYLE );
					map.addOverlay( overlayWindow );
					
					DU_form_redirect = 2;
					DU_initAndOpenDetailUnortWindow( marker, id );
					
					// Pan the map to give a better overview
					//map.panTo(createNewCenter(marker.getPoint()));
					FU_panMap(point);
				} else {
					last_clicked_marker = null;
				}
			}
		);
	
	if ((OPEN_UNORT != -1) && (id == OPEN_UNORT)) {
		globalStatus.open_marker = marker;
		globalStatus.open_marker_id = id;
	}
	
	return marker;
}

function openUnortByID(id){
	if (id == DU_UNORT_ID) {
		// console.log('already open');
		return;
	}
	if(unortMarkersByID['u'+id]){
		manualOpen(unortMarkersByID['u'+id],id);
	}
}

function manualOpen(marker,id){
	// If an overlaywindow exists 
	if (overlayWindow != null){
		
		if (globalStatus.open_window && !globalStatus.place_id){
			AU_abortNewUnort();
		}	
		// and we click the same marker with a hidden window show it
		else if (last_clicked_marker == marker && overlayWindow.isHidden()){
			overlayWindow.show();
			return;
		}
		// if it was a new marker, destroy the previous window
		else if (last_clicked_marker == marker){
			DU_saveState();
			overlayWindow.hide();
			return;
		}
		// if it was a new marker, destroy the previous window
		else{
			overlayWindow.hide();
			overlayWindow = null;
		}
	}
	// Store the marker that was clicked
	last_clicked_marker = marker;
	
	globalStatus.open_window = true;
	globalStatus.place_id = id;
	overlayWindow = new EWindow(map,UNORT_STYLE);
	map.addOverlay(overlayWindow);
	
	DU_initAndOpenDetailUnortWindow( marker, id );
	
	map.panTo( createNewCenter(marker.getPoint()) );
}


// This function picks up the click and opens the corresponding info window
function myclick(i) {
	gmarkers[i].openInfoWindowHtml(htmls[i]);
}

/*
function checkType(newtype) {
	document.getElementById( "type_ort" ).src = "img/icon_ort_klein_b.png";
	document.getElementById( "type_strasse" ).src = "img/icon_strasse_klein_b.png";
	document.getElementById( "type_geb" ).src = "img/icon_geb_klein_b.png";
	document.getElementById( "type_areal" ).src = "img/icon_areal_klein_b.png";
	if (newtype != "") {
		store_edit_type = newtype;
		document.getElementById( "type_"+newtype ).src =  "img/icon_"+newtype+"_klein_a.png";
	} else {
		store_edit_type = "";
		document.getElementById( "checked_type" ).value = "";
	}
}
*/

// cross-browser function to stop event propogation.
// assign this as your event function.
//
// NOTE: in production code you will want to remove the
// GLog.write()s and probably also the window.alert()
// which checks the correctness of your code.
//
// Examples of how to use.
//
// // traditional "on" properties
// b.onclick = stop_propagation;
//
// // IE-specific attachEvent()
// // NOTE: the extra "on" before the event name
// b.attachEvent("onclick", stop_propagation);
//
// // DOM2 (Netscape, Firefox, NOT IE) addEventListener()
// // IMPORTANT: pass false, not true, for capture argument.
// b.addEventListener("click", stop_propagation, false);
//
// // Google GEvent addDomListener, which does one
// // of the above depending on the browser platform
// GEvent.addDomListener(b, "click", stop_propagation);
// 

/*
function stop_propagation(event) {
	var type = event ? event.type : window.event.type;
	var phase = event ? event.eventPhase : "unknown";
	//GLog.write(this.id + ' ' + type + ' ' + event + ' ' + phase);
	
	// IE: it's important to test window.event, not event.
	// IE sends a non-null event for attachEvent() but that
	// event has no eventPhase or stopPropagation() properties.
	if (window.event) {
		// IE
		//GLog.write("used window.event.cancelBubble");
		window.event.cancelBubble = true; // for IE
	} else {
		// non-IE
		// NOTE: we cannot even mention event.cancelBubble here, not
		// even read it, because if we do, a hideous FireFox 1.5.0.4
		// (and probably also Netscape) IE compatiblity hack will kick
		// into action and change the value of event.eventPhase to 0,
		// which is bad if eventPhase happens to have been
		// CAPTURING_PHASE (1) (see below). don't believe me?  try it:
		// GLog.write("phase=" + event.eventPhase);
		// GLog.write("cancel=" + event.cancelBubble);
		// GLog.write("now phase=" + event.eventPhase);
		
		if (event.eventPhase == 1) {
			// don't call stopPropogation() in CAPTURING_PHASE (1) --
			// we want events to be able to propogate down, but not up.
			// this is really user error; almost certainly the user
			// called
			//   b.addEventListener(e, f, false)
			// instead of
			//   b.addEventListener(e, f, true).
			// in which case they WON'T call us at the right time!
			//window.alert("error: stop_propogation used for capturing phase");
			//GLog.write("avoided stopPropogation--wrong phase");
		} else {
			//GLog.write("used stopPropogation");
			event.stopPropagation();
		}
	} 
}
*/
function getBrowserSize() {
	var myWidth = 0, myHeight = 0;
	if (typeof( window.innerWidth) == 'number' ) {
		//Non-IE
		myWidth = window.innerWidth;
		myHeight = window.innerHeight;
	} else if (document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight )) {
		//IE 6+ in 'standards compliant mode'
		myWidth = document.documentElement.clientWidth;
		myHeight = document.documentElement.clientHeight;
	} else if (document.body && (document.body.clientWidth || document.body.clientHeight)) {
		//IE 4 compatible
		myWidth = document.body.clientWidth;
		myHeight = document.body.clientHeight;
	}
	browser_width = myWidth;
	browser_height= myHeight;
}

function getClockTime() {
	var now    = new Date();
	var hour   = now.getHours();
	var minute = now.getMinutes();
	var second = now.getSeconds();
	var ap = "AM";
	
	if (hour > 11) { ap = "PM"; }
	if (hour > 12) { hour = hour - 12; }
	if (hour == 0) { hour = 12; }
	if (hour < 10) { hour = "0" + hour; }
	if (minute < 10) { minute = "0" + minute; }
	if (second < 10) { second = "0" + second; }
	
	return hour + ':' + minute + ':' + second + " " + ap;
}

function getDate() {
	var now = new Date();
	var day = now.getDate();
	var month = (now.getMonth() + 1);
	var year = now.getYear();
	if (year < 1900) { year += 1900; }
	if (month < 10) { month = "0" + month; }
	if (day < 10) { day = "0" + day; }
	
	return year+"-"+month+"-"+day;
}

function getEarlierDate( numberOfDays ) {
	var now = new Date();
	now.setDate( now.getDate() - numberOfDays );
	var day = now.getDate();
	var month = (now.getMonth() + 1);
	var year = (now.getYear() + 1900);
	if (month < 10) { month = "0"+month; }
	if (day < 10) { day = "0" + day; }
	
	return year + "-" + month + "-" + day;
}


function changeMapType(type) {
	globalStatus.maptype = type;
	saveMapStatus();
	document.getElementById('maptype_map').style.backgroundImage="none";
	document.getElementById('maptype_satellite').style.backgroundImage="none";
	document.getElementById('maptype_hybrid').style.backgroundImage="none";
	
	document.getElementById(type).style.backgroundImage="url('img/map/all/opacity100.png')";
}

function saveMapStatus() {
	var center = map.getCenter();
	globalStatus.lng = center.lng();
	globalStatus.lat = center.lat();
	globalStatus.zoom = 1 * map.getZoom();
	globalStatus.map_type = map.getCurrentMapType();
	var cookie;
	cookie = 
			"settings=" + globalStatus.zoom + "," + globalStatus.lng + "," + globalStatus.lat + "," + globalStatus.map_type.getName() + "," + 
			globalStatus.timeline + "," + globalStatus.timeline_center + "," + globalStatus.timeline_from + "," + globalStatus.timeline_to;
	document.cookie = cookie;
}

function readSettingsCookie() {
	var i = 0;
	var search = "settings=";
	while (i < document.cookie.length ) {
		if (document.cookie.substring( i, i + search.length ) == search) {
			var end = document.cookie.indexOf( ";", i + search.length );
			end = (end > -1) ? end : document.cookie.length;
			var cookie = document.cookie.substring( i + search.length, end );
			return unescape( cookie );
		}
		i++;
	}
	return false;
}

function restoreMapStatus() {
	var settingString;
	if (settingString = readSettingsCookie()) {
		var setting = settingString.split( "," );
		globalStatus.zoom = 1 * setting[0];
		globalStatus.lng = setting[1];
		globalStatus.lat = setting[2];
		switch (setting[3]) {
			case 'Satellit':	globalStatus.map_type = G_SATELLITE_MAP; break;
			case 'Hybrid':		globalStatus.map_type = G_HYBRID_MAP; break;
			default:					globalStatus.map_type = G_NORMAL_MAP;
		}
		globalStatus.timeline = (setting[4] == "true") ? true : false;
		globalStatus.timeline_center = setting[5];
		globalStatus.timeline_from = setting[6];
		globalStatus.timeline_to = setting[7];
	} else {
		globalStatus.timeline = false;
	}
}

function addUnort() {
	setTimeout( function() {
				createNewUnortMarker( map.getCenter() );
			}, 
			1000 
		);
}

function calendarShow( type ) {
	var xoff = -100;
	var yoff = -100;
	calendar_active = type;
	switch (type) {
		case 1: // timeline
			xoff = -190;
			yoff = -195;
			calendar.setImagesPath( './img' );
			break;
		case 2: // noticed (new and settings)
			calendar.setImagesPath( './img' );
			break;
		default: // page view
			calendar.setImagesPath( '../img' );
	}
	calendar.setOffset( xoff, yoff );
	calendar.show();
}

function calendarCallback( d, m, y) {
	calendar._hideLayer();
	d = (d<10) ? '0'+d : d;
	m = (m<10) ? '0'+m : m;
	switch (calendar_active) {
		case 1:
			var command = 'centerTimelineOnDate( "'+y+'-'+m+'-'+d+'" )';
			setTimeout( command, 1000 );
			break;
		case 2:
			document.getElementById( 'date_noticed' ).value = d+"."+m+"."+y;
			document.getElementById( 'date_noticed' ).style.fontStyle = "normal";
			break;
		case 3:
			document.getElementById( 'list_sort_from' ).value = y+"-"+m+"-"+d;
			document.getElementById( 'list_sort_from' ).style.fontStyle = "normal";
			break;
		case 4:
			document.getElementById( 'list_sort_to' ).value = y+"-"+m+"-"+d;
			document.getElementById( 'list_sort_to' ).style.fontStyle = "normal";
			break;
	}
	calendar_active = 0;
}

function germanDate( date ) {
	if (date) {
		var part;
		part = date.split( '-' );
		return part[2]+'.'+part[1]+'.'+part[0];
	} else {
		return '1.1.2008';
	}
}

function intDate( date ) {
	var part = date.split( '.' );
	return part[2]+'-'+part[1]+'-'+part[0];
}

// highlite marker on the map (highlite = true) or cancel highliting ( = false)
function highlightMarker( id, highlite ) {

}

