
//se ejecuta primero 	function loadLocation()  LINEA 160 aprox//

	// FALLO EN 293: ME OBLIGA a poner IP Mode, cuando debería detectar el if y no tener que esperar a un refresh para detectar la cookie
	

		//CODIGO DE GEO IP //
		
		
		function geolocate(timezone, cityPrecision) {
   var key ="c9c3663bcb9112e09db18d00da8d206bd8ced2cd24f6ae5cd8cfaf449b419cb8";
  var api = (cityPrecision) ? "ip-city" : "ip-country";
  var domain = 'api.ipinfodb.com';
  var version = 'v3';
  var url = "http://" + domain + "/" + version + "/" + api + "/?key=" + key + "&format=json" + "&callback=?";
  var geodata;
  var JSON = JSON || {};
  
  // implement JSON.stringify serialization
  JSON.stringify = JSON.stringify || function (obj) {
    var t = typeof (obj);
    if (t != "object" || obj === null) {
      // simple data type
      if (t == "string") obj = '"'+obj+'"';
        return String(obj);
    } else {
    // recurse array or object
      var n, v, json = [], arr = (obj && obj.constructor == Array);
      for (n in obj) {
        v = obj[n]; t = typeof(v);
        if (t == "string") v = '"'+v+'"';
        else if (t == "object" && v !== null) v = JSON.stringify(v);
        json.push((arr ? "" : '"' + n + '":') + String(v));
      }
      return (arr ? "[" : "{") + String(json) + (arr ? "]" : "}");
    }
  };
  
  // implement JSON.parse de-serialization
  JSON.parse = JSON.parse || function (str) {
    if (str === "") str = '""';
      eval("var p=" + str + ";");
      return p;
  };
  
 
  //Check if cookie already exist. If not, query IPInfoDB
  this.checkcookie = function(callback) {
    geolocationCookie = getCookie('geolocation');
   // if (!geolocationCookie) { // SIEMPRE REDETECTAMOS GEOIP 
      getGeolocation(callback);
    /*} else {
      geodata = JSON.parse(geolocationCookie);
      callback();
    }*/
  }
  
  //Return a geolocation field
  this.getField = function(field) {
    try {
      return geodata[field];
    } catch(err) {}
  }
		
		  //Request to IPInfoDB
  function getGeolocation(callback) {
    try {
      $.getJSON(url,
      function(data){
        if (data['statusCode'] == 'OK') {
          geodata = data;
          JSONString = JSON.stringify(geodata);
          setCookie('geolocation', JSONString, 365);
          callback();
        }
      });
    } catch(err) {}
  }
  


  //Set the cookie
  function setCookie(c_name, value, expire) {
    var exdate=new Date();
    exdate.setDate(exdate.getDate()+expire);
    document.cookie = c_name+ "=" +escape(value) + ((expire==null) ? "" : ";expires="+exdate.toGMTString());
  }
  

  //Get the cookie content
  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 getgeoip()
{
	        
	/*INTENTAMOS CONSEGUIR LA GEO DESDE IP */
var visitorGeolocation = new geolocate(false, true);

//Check for cookie and run a callback function to execute after geolocation is read either from cookie or IPInfoDB API
//$(document).ready(function(){alert(visitorGeolocation.getField('countryCode'))}) doesnt work with google Chrome, this is why a callback is used instead
//setTimeout(alert('Visitor country code : ' + visitorGeolocation.getField('countryCode')),9000);


var callback = function(){
          // alert('Visitor country code : ' + visitorGeolocation.getField('countryCode'));
				//alert('Visitor country code : ' + visitorGeolocation.getField('latitude'));
				  $.cookie("posLat", visitorGeolocation.getField('latitude') , { expires: 111});
				    $.cookie("posLon", visitorGeolocation.getField('longitude'), { expires: 111});
				
               };
visitorGeolocation.checkcookie(callback);
	

// document.write(document.cookie);//escribe en pantalla las cookies activas
}


// FIN CODIGO IP











//CODIGO GEO HTML5


  var latitude;
    var longitude;
    var accuracy;
	 var latitude;
    var longitude;
    var accuracy;
	
	var state
	
	
	function loadLocation() {
    
        if(navigator.geolocation) {
            document.getElementById("status").innerHTML = "Detecting location...";
           // document.getElementById("status").style.color = "#1ABC3C";
            
            if($.cookie("posLat")) {
				
				 getshowcookiegeo() ;
                //updateDisplay();
				// lo pasamos a las variables de sesión

					var url2 = '2service/geo.php?lat='+latitude+'&long='+longitude+'&cit='+city;
				 execurl(url2, "GET","false");
				 
                
            } else {
                navigator.geolocation.getCurrentPosition(
                                    success_handler, 
                                    error_handler, 
                                    {timeout:10000});				
									
            }
        }
    }



function getshowcookiegeo() {
		
                latitude = $.cookie("posLat");
                longitude = $.cookie("posLon");
                accuracy = $.cookie("posAccuracy");
				
				neightb = $.cookie("posNeightb");
				city = $.cookie("posCity");
				country = $.cookie("posCountry");
                //state = $.cookie("posState");
                //code = $.cookie("posCode");
				
                document.getElementById("status").innerHTML = "<a id=\"clear_cookies\" href=\" javascript:clear_cookies();\" style=\"cursor:pointer; margin-left: 15px;\">"+neightb + " ("+ city+")</a>";
				
		}






    function success_handler(position) {
        latitude = position.coords.latitude;
        longitude = position.coords.longitude;
        accuracy = position.coords.accuracy;
       // var url2 = '2service/geo.php?lat='+latitude+'&long='+longitude+'&cit='+city;
		var url2 = '2service/geo.php?lat='+latitude+'&long='+longitude;
		execurl(url2, "GET","false");
				 
       getlatlengeonames(latitude,longitude);
    }
    
	
	
	
	
function getlatlengeonames(latitude,longitude) {
	
	 if (!latitude || !longitude) {
           // document.getElementById("status").innerHTML = "HTML5 Geolocation supported, but location data is currently unavailable.";
			 document.getElementById("status").innerHTML = "Location currently unavailable.";
            return;
        }
	
	
	 if (!window.count) window.count = 0;
            var urlJSON ='';
            
            count ++;
            // var urlJSON = 'http://ws.geonames.org/findNearbyPlaceNameJSON?lat=-36.9104718&lng=174.9133483';
            var urlJSON = 'geonames.php?type=JSON&lat='+latitude+'&lon='+longitude;
            var urlXML  = 'geonames.php?type=XML&lat=' +latitude+'&lon='+longitude;
            

            // now get the XML reverse geo data
            $.getJSON(urlJSON, function(json) {

                /* Parse JSON objects */
                $.each(json.geonames,function(i,item) {
					
					
                  
					  
					neightb = item.name;
					city = item.adminName1;
					country = item.countryName;
					//alert (city);
					//$('#jsonResults').html('<p>You live in: ' + item.name + '</p>');
					 //document.getElementById("status").innerHTML = neightb +" ("+ city + ")";
					 document.getElementById("status").innerHTML = "<a id=\"clear_cookies\" href=\" javascript:clear_cookies();\" style=\"cursor:pointer; margin-left: 15px;\">"+neightb + " ("+ city+")</a>";
					  $.cookie("posNeightb", neightb , { expires: 111});
					 $.cookie("posCity", city , { expires: 111});
					  $.cookie("posCountry", country , { expires: 111});
	
					  
                });

            });
	
  
	
        $.cookie("posLat", latitude , { expires: 111});
        $.cookie("posLon", longitude , { expires: 111});
		$.cookie("posAccuracy", accuracy,  { expires: 111});
		//$.cookie("posCity", city , { expires: 111});
		$.cookie("posState", state , { expires: 111});
		$.cookie("posCode", code , { expires: 111});
		
  
  

		var url2 = '2service/geo.php?lat='+latitude+'&long='+longitude+'&cit='+city;
		execurl(url2, "GET","false");

		
		
      
	}



	
	
    function error_handler(error) {
		getgeoip();
		document.getElementById("status").innerHTML = "IP Location mode";
		//setTimeout(alert($.cookie("posLat")),9000); //si no, no daba tiempo a fijar la cookie y pasaba al else!
 		 
		if($.cookie("posLat")) //no la detecta a pesar de que la ha fijado en getgeoip
		{	
		
		latitude = $.cookie("posLat");
        longitude = $.cookie("posLon");
		  getlatlengeonames(latitude, longitude);
		    //alert (latitude); 
				var url2 = '2service/geo.php?lat='+latitude+'&long='+longitude+'&cit='+city+'&stat='+state+'&cod='+code;
		execurl(url2, "GET","false");
		
			 document.getElementById("status").innerHTML = "GeoIP";
			// document.getElementById("status").innerHTML = "<a id=\"clear_cookies\" href=\" javascript:clear_cookies();\" style=\"cursor:pointer; margin-left: 15px;\">"+neightb + " ("+ city+")</a>";

		
		} else {
		
		
        var locationError = '';
        switch(error.code){
			
			
			
			
        case 0:
            locationError = "Error retrieving location: " + error.message;
            break;
        case 1:
            locationError = "IP Location mode";
            break;
        case 2:
            locationError = "Browser unable to get location: " + error.message;
            break;
        case 3:
            locationError = "Browser timed out retrieving location.";
            break;
        }

        document.getElementById("status").innerHTML = locationError;
        document.getElementById("status").style.color = "#D03C02";
	
	 }
    }
	
	
	
	
	
	
	
	
    
    function clear_cookies() {
        $.cookie('posLat', null); 
		$.cookie('posLon', null);
		$.cookie('geolocation', null);
        //document.getElementById("status").innerHTML = "Cookies cleared.";
		loadLocation();
		latitude=0;
		longitude=0;
    }
	
	
	
   
   
    function updateDisplay() {
        //var gmapdata = '<iframe width="425" height="350" frameborder="0" scrolling="no" marginheight="0" marginwidth="0" src="http://maps.google.com/maps?f=q&amp;source=s_q&amp;hl=en&amp;geocode=&amp;ie=UTF8&amp;hq=&amp;ll=' + latitude + ',' + longitude + '&amp;output=embed"></iframe>';
        var gmapdata = '<img src="http://maps.google.com/maps/api/staticmap?center=' + latitude + ',' + longitude + '&zoom=16&size=425x350&sensor=false" />';
                
        document.getElementById("placeholder").innerHTML = gmapdata;
        document.getElementById("latitude").innerHTML = latitude;
        document.getElementById("longitude").innerHTML = longitude;
        document.getElementById("accuracy").innerHTML = accuracy;
    }
    
    
	/*
	
	function renderError() {
            $('#georesults').html('<p>The page could not get your location.</p>');
        }
		*/
		
	
