// JavaScript Document
var xmlData;
var currentId;

/*Load Garmin Javascript data*/
function loadGarminScripts(){
	//<script src="/widget/js/prototype/prototype.js" type="text/javascript"></script>
	//<script src="/widget/js/garmin/device/GarminDeviceDisplay.js" type="text/javascript"></script>
	var js = document.createElement('script');
	var js2 = document.createElement('script');
	
	js.src = '/widget/js/prototype/prototype.js';
	js.type='text/javascript';
	
	js2.src = '/widget/js/garmin/device/GarminDeviceDisplay.js';
	js2.type='text/javascript';
	
	var head = document.getElementsByTagName('head')[0];
	head.appendChild(js);
	head.appendChild(js2);
}

/**
Function called to begin upload of waypoint to user device
**/
function writeCurrentWayPoint(deviceType, id){
	currentId = id;
	if(deviceType == 'garmin'){
		retrievePoiGPX();
	}else if(deviceType == 'tomtom'){
		//url = retrieveTomTomUrl();
		key = "842bedd2-b8ab-4252-b934-45bf69cfa3fa";
		window.open("http://addto.tomtom.com/api/home/v2/georeference?action=add&amp;apikey=842bedd2-b8ab-4252-b934-45bf69cfa3fa&amp;name=TomTom&amp;latitude=51.4989&amp;longitude=-0.1786&amp;source=http%3A//www.autopilot.ie");
	}
}

/**
Retrieves the current POI's xml from the server and on receiving the response it begins the upload.
**/
function retrievePoiGPX(){
	var xmlHttp2 = getXMLHttp();
	xmlHttp2.onreadystatechange = function(){
		if(xmlHttp2.readyState == 4){
			xmlData = xmlHttp2.responseText;
			initSatNav();
		}
	}
	xmlHttp2.open("GET", rootApplicationDirectory+"satNavDownload.php", true); 
	xmlHttp2.send("");
}

/**
Handles uploading of waypont GPX file as downloaded from satNavDownload.php
**/
function initSatNav(){
		var display = new Garmin.DeviceDisplay("garmin", {
		 pathKeyPairsArray:      ["http://www.autopilot.ie", "c676a28837d70b33b08a9df49c36adcd"], 
   	  	 unlockOnPageLoad: false, 					  //delays unlocking to avoid authorization prompt until action 
		 hideIfBrowserNotSupported: true,
		 showStatusElement: false,                    //provide minimal feedback
		 autoFindDevices: true,                       //it will search for devices upon action
		 showCancelFindDevicesButton: false,          //no need to cancel small data transfers
		 autoWriteData: true,                         //automatically write the data once devices found
		 showReadDataElement: false,
		 getWriteData: function() {return xmlData;},
		 getWriteDataFileName: function() {return currentId+"POI.gpx"},
		 afterFinishWriteToDevice: function(success, display) {
			  alert((success ? "POI added to your 'favourites' on your sat-nav!" : "POI wasn't added to your sat-nav!")); 
		 }
	});
}
