ii.retry_on_error = 60000;
ii.log_to_console = true;

function handleError() {
	ii.log('error retrieving position');
	setLocateIcon('error');
	if (!ii.retry_on_error)
		return;

	window.setTimeout(locateme, ii.retry_on_error);
}

repeatLast = 0;
function updatePos(pos, resp) {
	ii.log('UPDATEPOS CALLED WITH '+pos+', '+resp);

	if (repeatLast)
		window.clearTimeout(repeatLast);

	if (!resp)
	{
		var coords = pos.coords;

		setLocateIcon('waiting');
		ii.log('sending position: '+coords.latitude+'x'+coords.longitude);
		var params = { lat:coords.latitude, lon:coords.longitude};
		var key = ii.getCookieValue('sessionkey');
		if (key)
			params.key = key;
		ii.get(
			'p-new-loc',
			function(resp) {
				updatePos(pos, resp);
			}, params
		);
		return;
	};
	
	setLocateIcon('active');

	if (window.map) {
		updateMePos(pos.coords.latitude, pos.coords.longitude);
	}
	ii.zoomOnLocation = false;

	ii.setCookie('located', 
			''+pos.coords.latitude+'x'+pos.coords.longitude,
			0);

	repeatLast = window.setTimeout(function() {
		updatePos(pos); }, 1000 * 12);
}
$(function() {
	ii.init();
	return;
});

$(function() { 

});

$(function() { 
	if (ii.getCookieValue('located')) {
		console.log('still locating..');
		locateme();
	}
});

function locateAndZoomMe() {
	ii.zoomOnLocation = true;
	locateme();
}

watchId = 0;
function locateme() {
	
	// get position one-time to set-cookie
	if (navigator.geolocation)
	{
		//navigator.geolocation.clearWatch(watchId);
		var options = {
			enableHighAccuracy: true,
			timeout: 1000 * 60 , 
			maximumAge: 0 
		}
		ii.log('starting watch');
		watchId = navigator.geolocation.watchPosition(
				updatePos, handleError, options);

		setLocateIcon('waiting');
	}
}

function setLocateIcon(type) {
	ii.log('setting locate icon: '+type);

	if ($('#locateme_btn').length == 0)
		return;

	$('#locateme_btn')[0].className = type;

	if (window.flickerTimer)
		window.clearInterval(window.flickerTimer);
	if (type == 'active')
	{
		var lb = $('#locateme_btn');
		window.flickerTimer = window.setInterval(function() {
			ii.log(lb[0].className);
			if (lb[0].className == 'active')
				lb[0].className = 'active_off';
			else
				lb[0].className = 'active';

		}, 900)
	}
}


