/*
  YQL Geo library by Christian Heilmann
  Homepage: http://isithackday.com/geo/yql-geo-library
  Copyright (c)2010 Christian Heilmann
  Code licensed under the BSD License:
  http://wait-till-i.com/license.txt
*/
var yqlgeo = function(){
  var callback;
  function get(){
    var args = arguments;
    for(var i=0;i<args.length;i++){
      if(typeof args[i] === 'function'){
        callback = args[i];
      }
    }
    if(args[0] === 'visitor'){getVisitor();}
    if(typeof args[0] === 'string' && args[0] != 'visitor'){
      if(args[0]){
        if(/^http:\/\/.*/.test(args[0])){
          getFromURL(args[0]);
        } else if(/^[\d+\.?]+$/.test(args[0])){
          getFromIP(args[0]);
        } else {
          getFromText(args[0]);
        }
      } 
    }
    var lat = args[0];
    var lon = args[1];
    if(typeof lat.join !== undefined && args[0][1]){
      lat = args[0][0];
      lon = args[0][1];
    };    
    if(isFinite(lat) && isFinite(lon)){
      if(lat > -90 && lat < 90 &&
         lon > -180 && lon < 180){
        getFromLatLon(lat,lon);
      }
    }
  }
  function getVisitor(){
    retrieveip();
  };

  function getFromIP(ip){
    var yql = 'select * from geo.places where woeid in ('+
              'select place.woeid from flickr.places where api_key="29e74c681d23f4e0e11d4bee82f7bbec" and (lat,lon) in('+
              'select latitude,longitude from pidgets.geoip'+
              ' where ip="'+ip+'"))';
    load(yql,'yqlgeo.retrieved');
  };

	function wipmania(data) {
    var lat = data.latitude;
    var lon = data.longitude;
    //alert(lat+', '+lon);
    if(isFinite(lat) && isFinite(lon)){
      if(lat > -90 && lat < 90 &&
         lon > -180 && lon < 180){
        getFromLatLon(lat,lon);
      }
    }
	}
	
  function retrieveip(){
  	// This: http://jsonip.appspot.com/?callback=yqlgeo.ipin doesn't always work
    jsonp('http://api.wipmania.com/jsonp?callback=yqlgeo.ipin');
  };

  function ipin(o){
  	// if coordinates retrieved from wipmania
  	if (o.latitude) {
  		wipmania(o);
  	} else {
  	// revert to pidgets.geoip database to get the location based on IP
			IPAddress = getMetaContent("ipaddress");
    	getFromIP(IPAddress);
    }
  };

  function getFromLatLon(lat,lon){
    var yql = 'select * from geo.places where woeid in ('+
              'select place.woeid from flickr.places where api_key="29e74c681d23f4e0e11d4bee82f7bbec" and lat='+
              lat + ' and  lon=' + lon + ')';
    load(yql,'yqlgeo.retrieved');
  };

  function getFromURL(url){
    var yql = 'select * from geo.places where woeid in ('+
              'select match.place.woeId from geo.placemaker where '+
              'documentURL="' + url + '" and '+
              'documentType="text/html" and appid="")';
    load(yql,'yqlgeo.retrieved');
  }

  function getFromText(text){
    var yql = 'select * from geo.places where woeid in ('+
              'select match.place.woeId from geo.placemaker where'+
              ' documentContent = "' + text + '" and '+
              'documentType="text/plain" and appid = "")';
    load(yql,'yqlgeo.retrieved');
  };

  function jsonp(src){
    if(document.getElementById('yqlgeodata')){
      var old = document.getElementById('yqlgeodata');
      old.parentNode.removeChild(old);
    }
    var head = document.getElementsByTagName('head')[0];
    var s = document.createElement('script');
    s.setAttribute('id','yqlgeodata');
    s.setAttribute('src',src);
    head.appendChild(s);
  };

  function load(yql,cb){
    if(document.getElementById('yqlgeodata')){
      var old = document.getElementById('yqlgeodata');
      old.parentNode.removeChild(old);
    }
    var src = 'http://query.yahooapis.com/v1/public/yql?q='+
              encodeURIComponent(yql) + '&format=json&callback=' + cb + '&'+
              'env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys';
              //alert(src);
    var head = document.getElementsByTagName('head')[0];
    var s = document.createElement('script');
    s.setAttribute('id','yqlgeodata');
    s.setAttribute('src',src);
    head.appendChild(s);
  };

  function retrieved(o){
    if(o.query.results !== null){
      callback(o.query.results);
    } else {
      callback({error:o.query});
    }
  };
  return {
    get:get,
    retrieved:retrieved,
    ipin:ipin
  };
}();

/* 
  Geo-Location by Chris Michaelides
  Homepage: http://www.axxis.gr
  Copyright (c)2011-2012 Chris Michaelides - AXXIS Internet Solutions
  Code licensed under the BSD License:
  http://wait-till-i.com/license.txt
*/
var xmlhttp;
if (!xmlhttp) {
  try {
    xmlhttp = new XMLHttpRequest();
  }
  catch (e) {
    if (window.XMLHttpRequest)
      {// code for IE7, Firefox, Opera, etc.
      xmlhttp=new XMLHttpRequest();
      }
    else if (window.ActiveXObject)
      {// code for IE6, IE5
      xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
      }
  }
}

function setCookie(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 getCookie(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 deleteCookie(name) {
	setCookie(name,"",-1);
}

function getMetaContent(metatitle) {
  var meta = document.getElementsByTagName("meta");
  for (var i = 0; i < meta.length; ++i) {
    //alert(metatitle+' => '+meta[i].getAttribute("name")+': '+meta[i].getAttribute("content"));     
    if (meta[i].getAttribute("name")==metatitle) {
      return meta[i].getAttribute("content");
    }
  }
  return true;
}

	var visitorError = false;
	var gotIP = false;
  // First set current position according to IP, just to be sure.
	yqlgeo.get("visitor", normalize_yql_response);
	// Now check to see if this browser supports geolocation.
	allow_geolocation = getMetaContent('allow_geolocation');
	if (allow_geolocation=='allow') {
		if (navigator['geolocation']) {
				navigator['geolocation']['getCurrentPosition'](
	        function (position) {
	          //alert('in position!');
	          handle_geolocation_query(position);
	        }, 
	        function (error) {
						yqlgeo.get("visitor", normalize_yql_response);
	        }, 
	        {
				   timeout: (5 * 1000),
				   maximumAge: (1000 * 60 * 15),
				   enableHighAccuracy: true
			    }
      	);
    }
  }

    function handle_errors(error)
    {
      //alert('in handling errors!');
        switch(error.code)
        {
            case error.PERMISSION_DENIED: setCookie('se_user_latitude', "You did not share geolocation data! Please try again...");
            break;

            case error.POSITION_UNAVAILABLE: setCookie('se_user_latitude', "Could not detect your current position!");
            break;

            case error.TIMEOUT: setCookie('se_user_latitude', "Retrieving your position has timed out! Please try clearing your cache and restarting your browser...");
            break;

            default: setCookie('se_user_latitude', "Your device was denied permission to geolocation!");
            break;
        }
    }

    function normalize_yql_response(response)
    {
      if (!gotIP) {
        if (response.error)
        {
						var error = { code : 0 };
            handle_errors(error);
            visitorError = true;
            return;
        }

        var position = {
            coords :
            {
                latitude: response.place.centroid.latitude,
                longitude: response.place.centroid.longitude
            }/*,
            address :
            {
                city: response.place.locality2.content,
                region: response.place.admin1.content,
                country: response.place.country.content
            }*/
        };
				//alert(position['coords']['latitude']+', '+position['coords']['longitude']);
        handle_geolocation_query(position);
      }
      gotIP=true;
    }

    function handle_geolocation_query(position){
      //alert('success on geolocation!');
 			setCookie('se_user_latitude', position['coords']['latitude'], 1);
 			setCookie('se_user_longitude', position['coords']['longitude'], 1);
      try {
        var grsite = document.getElementById('grsite').value;
      } catch(err) {
        var grsite = getMetaContent('grsite');
      }
        url = grsite+'index.php?option=com_superevents&task=store_userposition&tmpl=component';
      if (document.getElementById('grmyid'))
        var myid = document.getElementById('grmyid').value;
      if (document.getElementById('myid'))
        var myid = document.getElementById('myid').value;
      if (!myid) myid = getMetaContent('myid');
      if (myid>0 && xmlhttp.responseText!="store_position=OK") {
        var xmlMessage = 'myid='+myid+'&user_lat='+position['coords']['latitude']+"&user_lon="+position['coords']['longitude'];
        xmlhttp.open("POST", url+'&'+xmlMessage, false);
        // for ie compatibility
        xmlhttp.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
        xmlhttp.send(xmlMessage);
        if (xmlhttp.responseText=="store_position=OK") {
          return true;
        } else {
          return false;
        }
      }
    }

