globals=
{
	errorBox:null,
	infoBox:null,
	hoverscreen:null,	
	historybarslider:null,
	countries:null
};
function toggleSubMenu(parent, classtohide, idtoshow)
{
	var tohide = $(parent).getElementsByClassName(classtohide).each(function(s){Element.addClassName(s,'hidden');});
	var toshow = document.getElementById(idtoshow);
	Element.removeClassName(toshow,'hidden');
}

function toggleHiddenVisible(idtoshow)
{
	var toshow = document.getElementById(idtoshow);
	Element.toggle(toshow);
}
function selectValueSet(selectName, value)
{
	selectObject = $(selectName);
	for(index = 0; index < selectObject.length; index++)
	{
		if(selectObject[index].value == value)
		{
			selectObject.selectedIndex = index;
			index = selectObject.length;
		}
	}
}
function sleep(milliseconds) {
  var start = new Date().getTime();
  for (var i = 0; i < 1e7; i++) {
    if ((new Date().getTime() - start) > milliseconds){
      break;
    }
  }
}
function URLEncode (clearString) {
  var output = '';
  var x = 0;
  clearString = clearString.toString();
  var regex = /(^[a-zA-Z0-9_.]*)/;
  while (x < clearString.length) {
    var match = regex.exec(clearString.substr(x));
    if (match != null && match.length > 1 && match[1] != '') {
    	output += match[1];
      x += match[1].length;
    } else {
      if (clearString[x] == ' ')
        output += '+';
      else {
        var charCode = clearString.charCodeAt(x);
        var hexVal = charCode.toString(16);
        output += '%' + ( hexVal.length < 2 ? '0' : '' ) + hexVal.toUpperCase();
      }
      x++;
    }
  }
  return output;
}

function getErrorMessage(request)
{
	try {
		var errortext = request.getResponseHeader('X-AJAX-ERRORMESSAGE');
		if (errortext.length>0)
		{
			$('message').innerHTML = '';
			$('errormessage').innerHTML = errortext;
			 globals.errorBox = new Control.Modal(false,{
				containerClassName: 'error',
 				overlayClassName: 'error',
				width: 300,
			    contents: function(){
			    	var alertBox ="<div>";
	                     alertBox  +="<img src=\"/img/error.jpg\" style=\"position: relative; float:left; top: 1%; left: 2%\" /></td>";
    	                 alertBox +="<SPAN style=\"position: relative; top:10px; left: 7%\">"+errortext+"</SPAN>";
        	             alertBox  +="<input style=\"color:#900; font-weight:bold; background-color:#eac8c8;border:2px solid #900; position: absolute; bottom:4px; right:4px;\" type=\"button\" value=\"    OK      \" onclick=\"globals.errorBox.close();\" />";
		    	        alertBox+="</div>";
			         return alertBox ;
			    }
			 });
			 globals.errorBox.open();
		}
	}
	catch (e) {$('message').innerHTML='';}
}

function getMessage(request)
{
	try {
		var refreshtext = request.getResponseHeader('X-AJAX-GOTO');
		if (refreshtext && refreshtext.length>0)
		{
			document.location.href=refreshtext;
			return false;
		}
	}
	catch (e) {}
	try {
		var refreshtext = request.getResponseHeader('X-AJAX-REFRESH');
		if (refreshtext && refreshtext.length>0)
		{
			document.location.reload();
			return false;
		}
	}
	catch (e) {}
	try {
		var messagetext = request.getResponseHeader('X-AJAX-MESSAGE');
		if (messagetext.length>0)
		{
			$('errormessage').innerHTML='';
			$('message').innerHTML=request.getResponseHeader('X-AJAX-MESSAGE');

			 globals.infoBox = new Control.Modal(false,{
				containerClassName: 'info',
 				overlayClassName: 'info',
				width: 300,
			    contents: function(){
			    	var alertBox ="<div>";
	                     alertBox  +="<img src=\"/img/info.jpg\" style=\"position: relative; float:left; top: 1%; left: 2%\" /></td>";
    	                 alertBox +="<SPAN style=\"position: relative; top:10px; left: 7%\">"+messagetext+"</SPAN>";
        	             alertBox  +="<input style=\"color:#506dcb; font-weight:bold; background-color:#d6e0fe;border:2px solid #506dcb; position: absolute; bottom:4px; right:4px;\" type=\"button\" value=\"    OK      \" onclick=\"globals.infoBox.close();\" />";
		    	        alertBox+="</div>";
			         return alertBox ;
			    }
			 });
			 globals.infoBox.open();

		}
	}
	catch (e) {$('message').innerHTML='';}
	return false;
}

function AjaxLink(link,target)
{
 	new Ajax.Updater(target,link,{onComplete:function(request){getErrorMessage(request);}, evalScripts:true});
 	return false;
}

function loadModal(url)
{
 globals.hoverscreen = new Control.Modal(false,{
     contents: function(){
         new Ajax.Request(url,{
             onComplete: updateModal
         });
         return 'loading...';
     }
 });
 globals.hoverscreen.open();
}

function updateModal(request)
{
	globals.hoverscreen.update(request.responseText);
}

multiselect=
{
	version: '1.0',
	ajax_request: false,
	add: function(theParent)
	{
		multiselect.ajax_request=new Ajax.Request
		(
			'/gui_multiselect/add/',
			{
				method: 'post',
				parameters: 'id='+$(theParent + '_select').value+'&ids='+$(theParent +'_selected').value+'&tablename='+$(theParent + '_table').value+'&keyfield='+$(theParent + '_keyfield').value+'&valuefield='+$(theParent + '_valuefield').value+'&parent='+theParent,
				onComplete: multiselect.responseHandler
			}
		);
		return;
	},
	remove: function(theParent,theID)
	{

		if (theID)
		{
			multiselect.ajax_request=new Ajax.Request
			(
				'/gui_multiselect/remove/',
				{
					method: 'post',
					parameters: 'id='+theID+'&ids='+$(theParent +'_selected').value+'&tablename='+$(theParent + '_table').value+'&keyfield='+$(theParent + '_keyfield').value+'&valuefield='+$(theParent + '_valuefield').value+'&parent='+theParent,
					onComplete: multiselect.responseHandler
				}
			);
		}
		return;
	},
	responseHandler: function(theResponse)
	{
		if (multiselect.ajax_request.getHeader('X-AJAX-RESULT')==1)
		{
			var theParent = multiselect.ajax_request.getHeader('X-AJAX-THEPARENT');
			var outputfield=$(theParent);
			var theScripts=theResponse.responseText.extractScripts();
			outputfield.innerHTML=theResponse.responseText;
			theScripts.each
			(
				function(thisScript)
				{
					return eval(thisScript);
				}
			);
		}
		return;
	}
};

globalmap=
{
	divName:'mapContent',
	markers:null,
	types:null,
	pointers:null,
	visible:null,
	icon:null,
	zoomlevel:null,
	map:null,
	clusterer:null,
	brandicons:null,
	routePoints:null,
	routeMarkers:null,
	routeOverlays:null,
	lineIx:0,
	totalDistance:0,
	baseIcon:null,
	greenIcon:null,
	redIcon:null,
	isenabled:null,
	colors: null,
	stilllastrequest:0,
	addRoutePoint:function(point) {
		var dist = 0;
		if (!this.routePoints[this.lineIx]) {
			this.routePoints[this.lineIx] = Array();
			this.routeMarkers[this.lineIx] = Array();
		}
		this.routePoints[this.lineIx].push(point);

		if (this.routePoints[this.lineIx].length > 1)	{
			this.plotRoute();
			dist = this.routePoints[this.lineIx][this.routePoints[this.lineIx].length-2].distanceFrom(point) / 1000;
			this.totalDistance += dist;
			//document.getElementById("dist").innerHTML = 'Total Distance: '+ totalDistance.toFixed(3) + ' km';
		}
		else {
			this.routeMarkers[this.lineIx][this.routePoints[this.lineIx].length-1] = new GMarker(point,{icon:this.greenIcon,title:'Start'});
			this.map.addOverlay(this.routeMarkers[this.lineIx][this.routePoints[this.lineIx].length-1]);

		}
		//document.getElementById("route").innerHTML += point.y.toFixed(6) + ' ' + point.x.toFixed(6) + ' : ' + dist.toFixed(3) +"<br>";
	},
	plotRoute: function() {
		if (typeof(this.routeOverlays[this.lineIx])=='object') this.map.removeOverlay(this.routeOverlays[this.lineIx]);
		var modcount = this.lineIx % 5;
		var thiscolor = this.colors[modcount];
		this.routeOverlays[this.lineIx] = new GPolyline(this.routePoints[this.lineIx],thiscolor,3,1);
		this.map.addOverlay(this.routeOverlays[this.lineIx]);
	},
	mapClick: function (marker, point) {
		if (!marker) {
			if (this.stilllastrequest==0)
			{
				this.stilllastrequest=1;
				this.addRoutePoint(point);
				mousefollow.isonmap=true;
				var thislat = point.lat();
			  	var thislng = point.lng();
				mousefollow.reversegeocoder.reverseGeocode(point);
				this.stilllastrequest=0;
				new Ajax.Updater('contentMediaPanel','/itinerary/addLocation/' + mousefollow.id +'/'+thislat+'/'+thislng, {onFailure:function(request){getErrorMessage(request);return false;}, onComplete:function(request){getMessage(request);;return false;}, evalScripts:true}); return false;
			}
		}
	},
	routerevgeocoder: function(placemark) {
        var thislat = placemark.Point.coordinates[1];
	  	var thislng = placemark.Point.coordinates[0];
	  	var thislocation = 	URLEncode(placemark.address);
	  	var thiscountry = mousefollow.reversegeocoder.getPlacemarkProperty(placemark,"CountryNameCode");
	  	new Ajax.Updater('contentMediaPanel','/itinerary/updateLocation/'+ mousefollow.id +'/'+thislat+'/'+thislng+'/'+thiscountry+'/'+thislocation, {onFailure:function(request){getErrorMessage(request);;return false;}, onComplete:function(request){getMessage(request);return false;}, evalScripts:true}); return false;
        GEvent.removeListener(this.geocodereventlistner);
    },
	enable: function(origin,id)
	{
		this.isenabled=true;
		this.map.getDragObject().setDraggableCursor("crosshair");
		this.routePoints = new Array();
		this.routeMarkers = new Array();
		this.routeOverlays = new Array();
		this.colors = new Array();
		this.colors[0]='#0080FF';
		this.colors[1]='#FF0000';
		this.colors[2]='#008000';
		this.colors[3]='#800080';
		this.colors[4]='#FF0080';
		this.totalDistance = 0;
		this.baseIcon = new GIcon();
		this.baseIcon.iconSize=new GSize(16,16);
		this.baseIcon.iconAnchor=new GPoint(8,8);
		this.baseIcon.infoWindowAnchor=new GPoint(10,0);
		this.greenIcon = (new GIcon(this.baseIcon, "/img/greenCircle.png", null, ""));
		this.redIcon = (new GIcon(this.baseIcon, "/img/redCircle.png", null, ""));
		mousefollow.origin=origin;
		mousefollow.id=id;
		mousefollow.fx = mousefollow.follow.bindAsEventListener(mousefollow);
		mousefollow.fxdisable = mousefollow.disable.bindAsEventListener(mousefollow);
		mousefollow.fxmappoint = this.mapClick;
		mousefollow.fxgeocoder = this.routerevgeocoder;
		mousefollow.reversegeocoder = new GReverseGeocoder(globalmap.map);
		mousefollow.geocodereventlistner = GEvent.bind(mousefollow.reversegeocoder, "load", this, mousefollow.fxgeocoder);

		Event.observe(document, 'mousemove', mousefollow.fx);
		mousefollow.isonmap=false;
		this.mappointeventlistner = GEvent.bind(globalmap.map, "click", this, mousefollow.fxmappoint);

	},
	addClosing: function() {
		if (typeof(this.routePoints)=='object')
		{
			if (this.routePoints[this.lineIx].length > 1)	{
				//this.map.removeOverlay(this.routeMarkers[this.lineIx][this.routePoints[this.lineIx].length-1]);
				this.routeMarkers[this.lineIx][1] = new GMarker(this.routePoints[this.lineIx][this.routePoints[this.lineIx].length-1],{icon:this.redIcon,title:'End'});
				this.map.addOverlay(this.routeMarkers[this.lineIx][1]);
				this.lineIx++;
				//document.getElementById("route").innerHTML += '<br>';
			}
		}
		this.disable();
	},
	disable: function()
	{
		Event.stopObserving(document, 'click', this.fxdisable);
		Event.stopObserving(document, 'mousemove', this.fx);
		GEvent.removeListener(this.mappointeventlistner);
		this.map.getDragObject().setDraggableCursor("hand");
		var obj = $(mousefollow.divName).style;
		obj.visibility = 'hidden';
		this.isenabled=false;
	},
	encodePolyline: function() {
		var encodedPoints = '';
		var	encodedLevels = '';
		var plat = 0;
		var plng = 0;

		for (var n = 0 ; n < this.routePoints[this.lineIx].length ; n++ ) {
			var lat = this.routePoints[this.lineIx][n].y.toFixed(8);
			var lng = this.routePoints[this.lineIx][n].x.toFixed(8);
			var level = (n == 0 || n == this.routePoints[this.lineIx].length-1) ? 3 : 1;
			var level = 0;
			var late5 = Math.floor(lat * 1e5);
			var lnge5 = Math.floor(lng * 1e5);

			dlat = late5 - plat;
			dlng = lnge5 - plng;
			plat = late5;
			plng = lnge5;

			encodedPoints += encodeSignedNumber(dlat) + encodeSignedNumber(dlng);
			encodedLevels += encodeNumber(level);
		}


		var html = '';
		html += 'new GPolyline.fromEncoded({\n';
		html += '  color: "#0000ff",\n';
		html += '  weight: 4,\n';
		html += '  opacity: 0.8,\n';
		html += '  points: "'+encodedPoints+'",\n';
		html += '  levels: "'+encodedLevels+'",\n';
		html += '  zoomFactor: 16,\n';
		html += '  numLevels: 4\n';
		html += '});\n';

		return html;
	},
	clearAll: function() {
		while (this.lineIx >= 0) {
			this.resetRoute();
		}
		this.lineIx=0;
		this.totalDistance = 0;
	},
	resetRoute: function() {
		if (typeof(this.routePoints)=='undefined' && typeof(this.routePoints)=='object')
		{
			if (!this.routePoints[this.lineIx] || this.routePoints[this.lineIx].length == 0) {
				this.lineIx--;
			}

			this.routePoints[this.lineIx] = null;

			this.map.removeOverlay(this.routeOverlays[this.lineIx]);

			for (var n = 0 ; n < this.routeMarkers[this.lineIx].length ; n++ ) {
				var marker = this.routeMarkers[this.lineIx][n];
				this.map.removeOverlay(marker);
			}
			this.routeMarkers[this.lineIx] = null;

		}
		this.lineIx--;
	}
};
// Simple follow the mouse script
mousefollow=
{
	divName:'pinpoint', // div that is to follow the mouse
    offX: -6,          // X offset from mouse position
    offY: -50,          // Y offset from mouse position
	justenabled: false,
	fx: null,
	id: null,
	isonmap: false,
	marker: null,
	fxdisable: null,
	fxmappoint: null,
	fxgeocoder: null,
	mappointeventlistner: null,
	geocodereventlistner:null,
	origin: null,
	reversegeocoder: null,
	mouseX: function(evt) {
		if (!evt) evt = window.event; if (evt.pageX) return evt.pageX; else if (evt.clientX)return evt.clientX + (document.documentElement.scrollLeft ?  document.documentElement.scrollLeft : document.body.scrollLeft); else return 0;
	},
	mouseY: function(evt) {
		if (!evt) evt = window.event; if (evt.pageY) return evt.pageY; else if (evt.clientY)return evt.clientY + (document.documentElement.scrollTop ? document.documentElement.scrollTop : document.body.scrollTop); else return 0;
	},
	follow: function(evt) {
		var obj = $(this.divName).style;
		obj.visibility = 'visible';
		obj.left = (parseInt(this.mouseX(evt))+this.offX) + 'px';
		obj.top = (parseInt(this.mouseY(evt))+this.offY) + 'px';
	},
	enable: function(origin,id)
	{
		globalmap.map.getDragObject().setDraggableCursor("crosshair");
		this.origin=origin;
		this.id=id;
		this.fx = this.follow.bindAsEventListener(this);
		this.fxdisable = this.disable.bindAsEventListener(this);
		this.fxmappoint = this.mappoint;
		this.fxgeocoder = this.followrevgeocoder;
		this.reversegeocoder = new GReverseGeocoder(globalmap.map);
		this.geocodereventlistner = GEvent.bind(this.reversegeocoder, "load", this, this.fxgeocoder);

		Event.observe(document, 'mousemove', this.fx);
		this.justenabled=true;
		this.isonmap=false;
		Event.observe(document, 'click', this.fxdisable);
		this.mappointeventlistner = GEvent.bind(globalmap.map, "click", this, this.fxmappoint);

	},
	disable: function()
	{
		if ((this.justenabled==false))
		{
			Event.stopObserving(document, 'click', this.fxdisable);
			Event.stopObserving(document, 'mousemove', this.fx);
			GEvent.removeListener(this.mappointeventlistner);
			globalmap.map.getDragObject().setDraggableCursor("hand");

			var obj = $(this.divName).style;
			obj.visibility = 'hidden';
		}
		this.justenabled=false;
	},
	mappoint: function(overlay, latlng)
	{
		this.isonmap=true;
		var icon = new GIcon();
		icon.image = '/img/pinsm.gif';
		icon.iconSize = new GSize(25, 25);
		icon.iconAnchor = new GPoint(14, 25);
		icon.infoWindowAnchor = new GPoint(14, 14);
		if (this.marker!=null) globalmap.map.removeOverlay(this.marker);
		this.marker = new GMarker(latlng,icon)
		globalmap.map.addOverlay(this.marker);
		var thislat = latlng.lat();
	  	var thislng = latlng.lng();
		this.reversegeocoder.reverseGeocode(latlng);
		try
        {
        	$(mousefollow.origin + '_lat').value=thislat;
        	$(mousefollow.origin + '_lng').value=thislng;
        }
		catch (e) {}
		
		new Ajax.Updater(mousefollow.origin + '_locationoutput','/locations/setLatLng' + this.origin + '/' + this.id +'/'+thislat+'/'+thislng, {onFailure:function(request){getErrorMessage(request);}, onComplete:function(request){getMessage(request);}, evalScripts:true}); return false;
		
	},
	followrevgeocoder: function(placemark) {
        var thislat = placemark.Point.coordinates[1];
	  	var thislng = placemark.Point.coordinates[0];
	  	var thislocation = 	URLEncode(placemark.address);
	  	var thiscountry = this.reversegeocoder.getPlacemarkProperty(placemark,"CountryNameCode");	  	
        try
        {
	        $(mousefollow.origin + '_lat').value=thislat;
        	$(mousefollow.origin + '_lng').value=thislng;
        }
        catch (e) {}
        try
        {
        	
        	var thiscountry2=-1;
        	for (var n = 1 ; n < globals.countries.length ; n++ ) {
				if (thiscountry==globals.countries[n]) 
				{
					thiscountry2 = n;
					n=globals.countries.length;
				}
			}
	        if (thiscountry2>0) selectValueSet(mousefollow.origin + '_country',thiscountry2);
        }
		catch (e) {}
        
        GEvent.removeListener(this.geocodereventlistner);
	  	new Ajax.Updater(mousefollow.origin + '_locationoutput','/locations/setLocation' + this.origin + '/' + this.id +'/'+thislat+'/'+thislng+'/'+thiscountry+'/'+thislocation, {onFailure:function(request){getErrorMessage(request);}, onComplete:function(request){getMessage(request);}, evalScripts:true}); return false;
        
    }
};

function DEC2DMS(dec) {

	var deg = Math.floor(Math.abs(dec));
	var min = Math.floor((Math.abs(dec)-deg)*60);
	var sec = (Math.round((((Math.abs(dec) - deg) - (min/60)) * 60 * 60) * 100) / 100 ) ;

	deg = dec < 0 ? deg * -1 : deg;

	var dms  = deg + '&deg ' + min + '\' ' + sec + '"';
	return dms;
}

function encodeSignedNumber(num) {
	var sgn_num = num << 1;

	if (num < 0) {
		sgn_num = ~(sgn_num);
	}

	return(encodeNumber(sgn_num));
}

// Encode an unsigned number in the encode format.
function encodeNumber(num) {
	var encodeString = "";

	while (num >= 0x20) {
		encodeString += (String.fromCharCode((0x20 | (num & 0x1f)) + 63));
		num >>= 5;
	}

	encodeString += (String.fromCharCode(num + 63));
	return encodeString;
}

