google.load("earth", "1");
var ge = null;
var lineStringPlacemarks = new Array();
var lineCounter = 0;
var placemarkCounter = 0;
var placemark = null;
var refreshPlacemarksArr = new Array();
var justBounded = 0;
var endPanTimer = null;
var END_PAN_TIMER_DELAY = 700;
var geObjects = new Array();
var objCounter = 0;
geObjects[objCounter] = null;
var refreshnotrunyet = true;
var pcounter = 0;
var rplacemarks = new Array();
var viewSet = false;

var showInterval;
var anInterval;

// Global value to ensure scripts refer to correct URLS
var siteurl = location.protocol+"//"+location.hostname+((location.port.length>0&&location.port!=80&&location.port!=443)?":"+location.port:"");

var firstruntest = 0;



function GetMap() {
  google.earth.createInstance("map", initCallback, failureCallback);
}

function GetLIVEMap() {
  google.earth.createInstance("map", initCallbackLIVE, failureCallback);
}

function GetPASTLIVEMap() {
  google.earth.createInstance("map", initCallbackPASTLIVE, failureCallback);
}

function GetALLLIVEMap() {
  google.earth.createInstance("map", initCallbackALLLIVE, failureCallback);
}

function GetEDITMap() {
  google.earth.createInstance("map", initCallbackEDIT, failureCallback);
}

function GetEDITExistingMap() {
  google.earth.createInstance("map", initCallbackEDITExisting, failureCallback);
}

function initCallbackLIVE(object) {
  	ge = object;
  	ge.getWindow().setVisibility(true);
  
  	// add a navigation control
	ge.getNavigationControl().setVisibility(ge.VISIBILITY_AUTO);	
	ge.getOptions().setScaleLegendVisibility(true); 
	ge.getLayerRoot().enableLayerById(ge.LAYER_BORDERS, true);

	/*
	google.earth.addEventListener(ge.getView(), 'viewchangeend', function() {
    	viewTest();
	});
	*/
	UpdatePoints('live');	
}

function initCallbackPASTLIVE(object) {
  	ge = object;
  	ge.getWindow().setVisibility(true);
  
  	// add a navigation control
	ge.getNavigationControl().setVisibility(ge.VISIBILITY_AUTO);	
	ge.getOptions().setScaleLegendVisibility(true); 
	ge.getLayerRoot().enableLayerById(ge.LAYER_BORDERS, true);

	/*
	google.earth.addEventListener(ge.getView(), 'viewchangeend', function() {
    	viewTest();
	});
	*/
	UpdatePoints('pastlive');	
}

function initCallbackALLLIVE(object) {
  	ge = object;
  	ge.getWindow().setVisibility(true);
  
  	// add a navigation control
	ge.getNavigationControl().setVisibility(ge.VISIBILITY_AUTO);	
	ge.getOptions().setScaleLegendVisibility(true); 
	ge.getLayerRoot().enableLayerById(ge.LAYER_BORDERS, true);
	
	UpdatePoints('alllive');	
}

function initCallbackEDIT(object) {
  	ge = object;
  	ge.getWindow().setVisibility(true);
  
  	// add a navigation control
	ge.getNavigationControl().setVisibility(ge.VISIBILITY_AUTO);	
	ge.getOptions().setScaleLegendVisibility(true); 
	ge.getLayerRoot().enableLayerById(ge.LAYER_BORDERS, true);
	
	//for saving flights
	google.earth.addEventListener(ge.getView(), 'viewchangeend', function() {
    	getCameraAngle();
	});
  	getCameraAngle();  //on change	
	UpdatePoints('edit');	
}

function initCallbackEDITExisting(object) {
  	ge = object;
  	ge.getWindow().setVisibility(true);
  
  	// add a navigation control
	ge.getNavigationControl().setVisibility(ge.VISIBILITY_AUTO);	
	ge.getOptions().setScaleLegendVisibility(true); 
	ge.getLayerRoot().enableLayerById(ge.LAYER_BORDERS, true);
	
	//for saving flights
	google.earth.addEventListener(ge.getView(), 'viewchangeend', function() {
    	getCameraAngle();
	});
  	getCameraAngle();  //on change
	flightid = document.getElementById('flightid').value;
	var initialload = 'yes';
	UpdatePoints('edit',flightid,initialload);	
}

function initCallback(object) {
  	ge = object;
  	ge.getWindow().setVisibility(true);
  
  	// add a navigation control
	ge.getNavigationControl().setVisibility(ge.VISIBILITY_AUTO);	
	ge.getOptions().setScaleLegendVisibility(true); 
	ge.getLayerRoot().enableLayerById(ge.LAYER_BORDERS, true);

	UpdatePoints('saved');	
}

function failureCallback(object) {
}

function zoomto(zmlat,zmlng){
	var heading = 0;
	var tilt = 70;
	var range = 7000;
	
	var la = ge.createLookAt('');
	la.set(zmlat*1, zmlng*1, 0, ge.ALTITUDE_RELATIVE_TO_GROUND, heading*1, tilt*1, range*1);
	ge.getView().setAbstractView(la);
}

function refreshMap(){
	setTimeout("UpdatePoints('live-refresh')",2000);
	anInterval = setInterval("UpdatePoints('live-refresh')",10000); //get a batch of points every 30 sec   
}

function UpdatePoints (mtype,flightid,initialload){
	initialload = initialload || 'no';
	flightid = flightid || 0;	
	var autorefresh = false;
	var nozoom = false;
	
	if(mtype=='saved'){   //saved flights (time)
		var id = $("#fid").val();
		var fromval = 0;
		var toval = 0;
		var last = $("#detailh").val();  //use to pass detail (normal or high)		
		var altmode = 0;
		var units = $("input[@name='units']:checked").val();
		if($('#nozoom').val()=='1') nozoom = true;
	} 
	else if(mtype=='live'){   //live
		var id = $("#pid").val();
		var fromval = 0;
		var toval = 0;
		var last = $("#lastx").val();
		var altmode = ($('#clamp').val()=='clampToGround')?'clampToGround':'absolute';
		var units = 0;		
		// remove the old parsed KML objects if they exist		
		for(i=geObjects.length;i>=0;i--){
			if (geObjects[i]){ 
				ge.getFeatures().removeChild(geObjects[i]); 
			}								
		}
		//remove autorefresh items if they exist
		if(placemarkCounter>0) ge.getFeatures().removeChild(placemark);  //latest pin
		if(pcounter>0){  //photo/text
			for(i in rplacemarks){
				ge.getFeatures().removeChild(rplacemarks[i]);
			}		
		}		
		if(lineCounter>0){  //lines
			for(i in lineStringPlacemarks){
				ge.getFeatures().removeChild(lineStringPlacemarks[i]);
			}		
		}
	} 
	else if(mtype=='pastlive'){   //past live flights
		var id = $("#pastlive").val();
		var fromval = 0;
		var toval = 0;
		var last = 0;
		var altmode = ($('#clamp').val()=='clampToGround')?'clampToGround':'absolute';
		var units = 0;
	} 
	else if(mtype=='live-refresh'){   //live auto refresh points
		if(refreshnotrunyet){
			//start display loop
			showInterval = setInterval("showRefreshPoints()",900); //show new points every 1 sec	(slighly less to allow for overhead)
			refreshnotrunyet = false;
		}
		var id = $("#pid").val();
		var fromval = $("#maxtime").val();
		var toval = 0;
		var last = $("#lastx").val();
		var altmode = ($('#clamp').val()=='clampToGround')?'clampToGround':'absolute';
		var units = 0;
		mtype = 'live';
		autorefresh = true;		
	} 
	else if(mtype=='alllive'){   //all live users
		var id = 0;
		var fromval = 0;
		var toval = 0;
		var last = 0;
		var altmode = 0;
		var units = 0;
	} 
	else if(mtype=='edit'){   //flight editor
		var fromval = $("#from").val();
		var toval = $("#to").val();
		var last = 0;
		var altmode = $("#altmode_hid").val();		
		updateTimes(fromval, toval);		
		var id = $("#phoneid").val();		
		if(flightid > 0){
			var units = flightid;	
		} else { 
			var units = 0;
		}		
		if((initialload != 'yes')&&(flightid!=0)){ nozoom = true; }
		
	}

	var baseurl= siteurl+"/includes/genkml.php?ran=" + (Math.random()*1000) + "&";
	baseurl += "fdate=" + fromval + "&tdate=" + toval + "&id=" + id + "&last=" + last + "&mode=" + mtype + "&am=" + altmode + "&units=" + units;
	loadXMLDoc(baseurl,autorefresh,nozoom,mtype);

	if((mtype=='live')){
		updateMaxTime();
	}
}

function updateMaxTime(){
	var url = siteurl+"/includes/getMaxtime.php?ran=" + (Math.random()*1000) + "&id=" +  $("#pid").val();
	var request = window.XMLHttpRequest ?
	new XMLHttpRequest() : new ActiveXObject("MSXML2.XMLHTTP.3.0");
	request.open("GET", url, true);
	request.setRequestHeader("Content-Type", "text/xml");

	request.onreadystatechange = function()
	{
		if (request.readyState == 4 && request.status == 200)
		{
			if (request.responseText)
			{				
				if($("#maxtime").val() == '0'){ 
					var latesttime = request.responseText - 30;
				} else {
					var latesttime = request.responseText;
				}
				$("#maxtime").val(latesttime);
			}
		}
	};
	
	request.send(null);

}


function loadXMLDoc(url,autorefresh,nozoom,mtype){	
	var request = window.XMLHttpRequest ?
	new XMLHttpRequest() : new ActiveXObject("MSXML2.XMLHTTP.3.0");
	request.open("GET", url, true);
	request.setRequestHeader("Content-Type", "text/xml");

	request.onreadystatechange = function()
	{

		if (request.readyState == 4 && request.status == 200)
		{
			if (request.responseText)
			{				
				var found = true;				
				if(!autorefresh){
					// remove the old parsed KML objects if they exist
					for(i=geObjects.length;i>=0;i--){
						if (geObjects[i]){ 
							ge.getFeatures().removeChild(geObjects[i]); 
						}								
					}
				}					
				
				if(!autorefresh){	
					//extract view settings
					extractor=/<LookAt>(.*)<\/LookAt>/;
					try {
						var lookat=extractor.exec(request.responseText)[1];
					} catch (ex){							
						if(!autorefresh) $('#nottracked').css({"display":"block"});
					}
					if(!nozoom){
						$('#nottracked').css({"display":"none"});
						extractor=/<longitude>(.*)<\/longitude>/;
						var lng=extractor.exec(lookat)[1];
						extractor=/<latitude>(.*)<\/latitude>/;
						var lat=extractor.exec(lookat)[1];
						extractor=/<range>(.*)<\/range>/;
						var range=extractor.exec(lookat)[1];
						extractor=/<tilt>(.*)<\/tilt>/;
						var tilt=extractor.exec(lookat)[1];	
						extractor=/<heading>(.*)<\/heading>/;
						var heading=extractor.exec(lookat)[1];	
						//alt not used
	
						var la = ge.createLookAt('');
						la.set(lat*1, lng*1, 0, ge.ALTITUDE_RELATIVE_TO_GROUND, heading*1, tilt*1, range*1);						
						ge.getView().setAbstractView(la);
						viewSet = true;
					} 
					//apply kml
					try {		
						
					//if(geObjects[objCounter]) ge.getFeatures().removeChild(geObjects[objCounter]);  //clear markers
						geObjects[objCounter] = ge.parseKml(request.responseText);
						ge.getFeatures().appendChild(geObjects[objCounter]);
						
					} catch (ex) {
						alert('Parse error');
					} 				
				} else {	//  AUTO REFRESH 
						
					//push points onto array						
					/*
						|lat,lng,alt,text,photo|-34.456,145.7666,233,-,2345235423452345.jpg|
					*/
					var finalPointsArr = new Array();
					var pntsArr = request.responseText.split("/*/");
					for(i in pntsArr){						
						var parts = pntsArr[i].split('|*|');							
						var count = 0;
						if(pntsArr[i]!=''){
							for(j in parts){						
								if(count==0) var lat = parts[j];
								else if(count==1) var lng = parts[j];
								else if(count==2) var alt = parts[j];
								else if(count==3) var txt = parts[j];
								else if(count==4) var phot = parts[j];								
								count++;
							}											
							refreshPlacemarksArr.push(new Array(lat,lng,alt,txt,phot));					
						}
					}									
					
				}
				
				//clear loadergif
				if(mtype=='pastlive'){
					$('.loadergif').css('display','none');
				}
				
			}
		}
	};
	
	request.send(null);

}

function showRefreshPoints(){	
	
	//remove initial load placemark		
	if((placemarkCounter==0)&&(refreshPlacemarksArr.length>1)){		
		if(geObjects[objCounter]){
			var child1features = geObjects[objCounter].getFeatures();						
			
			var features = child1features.getChildNodes();						
			for(var i = 0; i < features.getLength(); i++)
			{						
				var feat = features.item(i);
				if(feat.getName() == 'Latest Position'){
					child1features.removeChild(feat); 
				}
			} 	
		}
	}
	
	
	//read one, then pop one
	//
	var thisPoint = refreshPlacemarksArr[0]; 
	var nextPoint = refreshPlacemarksArr[1];
	
	
	if(typeof(nextPoint) !== 'undefined'){
	
		//set view if needed
		if(!viewSet){
			var la = ge.createLookAt('');
			la.set(thisPoint[0]*1, thisPoint[1]*1, 0, ge.ALTITUDE_RELATIVE_TO_GROUND, 0, 30, 38000);						
			ge.getView().setAbstractView(la);
			viewSet = true;
		}
		
		var tmpp = refreshPlacemarksArr.shift();  //takes it off the front of the queue
		//setup ge line
		var lineStringPlacemark = ge.createPlacemark('');
		var lineString = ge.createLineString('');
		lineStringPlacemark.setGeometry(lineString);												
		lineString.setAltitudeMode(ge.ALTITUDE_ABSOLUTE);
				
		//create 'latest position' placemark								
		createPlacemarkp(nextPoint[0]*1, nextPoint[1]*1, nextPoint[2]*1);								
							
		//create 'statustext' placemark if required
		if(thisPoint[3]!='-') createPhotoTextPlacemark(thisPoint[0]*1, thisPoint[1]*1, thisPoint[2]*1,'text',thisPoint[3]);								
		
		//create 'photo' placemark if required
		if(thisPoint[4]!='-') createPhotoTextPlacemark(thisPoint[0]*1, thisPoint[1]*1, thisPoint[2]*1,'photo',thisPoint[4]);		
		
		//add to line
		lineString.getCoordinates().pushLatLngAlt(thisPoint[0]*1, thisPoint[1]*1, thisPoint[2]*1);  //this point
		lineString.getCoordinates().pushLatLngAlt(nextPoint[0]*1, nextPoint[1]*1, nextPoint[2]*1);  //next point
		
		// Create a style and set width and color of line
		lineStringPlacemark.setStyleSelector(ge.createStyle(''));
		var lineStyle = lineStringPlacemark.getStyleSelector().getLineStyle();
		lineStyle.setWidth(6);
		lineStyle.getColor().set('990e0edc');  // aabbggrr format
		
		if($('#clamp').val()=='absolute'){
			lineString.setAltitudeMode(ge.ALTITUDE_ABSOLUTE);
		} else {
			lineString.setAltitudeMode(ge.ALTITUDE_CLAMP_TO_GROUND);
		}
		
		//display line segment
		ge.getFeatures().appendChild(lineStringPlacemark);
		lineStringPlacemarks[lineCounter] = lineStringPlacemark;
		lineCounter++;

	} 


	
}

function createPhotoTextPlacemark(lat,lng,alt,pintype,pdata) {		
	//determine placemark type
	var pinUrl = '';
	var phtml = '';
	if(pintype=='photo'){
		pinUrl = 'http://www.gpslogbooks.com/images/pushpin_photo.png';
		phtml = '<div class="popup-box-thumb"><a href="/photos/' + pdata + '" target="_blank"><img src="/photos/preview/' + pdata + '" /></a></div>';
	} else if(pintype=='text'){
		pinUrl = 'http://www.gpslogbooks.com/images/pushpin_text.png';
		phtml = '<div>' + pdata + '</div>';
	}
		
	rplacemark = ge.createPlacemark('');	
	
	// Create style map for placemark
	var icon = ge.createIcon('');	
	icon.setHref(pinUrl);
	var style = ge.createStyle('');
	style.getIconStyle().setIcon(icon);
	rplacemark.setStyleSelector(style);

	// Create point	
	var point = ge.createPoint('');
	point.setLatitude(lat);
	point.setLongitude(lng);
	point.setAltitude(alt);
	
	if($('#clamp').val()=='absolute'){
		point.setAltitudeMode(ge.ALTITUDE_ABSOLUTE);
	} else {
		point.setAltitudeMode(ge.ALTITUDE_CLAMP_TO_GROUND);
	}
	
	rplacemark.setGeometry(point);	
	ge.getFeatures().appendChild(rplacemark);
	
	google.earth.addEventListener(rplacemark, 'click', function(event) {
		// prevent the default balloon from popping up
		event.preventDefault();		
		var balloon = ge.createHtmlStringBalloon('');
		balloon.setFeature(this); // optional
		balloon.setMaxWidth(200);		  		
		balloon.setContentString(phtml);		  
		ge.setBalloon(balloon);
	});
	
	rplacemarks[pcounter] = rplacemark;  //needed for later clearing		
	pcounter++;
	
}

function createPlacemarkp(lat,lng,alt) {
	
	if(placemarkCounter>0) ge.getFeatures().removeChild(placemark);  //don't try to remove if none there

	//determine placemark type
	var pinUrl = 'http://www.gpslogbooks.com/images/pushpin_pin.png';		
	
	placemark = ge.createPlacemark('');
	placemark.setName("Latest Position");
		
	ge.getFeatures().appendChild(placemark);
	
	// Create style map for placemark
	var icon = ge.createIcon('');	
	icon.setHref(pinUrl);
	var style = ge.createStyle('');
	style.getIconStyle().setIcon(icon);
	placemark.setStyleSelector(style);

	// Create point	
	var point = ge.createPoint('');
	point.setLatitude(lat);
	point.setLongitude(lng);
	point.setAltitude(alt);
	
	if($('#clamp').val()=='absolute'){
		point.setAltitudeMode(ge.ALTITUDE_ABSOLUTE);
	} else {
		point.setAltitudeMode(ge.ALTITUDE_CLAMP_TO_GROUND);
	}
	
	placemark.setGeometry(point);

	placemarkCounter++;
}



function getCameraAngle(){
	// Get the current view
	var lookAt = ge.getView().copyAsLookAt(ge.ALTITUDE_ABSOLUTE);

	// update form values
	document.getElementById('camlat').value = lookAt.getLatitude();
	document.getElementById('camlng').value = lookAt.getLongitude();
	document.getElementById('camrng').value = lookAt.getRange();
	document.getElementById('camhead').value = lookAt.getHeading();
	document.getElementById('camtilt').value = lookAt.getTilt();		
	
}

function viewTest(){
	// Get the current view
	var lookAt = ge.getView().copyAsLookAt(ge.ALTITUDE_ABSOLUTE);
}

function sortNumber(a,b){
	return a - b;
}



function getInter(time1,time2){
	if(time1==time2){ return 0 }
	return ((time2 - time1)/7).toFixed(2); 
}

function getColour(time1,segments,ms){
	
	var diff = ms - time1; //diff bw time and first time
	var out = (Math.floor(diff/segments)+1);
	if(out>7) out = 7;	
	return out;
}


function getDateName(num){
	var allMonths = new Array("Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec");
	return allMonths[num];
}

function getHoursAmPm(hrs){
	var timeArr = new Array(0,"am");
	if(hrs<1){
		timeArr[0] = 12;		
	} else if(hrs>11){
		timeArr[0] = hrs - 12;
		if(hrs==12){ timeArr[0] = hrs; }		
		timeArr[1] = "pm"
	} else {
		timeArr[0] = hrs;
	}
	return timeArr;
}

function battImg(lvl){
	if((lvl>=0)&&(lvl<20)){ return 'batt0.png'; }
	else if((lvl>=21)&&(lvl<40)){ return 'batt21.png'; }	
	else if((lvl>=41)&&(lvl<60)){ return 'batt41.png'; }	
	else if((lvl>=61)&&(lvl<80)){ return 'batt61.png'; }	
	else if(lvl>=81){ return 'batt81.png'; }
}

function sdopImg(lvl){
	if((lvl>0)&&(lvl<20)){ return 'sig1.png'; }
	else if((lvl>=20)&&(lvl<50)){ return 'sig2.png'; }	
	else if((lvl>=50)&&(lvl<90)){ return 'sig3.png'; }	
	else if((lvl>=90)&&(lvl<100)){ return 'sig4.png'; }	
	else { return 'signone.png'; }
}

function setLegend(time1,time2,segments){
	//	alert(time1 + ' ' + time2 + ' ' + segments);
	scaleextra = document.getElementById('scale_extra');
	
	if(time2 > 0){	
		var month=new Array(12);
		month[0]="Jan";
		month[1]="Feb";
		month[2]="Mar";
		month[3]="Apr";
		month[4]="May";
		month[5]="Jun";
		month[6]="Jul";
		month[7]="Aug";
		month[8]="Sep";
		month[9]="Oct";
		month[10]="Nov";
		month[11]="Dec";
		
		var latestd = new Date();
		latestd.setTime(time2*1000);
		
		if(document.getElementById('scale_latest')){
			scalelatest = document.getElementById('scale_latest');
			
			scalelatest.innerHTML = '<div><img width="13px" height="12px" src="images/0_sm.png" /><span style="color:#680d0d;font-weight:bold">' + month[latestd.getMonth()] + ' ' + latestd.getDate() + ', ' + latestd.getHours() + ':' + padNum(latestd.getMinutes()) + ':' + padNum(latestd.getSeconds()) + '</span></div>';
			
			for(i=7;i>0;i--){
				aSpan = document.getElementById('scale'+i);	
				if(i==7){ seg1 = 'up'; } else { seg1 = getTimeVal(segments*-(i-7)); }  //gets segment ranges
				seg2 = getTimeVal(segments*-(i-8));
				aSpan.innerHTML = '<div><img width="13px" height="12px" src="images/' + i + '_sm.png" /><strong>' + seg1 + '</strong> to <strong>' + seg2 + '</strong> *</div>';
			}
					
			scaleextra.innerHTML = '<br />&nbsp;* time from latest point';
		}
		
	} else { 	
		scalelatest = document.getElementById('scale_latest');
		scalelatest.innerHTML = '<div><img width="13px" height="12px" src="images/0_sm.png" /><strong>Latest points</strong></div>'; 
		
		for(i=7;i>0;i--){  // remove legend items
			aSpan = document.getElementById('scale'+i);	
			aSpan.innerHTML = '';
		}		
		scaleextra.innerHTML = '';
	}

}

function padNum(num){  //used to pad out the time display with 0's if needed
	if(num<10){ 
		return '0' + num; 
	} else { return num }
}

function getTimeVal(segments){
		if(segments<60){ //less than a minute
			return roundNumber(segments,1) + 'sec';
		} else if(segments<(60*60)){ //less than an hour
				return roundNumber((segments/60),1) + 'min';
		} else if(segments<(60*60*24)){  //less than a day
				return roundNumber((segments/60/60),1) + 'hrs';
		} else {  // days
				return roundNumber((segments/60/60/24),1) + 'days';
		}
}

function roundNumber(num, dec) {
	var result = Math.round(num*Math.pow(10,dec))/Math.pow(10,dec);
	return result;
}

function checkage ( days, hours, mins )
{
	if ( days == 0 && hours == 0 && mins < 5 )
		return 1;
	
	if ( days == 0 && hours == 0 && ( mins >= 5 && mins < 15 ) )
		return 2;
		
	if ( days == 0 && hours == 0 && ( mins >= 15 && mins <= 59 ) )
		return 3;
		
	if ( days == 0 && ( hours >= 1 && (hours <= 5 && mins <= 59) ) )
		return 4;
		
	if ( days == 0 && ( hours >= 6 && (hours <= 23 && mins <= 59) ) )
		return 5;
		
	if ( days == 1 )
		return 6;
				
	if ( days >= 2 )
		return 7;	
}

function AddPushpin( lat, lng, pnttime, spd, age, layer )
{

}
	


//show a loading label
function ShowLoading()
{
//  alert('asdf');
  var el = document.createElement("div"); 
  el.setAttribute('id',"VELoading");
  //Now we should know the width and height of the VE map or else go and get it.
  var curr_width = 642;
  var curr_height = 483;
  el.style.top = ((curr_height - 25) / 2) + "px";
  el.style.left = ((curr_width - 105) / 2) + "px";
//  el.style.top = '650px';
//  el.style.left = '500px';
  el.style.border = "1px solid gray";
  el.style.font = "12px arial";
  el.style.background = "White";
  el.style.padding = "2px";
  el.style.verticalAlign = "middle";
  el.innerHTML = "<img src='images/spinner.gif' /> Please Wait. Loading data....";  
  map.AddControl(el);
}

//remove loading label
function HideLoading()
{
  var el = document.getElementById("VELoading");
  el.parentNode.removeChild(el);
}

function updateTimes(int1, int2)
{
	
	$('#timestart').html(getClockDateTime(int1));
	$('#timeend').html(getClockDateTime(int2));

}

function padDate(num)
{
		if(num < 10){
			return "0" + num;
		} else return num;
}

function getClockDateTime(int1)
{   
   var newMilli = int1*1000;

   var adate    = new Date();
   adate.setTime(newMilli);
   var day = adate.getDay();
   var hour   = adate.getHours();
   var minutes   = adate.getMinutes();
   var seconds   = adate.getSeconds();
   var date = adate.getDate();
   var month = adate.getMonth();
   var ayear = adate.getFullYear();

   var ap = "am";
   if (hour   > 11) { ap = "pm";             }
   if (hour   > 12) { hour = hour - 12;      }
   if (hour   == 0) { hour = 12;             }
   if (hour   < 10) { hour   = hour;   }
   
   var montharr=new Array(12);
	montharr[0]="Jan";
	montharr[1]="Feb";
	montharr[2]="Mar";
	montharr[3]="Apr";
	montharr[4]="May";
	montharr[5]="Jun";
	montharr[6]="Jul";
	montharr[7]="Aug";
	montharr[8]="Sep";
	montharr[9]="Oct";
	montharr[10]="Nov";
	montharr[11]="Dec";
	
   var dlab = "th";
   if((date==1)||(date==21)||(date==31)){ dlab = "st" };
   if((date==2)||(date==22)){ dlab = "nd" };
   if((date==3)||(date==23)){ dlab = "rd" };

   var daynames = ['Sun','Mon','Tue','Wed','Thu','Fri','Sat'];
   var timeString = daynames[day] + " " + date + dlab + " " + montharr[month] + " " + ayear + ", " + hour + ':' + padDate(minutes) + ':' + padDate(seconds) + ' ' + ap;

   return timeString;
} // function getClockTime()

function moveTime(num){	
	var marker = document.getElementById("mark").value;
	var timeInput = document.getElementById(marker);
	timeInput.value = timeInput.value*1 + (num*1);
	
	UpdatePoints('edit');
}

function moveExistingTime(num){	
	var marker = document.getElementById("mark").value;
	var timeInput = document.getElementById(marker);
	timeInput.value = timeInput.value*1 + (num*1);
	var flightid = document.getElementById('flightid').value;
	UpdatePoints('edit',flightid);
}

function altMode(mode){	
	$('#altmode_hid').val(mode);
	UpdatePoints('edit');
}

function altModeExisting(mode){	
	$('#altmode_hid').val(mode);
	var flightid = document.getElementById('flightid').value;
	UpdatePoints('edit',flightid);
}

function altToGround(){
	//console.log($('#clamp').attr('checked'));
}

function openpopup(url) 
{
var oNewWin = window.open(
	url,
	'geopop',
	'width=480,height=320,toolbar=0,location=0,directories=0,status=0,menubar=0,scrollbars=1,resizable=0').scrollTo(0, 256);
oNewWin.focus();
}



