/*!
 * Ajax
 *
 * Date: 16 Aug 2010  
 */
var req;

function getXHR()
{
	if(window.XMLHttpRequest) {
		req = new XMLHttpRequest();
		return true;
	}
	else try {
		req = new ActiveXObject('Msxml2.XMLHTTP');
		return true;
	} catch(e) {
		try {
			req = new ActiveXObject("Microsoft.XMLHTTP");
			return true;
		} catch(e) {
			req = false;
			return false;
		}
	}
}

function updateElm(url, id)
{
	if(getXHR())
	{
		req.open('POST', url, true);
		req.onreadystatechange = function()
		{
			if(req.readyState == 4) {
				if(req.status == 200) {
					document.getElementById(id).innerHTML = req.responseText;
				}
			} 
		}
		req.send('');
	}
	else return true;
	return false;
}

function add_debug_msg(str)
{	
	msg = document.getElementById('debug').innerHTML;
    document.getElementById('debug').innerHTML = msg + '<br />' + str;
}

function getloc()
{	
	host = window.location.host;
	if(host == 'localhost'){host = host + '/city.mobi/www/index.php';}
	href = window.location.protocol + '//' + host + '/location/';
	
	document.getElementById('uloc').innerHTML = '<a href="' + href + '">Locating ...</a>';
	
	if(geo_position_js.init())
	{		
		geo_position_js.getCurrentPosition(loc_success,loc_error,{enableHighAccuracy:false});
	}
}

function loc_success(loc)
{			
	host = window.location.host;
	if(host == 'localhost'){host = host + '/city.mobi/www/index.php';}
	
	// href url
	href = window.location.protocol + '//' + host + '/location/';
	
	// ajax url
	ajaxurl = window.location.protocol + '//' + host + '/location/auto_detect/lat/' + loc.coords.latitude + '/lon/' + loc.coords.longitude;
		
	document.getElementById('uloc').innerHTML = '<a href="' + href + '">Found location</a>';
			
	updateElm(ajaxurl, 'uloc');
}
			
function loc_error(e)
{	
	host = window.location.host;
	if(host == 'localhost'){host = host + '/city.mobi/www/index.php';}
	url = window.location.protocol + '//' + host + '/location/auto_detect/err/' + escape(e.message);
	updateElm(url, 'uloc');
}

function api_fail()
{
	host = window.location.host;
	if(host == 'localhost'){host = host + '/city.mobi/www/index.php';}
	url = window.location.protocol + '//' + host + '/location/auto_detect/fail/api';
	updateElm(url, 'uloc');
}

/*!
 * geo-location-javascript v0.4.3
 * http://code.google.com/p/geo-location-javascript/
 *
 * Copyright (c) 2009 Stan Wiechers
 * Licensed under the MIT licenses.
 *
 * Revision: $Rev: 68 $: 
 * Author: $Author: whoisstan $:
 * Date: $Date: 2010-02-15 13:42:19 +0100 (Mon, 15 Feb 2010) $:
 *
 * NOTE: Removed all comments, see test script for more info    
 */
var bb_successCallback;
var bb_errorCallback;
var bb_blackberryTimeout_id=-1;

function handleBlackBerryLocationTimeout()
{
	if(bb_blackberryTimeout_id!=-1)
	{
		bb_errorCallback({message:"Timeout error", code:3});
	}
}

function handleBlackBerryLocation()
{
	clearTimeout(bb_blackberryTimeout_id);
	bb_blackberryTimeout_id=-1;
	if (bb_successCallback && bb_errorCallback)
	{
		if(blackberry.location.latitude==0 && blackberry.location.longitude==0)
		{
			bb_errorCallback({message:"Position unavailable", code:2});
		}
		else
		{  
			var timestamp=null;

			if (blackberry.location.timestamp)
			{
				timestamp=new Date(blackberry.location.timestamp);
			}
			bb_successCallback({timestamp:timestamp, coords: {latitude:blackberry.location.latitude,longitude:blackberry.location.longitude}});
		}
		
		bb_successCallback = null;
		bb_errorCallback = null;
	}
}

var geo_position_js=function()
{
	var pub = {};
	var provider=null;
	
	pub.getCurrentPosition = function(successCallback,errorCallback,options)
	{				
		provider.getCurrentPosition(successCallback,errorCallback,options);
	}
	
	pub.init = function()
	{		
		try
		{			
			if (typeof(bondi)!="undefined" && typeof(bondi.geolocation)!="undefined")
			{				
				provider=bondi.geolocation;
			}
			else if (typeof(navigator.geolocation)!="undefined")
			{				
				provider=navigator.geolocation;
				pub.getCurrentPosition = function(successCallback, errorCallback, options)
				{
					function _successCallback(p)
					{
						if(typeof(p.latitude)!="undefined")
						{
							successCallback({timestamp:p.timestamp, coords: {latitude:p.latitude,longitude:p.longitude}});
						}
						else
						{
							successCallback(p);
						}
					}
					provider.getCurrentPosition(_successCallback,errorCallback,options);
				}
			}
			else if(typeof(window.blackberry)!="undefined" && blackberry.location.GPSSupported)
			{				
				if(typeof(blackberry.location.setAidMode)=="undefined")
				{
					return false;									
				}
				
				blackberry.location.setAidMode(2);
				pub.getCurrentPosition = function(successCallback,errorCallback,options)
				{
					bb_successCallback=successCallback;
					bb_errorCallback=errorCallback;

					if(options['timeout'])  
					{
						bb_blackberryTimeout_id=setTimeout("handleBlackBerryLocationTimeout()",options['timeout']);
					}
					else
					{
						bb_blackberryTimeout_id=setTimeout("handleBlackBerryLocationTimeout()",60000);
					}										
					blackberry.location.onLocationUpdate("handleBlackBerryLocation()");
					blackberry.location.refreshLocation();
				}
				provider=blackberry.location;				
			}	
			else if(typeof(window.google)!="undefined" && typeof(google.gears)!="undefined")
			{				
				provider=google.gears.factory.create('beta.geolocation');
			}
			else if ( typeof(Mojo) !="undefined" && typeof(Mojo.Service.Request)!="Mojo.Service.Request")
			{				
				provider=true;
				pub.getCurrentPosition = function(successCallback, errorCallback, options)
				{				
					parameters={};
					if(options)
					{
						if (options.enableHighAccuracy && options.enableHighAccuracy==true)
						{
							parameters.accuracy=1;
						}
						if (options.maximumAge)
						{
							parameters.maximumAge=options.maximumAge;
						}
						if (options.responseTime)
						{
							if(options.responseTime<5)
							{
								parameters.responseTime=1;
							}
							else if (options.responseTime<20)
							{
								parameters.responseTime=2;
							}
							else
							{
								parameters.timeout=3;
							}
						}
					}
										
					r=new Mojo.Service.Request('palm://com.palm.location', {
					method:"getCurrentPosition",
					parameters:parameters,
					onSuccess: function(p){successCallback({timestamp:p.timestamp, coords: {latitude:p.latitude, longitude:p.longitude,heading:p.heading}});},
						onFailure: function(e){
							if (e.errorCode==1)
							{
								errorCallback({code:3,message:"Timeout"});
							}
							else if (e.errorCode==2)
							{
								errorCallback({code:2,message:"Position Unavailable"});
							}
							else
							{
								errorCallback({code:0,message:"Unknown Error: webOS-code"+errorCode});
							}
						}
					});
				}
			}
			else if (typeof(device)!="undefined" && typeof(device.getServiceObject)!="undefined")
			{				
				provider=device.getServiceObject("Service.Location", "ILocation");
				
				pub.getCurrentPosition = function(successCallback, errorCallback, options)
				{
					function callback(transId, eventCode, result) {
						if (eventCode == 4)
						{
							errorCallback({message:"Position unavailable", code:2});
						}
						else
						{
							successCallback({timestamp:null, coords: {latitude:result.ReturnValue.Latitude, longitude:result.ReturnValue.Longitude, altitude:result.ReturnValue.Altitude,heading:result.ReturnValue.Heading}});
						}
					}
					
					var criteria = new Object();
					criteria.LocationInformationClass = "BasicLocationInformation";
					provider.ILocation.GetLocation(criteria,callback);
				}
			}
			else
			{				
				api_fail();
				
				return false;	
			}
		}
		catch (e)
		{			
			alert("error="+e);
			if(typeof(console)!="undefined")
			{
				console.log(e);
			}
			return false;
		}
		return  provider!=null;
	}
	
	return pub;
}();
