var COOKIE_NAME = 'wfp.logcluster.country';
var HTML_NODE = '#geoposition';
var ERROR_MSG = "<div id='nolocation'><p>No country profile for the country you are in</p></div>";

function readCookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}

function createCookie(name,value,days) {
	if (days) {
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	}
	else var expires = "";
	document.cookie = name+"="+value+expires+"; path=/";
}

function setCountryCookie(position) {
  lat = position.coords.latitude.toFixed(2)
  lon = position.coords.longitude.toFixed(2)

  if(!lat || !lon){
		countrycode = '';
	}else{
		geocode_url = "geocodeproxy?lat=" +lat + "&lon=" + lon;
		countrycode = jq.ajax({url: geocode_url, async: false}).responseText;
	}
  createCookie(COOKIE_NAME,countrycode,10);
  showCountry(countrycode)
}

function showCountry(countrycode){
	//inviare codice country tramite xmlhttpRequest
	var xmlhttp;
	if (window.XMLHttpRequest){
	  // code for IE7+, Firefox, Chrome, Opera, Safari
	  xmlhttp=new XMLHttpRequest();
	}
	else if (window.ActiveXObject){
	  // code for IE6, IE5
	  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
	}
	else{
	  alert("Your browser does not support XMLHTTP!");
	}
	xmlhttp.onreadystatechange=function(){
	  if(xmlhttp.readyState==4){
			if(countrycode){
				jq(HTML_NODE).replaceWith(xmlhttp.responseText)
			}else{
				jq(HTML_NODE).append(ERROR_MSG)
			}
	  }
	}
	
	xmlhttp.open("GET","@@country?code="+countrycode,true);
	xmlhttp.send(null);
}


var countrycode;
//leggere cookie e recuperare codice country
countrycode = readCookie(COOKIE_NAME)
if (!countrycode && geo_position_js.init()) {
  //recuperare codice country calcolato da geolocation
  geo_position_js.getCurrentPosition(setCountryCookie,function(){jq(HTML_NODE).append(ERROR_MSG);});
}else{
  showCountry(countrycode)
}
