function ComoLlegarFichaInit() {
	var elm = document.getElementById('como_llegar_desde');
	if(elm) checkCookie();
}
window_onload.push('ComoLlegarFichaInit()');

function setDirections() {
	var elm = document.getElementById('como_llegar_desde');
	if(elm) {
		if(elm.value != '') {
			setCookie('geolocation', elm.value, 365);
		}
	}
}

function setDesde(geolocation)
{
	var elm = document.getElementById('como_llegar_desde');
	if(elm) {
		elm.value = geolocation;
		setDirections();
	}
}

function ipinfodb_init(geoDict)
{
	ipinfodb_CountryName = geoDict['CountryName'];
	ipinfodb_RegionName  = geoDict['RegionName'];
	ipinfodb_City        = geoDict['City'];
	ipinfodb_Latitude    = geoDict['Latitude'];
	ipinfodb_Longitude   = geoDict['Longitude'];

	if(ipinfodb_City != '' && ipinfodb_RegionName != '' && ipinfodb_CountryName != '') {
		setDesde(ipinfodb_City + ', ' + ipinfodb_RegionName + ', ' + ipinfodb_CountryName);
	} else {
		setDesde(geolocation = ipinfodb_Latitude + ', ' + ipinfodb_Longitude);
	}
}

function getCookie(c_name)
{
	if(document.cookie.length > 0) {
		c_start = document.cookie.indexOf(c_name + "=");
		if(c_start != -1) {
			c_start = c_start + c_name.length + 1;
			c_end = document.cookie.indexOf(";", c_start);
			if(c_end == -1) c_end = document.cookie.length;
			return unescape(document.cookie.substring(c_start, c_end));
		}
	}
	return '';
}

function setCookie(c_name, value, expiredays)
{
	var exdate = new Date();
	exdate.setDate(exdate.getDate() + expiredays);
	document.cookie = c_name + "=" + escape(value) + ((expiredays == null) ? '' : ";expires=" + exdate.toGMTString());
}

function checkCookie()
{
	geolocation = getCookie('geolocation');
	if(geolocation) {
		setDesde(geolocation)
	} else {
		script = document.createElement('script')
		// script.src = "http://ipinfodb.com/ip_query.php?output=json&callback=ipinfodb_init";
		script.src = "http://api.ipinfodb.com/v2/ip_query.php?key=ed35690336e1ccbc9d89111e71cf03baf0e189522067f92546eb57f8110f4a22&output=json&callback=ipinfodb_init&timezone=false";
		document.body.appendChild(script)
	}
}

