/**
* utilities.js contains a library of javascript functions for different purposes
* created by Gerardo Grinman
* date 05/11/2008
*/

/**
* findPosX -> Returns the left position of an object
*/
function findPosX(obj)
{
	var curleft = 0;
	if(obj.offsetParent)
	    while(1) 
	    {
	      curleft += obj.offsetLeft;
	      if(!obj.offsetParent)
	        break;
	      obj = obj.offsetParent;
	    }
	else if(obj.x)
	    curleft += obj.x;
	return curleft;
}

/**
* findPosY -> Returns the top position of an object
*/
function findPosY(obj)
{
	var curtop = 0;
	if(obj.offsetParent)
	    while(1)
	    {
	      curtop += obj.offsetTop;
	      if(!obj.offsetParent)
	        break;
	      obj = obj.offsetParent;
	    }
	else if(obj.y)
	    curtop += obj.y;
	return curtop;
}

/**
* Removes an element from another element
* element -> string
* from -> string
*/
function removeSpecificElement(elementToRemove, from) {
	var d = document.getElementById( from );
	d.removeChild( elementToRemove );
}

function removeFromArray(a, keyToRemove)
{
	var auxArr = new Array();
	for (key in a)
	{
		if (key != keyToRemove)
		{
			var item = a[key];
			auxArr[key] = item;
			//alert(key + " " + item['numero']);
		}
	}
	
	a.length = 0;
	
	for (key in auxArr)
	{
		//alert(auxArr[key]['numero']);
		a[key] = new Array();
		a[key] = auxArr[key];
	}
	
}

function detectBrowser()
{
	var browser=navigator.appName;
	var b_version=navigator.appVersion;
	var version=parseFloat(b_version);
	if ((browser=="Netscape"||browser=="Microsoft Internet Explorer") && (version>=4))
	{
		//alert("Your browser is good enough! " + browser);
		if (browser=="Microsoft Internet Explorer")
			return "MSIE";
		else
			return "OTHER";
	}
	else
	{
		alert("Para continuar jugando sin problemas tenes que actualizar tu Explorador!");
	}
}

/**
* Returns the first element of an array
* a -> Array
*/
function getArrayFirstElement(a)
{
	for (var element in a)
    {
    	if (element in Object.prototype) continue;

    	return a[element];
    }	
}

function serialize(v){
if(typeof(v)=='object' && v.constructor==Array){
var i,s='',c=0;
for(i in v){
  ++c;
  s+=serialize(i)+serialize(v[i]);
  }
s="a:"+c+":{"+s+"}";
return s;
}
else if(Number(v)==v){
return 'i:'+v+';';
}
else if(typeof(v)=='string'){
return 's:'+v.length+':"'+v+'";';
}
}

function checkOnlyDecimals(e) {
	var keycode;
	if (window.event) keycode = window.event.keyCode;
	else if (e) keycode = e.which;
	
	if((keycode  == 0) || (keycode  == 8)|| (keycode  == 46))
		return true; 
		
	if ((keycode < 48) || (keycode  > 57))
		return false;
}

function checkOnlyIntegers(e) {
	var keycode;
	if (window.event) keycode = window.event.keyCode;
	else if (e) keycode = e.which;
	
	if((keycode  == 0) || (keycode  == 8))
		return true; 
		
	if ((keycode < 48) || (keycode  > 57))
		return false;
}

function removeFromArray(a, keyToRemove)
{
	var auxArr = new Array();
	for (key in a)
	{
		if (key != keyToRemove)
		{
			var item = a[key];
			auxArr[key] = item;
		}
	}
	
	a.length = 0;
	
	for (key in auxArr)
	{
		a[key] = new Array();
		a[key] = auxArr[key];
	}	
}

//IPInfoDB jQuery JSON query example
//Tested with FF 3.5, Opera 10, Chome 5 and IE 8
//Geolocation data is stored as serialized JSON in a cookie
//Bug reports : http://forum.ipinfodb.com/viewforum.php?f=7
function geolocate(timezone, cityPrecision) {
var key = '825ae586b47d7d988ced2888bbc34a2fd6f861b2f8796673a93ae482ab10c1f6';
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) {
    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 '';
}
}
//END GEOLOCATE
