//
// Wait
//
function Wait(aWaitMillSecs) {
	var date = new Date();
	var curDate = null;
	
	do { curDate = new Date(); } 
	while (curDate-date < aWaitMillSecs);
}  
//
//
//
function SetWaitMessage(aWaitMessage) 
{
	if (document.getElementById('wait_message') != null) {
		document.getElementById('wait_message').innerHTML = '&nbsp;&nbsp;'+aWaitMessage;
	}
}

function toogleOpacity(aElement)
{
  var e = document.getElementById(aElement);
  
  if (e) {
	//e.setAttribute("class", "transparencia");
  }
  
}

//
//
//

function toogleDisplay(aElement)
{
  var e = document.getElementById(aElement);
  

  if (e) {
      if (e.style.display == 'none')
          e.style.display = 'block';
      else
          e.style.display = 'none';
  }
}

//
//
//

function tg(aElement)
{
	toogleDisplay(aElement)
}

//
//
//

function toogleDisplayInLine(aElement)
{
  var e = document.getElementById(aElement);
  

  if (e) {
      if (e.style.display == 'none')
          e.style.display = 'inline';
      else
          e.style.display = 'none';
  }
}

//
//
//

function tgi(aElement)
{
  var e = document.getElementById(aElement);
  
  if (e) {
      if (e.style.display == 'none')
          e.style.display = 'inline';
      else
          e.style.display = 'none';
  }
}

//
//
//

function toogleVisible(aElement)
{
  var e = document.getElementById(aElement);
  

  if (e) {
      if (e.style.visibility == 'hidden')
          e.style.visibility = 'visible';
      else
          e.style.visibility = 'hidden';
  }
}

function HtmlBox(aInnerText)
{
	var html = '';
	
	html = '<div style="display:table;width:100%;height:100%;">';
	html = html + '<div style="display:table-row">';
	html = html + '<div style="display:table-cell;vertical-align:middle;text-align:center;">';
	html = html + aInnerText;
	html = html + '</div>';
	html = html + '</div>';
	html = html + '</div>';	

	return html;
}
//
//  AddQueryItem
//
function AddQueryItem(aQueryString,aQueryItem)
{
	if (aQueryString != '') {
		return aQueryString + '&' + aQueryItem;
	}
	else {
		return aQueryItem;
	}
}


var dtCh= "-";
var minYear=1975;
var maxYear=2100;

function isInteger(s){
	var i;
    for (i = 0; i < s.length; i++){
        // Check that current character is number.
        var c = s.charAt(i);
        if (((c < "0") || (c > "9"))) return false;
    }
    // All characters are numbers.
    return true;
}

function stripCharsInBag(s, bag){
	var i;
    var returnString = "";
    // Search through string's characters one by one.
    // If character is not in bag, append to returnString.
    for (i = 0; i < s.length; i++){
        var c = s.charAt(i);
        if (bag.indexOf(c) == -1) returnString += c;
    }
    return returnString;
}

function daysInFebruary (year){
	// February has 29 days in any year evenly divisible by four,
    // EXCEPT for centurial years which are not also divisible by 400.
    return (((year % 4 == 0) && ( (!(year % 100 == 0)) || (year % 400 == 0))) ? 29 : 28 );
}
function DaysArray(n) {
	for (var i = 1; i <= n; i++) {
		this[i] = 31
		if (i==4 || i==6 || i==9 || i==11) {this[i] = 30}
		if (i==2) {this[i] = 29}
   }
   return this
}

function isDate(dtStr){
	var daysInMonth = DaysArray(12)
	var pos1=dtStr.indexOf(dtCh)
	var pos2=dtStr.indexOf(dtCh,pos1+1)
	var strDay=dtStr.substring(0,pos1)
	var strMonth=dtStr.substring(pos1+1,pos2)
	var strYear=dtStr.substring(pos2+1)

  strYr=strYear
	if (strDay.charAt(0)=="0" && strDay.length>1) strDay=strDay.substring(1)
	if (strMonth.charAt(0)=="0" && strMonth.length>1) strMonth=strMonth.substring(1)
	for (var i = 1; i <= 3; i++) {
		if (strYr.charAt(0)=="0" && strYr.length>1) strYr=strYr.substring(1)
	}
	month=parseInt(strMonth)
	day=parseInt(strDay)
	year=parseInt(strYr)
	if (pos1==-1 || pos2==-1){
		alert("La fecha es incorrecta (El formato de la fecha debe ser : dd/mm/aaaa)")
		return false
	}
	if (strMonth.length<1 || month<1 || month>12){
		alert("La fecha es incorrecta")
		return false
	}
	if (strDay.length<1 || day<1 || day>31 || (month==2 && day>daysInFebruary(year)) || day > daysInMonth[month]){
		alert("La fecha es incorrecta")
		return false
	}
	if (strYear.length != 4 || year==0 || year<minYear || year>maxYear){
		alert("La fecha es incorrecta (El año debe estar comprendido entre "+minYear+" y "+maxYear+")")
		return false
	}
	if (dtStr.indexOf(dtCh,pos2+1)!=-1 || isInteger(stripCharsInBag(dtStr, dtCh))==false){
		alert("La fecha es incorrecta")
		return false
	}
return true
}

//
// URL Tools
//

function URLEncode(aString)
{
	var nocodificar = "0123456789"+"ABCDEFGHIJKLMNOPQRSTUVWXYZ"+"abcdefghijklmnopqrstuvwxyz" +"-_.!~*'()";
	var HEX = "0123456789ABCDEF";
	var textoAcodificar = aString;
	var codificado = "";

	for (var i = 0; i < textoAcodificar.length; i++ ) {
		var ch = textoAcodificar.charAt(i);
	    if (ch == " ") {
		    codificado += "+";
		} else if (nocodificar.indexOf(ch) != -1) {
		    codificado += ch;
		} else {
		    var charCode = ch.charCodeAt(0);
			if (charCode > 255) {
			    alert( "Caracter Unicode '"+ch+"' no puede ser codificado utilizando la codificación URL estandar.\n" +
				          "(sólo soporta caracteres de 8-bit.)\n" +
						  "Será sustituido por un símbolo de suma (+)." );
				codificado += "+";
			} else {
				codificado += "%";
				codificado += HEX.charAt((charCode >> 4) & 0xF);
				codificado += HEX.charAt(charCode & 0xF);
			}
		}
	}
	return codificado;
};

function URLDecode(aString) 
{
   var HEXCHARS = "0123456789ABCDEFabcdef"; 
   var codificado = aString;
   var decodicifado = "";
   var i = 0;
   while (i < codificado.length) {
       var ch = codificado.charAt(i);
	   if (ch == "+") {
	       decodicifado += " ";
		   i++;
	   } else if (ch == "%") {
			if (i < (codificado.length-2) 
					&& HEXCHARS.indexOf(codificado.charAt(i+1)) != -1 
					&& HEXCHARS.indexOf(codificado.charAt(i+2)) != -1 ) {
				decodicifado += unescape( codificado.substr(i,3) );
				i += 3;
			} else {
				alert( 'Bad escape combination near ...' + codificado.substr(i) );
				decodicifado += "%[ERROR]";
				i++;
			}
		} else {
		   decodicifado += ch;
		   i++;
		}
	} 
   return decodicifado;
};

//
// Ajax Tools
//

var xhttp = null; 
var xhttp_busy = false; 
var xtarget = '';

function getXHttp() 
{
	if (!xhttp) {
		// Probamos con IE
		try
		{
			// Funcionará para JavaScript 5.0
			xhttp = new ActiveXObject("Msxml2.XMLHTTP");
		}
		catch(e)
		{
			try
			{
				xhttp = new ActiveXObject("Microsoft.XMLHTTP");
			}
			catch(oc)
			{   
				xhttp = null;
			}
		}
	}
	
	if (!xhttp) {
		// Probamos con el resto
		try {
			xhttp = new XMLHttpRequest();
		}
		catch (e) {
			xhttp = null;
		}
	}
	
	return xhttp;
}

function handleXmlHttpResponse()
{
	if (xhttp.readyState == 4) {
		//document.getElementById(xupdate).innerHTML = 'analyzing response ...';
		if (xhttp.status == 200) {
			document.getElementById(xupdate).innerHTML = 'ok!';
			document.getElementById(xupdate).innerHTML = xhttp.responseText;
		}
		else {
			//document.getElementById(xupdate).innerHTML = 'xmlhttp response status = '+xhttp.status.toString();
		}
		xhttp_busy = false;
		
	}
}

function XHttpGET(url)
{
	if (!xhttp_busy) {
		getXHttp();
		if (xhttp) {
			xhttp.open("GET",url,true);
			xhttp.onreadystatechange = handleXmlHttpResponse;
			//xmlHttp.setRequestHeader('Content-Type', 'application/text');
			//document.getElementById(xupdate).innerHTML = 'waiting ...';
			xhttp_busy = true;
			xhttp.send(null);
		}
		else
			document.getElementById(xupdate).innerHTML = 'XMLHttp not found!';
	}
}

function XHttpUpdate(id,url)
{
	if (!xhttp_busy) {
		xupdate = id;
		document.getElementById(xupdate).innerHTML = '(consultando ...)';
		XHttpGET(url);
	}
}

function XQueryUpdate(id,query)
{
	XHttpUpdate(id,query);
}

//
// Browser Tools
//

var BrowserDetect = {
	init: function () {
		this.browser = this.searchString(this.dataBrowser) || "An unknown browser";
		this.version = this.searchVersion(navigator.userAgent)
			|| this.searchVersion(navigator.appVersion)
			|| "an unknown version";
		this.OS = this.searchString(this.dataOS) || "an unknown OS";
	},
	searchString: function (data) {
		for (var i=0;i<data.length;i++)	{
			var dataString = data[i].string;
			var dataProp = data[i].prop;
			this.versionSearchString = data[i].versionSearch || data[i].identity;
			if (dataString) {
				if (dataString.indexOf(data[i].subString) != -1)
					return data[i].identity;
			}
			else if (dataProp)
				return data[i].identity;
		}
	},
	searchVersion: function (dataString) {
		var index = dataString.indexOf(this.versionSearchString);
		if (index == -1) return;
		return parseFloat(dataString.substring(index+this.versionSearchString.length+1));
	},
	dataBrowser: [
		{
			string: navigator.userAgent,
			subString: "Chrome",
			identity: "Chrome"
		},
		{ 	string: navigator.userAgent,
			subString: "OmniWeb",
			versionSearch: "OmniWeb/",
			identity: "OmniWeb"
		},
		{
			string: navigator.vendor,
			subString: "Apple",
			identity: "Safari",
			versionSearch: "Version"
		},
		{
			prop: window.opera,
			identity: "Opera"
		},
		{
			string: navigator.vendor,
			subString: "iCab",
			identity: "iCab"
		},
		{
			string: navigator.vendor,
			subString: "KDE",
			identity: "Konqueror"
		},
		{
			string: navigator.userAgent,
			subString: "Firefox",
			identity: "Firefox"
		},
		{
			string: navigator.vendor,
			subString: "Camino",
			identity: "Camino"
		},
		{		// for newer Netscapes (6+)
			string: navigator.userAgent,
			subString: "Netscape",
			identity: "Netscape"
		},
		{
			string: navigator.userAgent,
			subString: "MSIE",
			identity: "Explorer",
			versionSearch: "MSIE"
		},
		{
			string: navigator.userAgent,
			subString: "Gecko",
			identity: "Mozilla",
			versionSearch: "rv"
		},
		{ 		// for older Netscapes (4-)
			string: navigator.userAgent,
			subString: "Mozilla",
			identity: "Netscape",
			versionSearch: "Mozilla"
		}
	],
	dataOS : [
		{
			string: navigator.platform,
			subString: "Win",
			identity: "Windows"
		},
		{
			string: navigator.platform,
			subString: "Mac",
			identity: "Mac"
		},
		{
			   string: navigator.userAgent,
			   subString: "iPhone",
			   identity: "iPhone/iPod"
	    },
		{
			string: navigator.platform,
			subString: "Linux",
			identity: "Linux"
		}
	]

};
BrowserDetect.init();

