
function xGetElementById(e)
{
  if(typeof(e)=='string') {
    if(document.getElementById) e=document.getElementById(e);
    else if(document.all) e=document.all[e];
    else e=null;
  }
  return e;
}

//object detection to return the correct object depending upon broswer type. Used by the getAXHA(); function.
function getNewHttpObject() {
    var objType = false;
    try {
        objType = new ActiveXObject('Msxml2.XMLHTTP');
    } catch(e) {
        try {
            objType = new ActiveXObject('Microsoft.XMLHTTP');
        } catch(e) {
            objType = new XMLHttpRequest();
        }
    }
    return objType;
}

//Function used to update page content with new xhtml fragments by using a javascript object, the dom, and http.
function getAXAH(url,elementContainer,postdata, async, mostrarImg){
	if (!async) var async = false;
   async = false;
//	screen.updateInterval=0;
   if (!mostrarImg)
   {
   	document.getElementById(elementContainer).innerHTML = '<table width="90%" height="60" align="center"><tr><td align="center" valign="middle"><img src="images/loading.gif" align="middle" border="0" alt="cargando"></td></tr></table>';
   }
	var theHttpRequest = getNewHttpObject();
	theHttpRequest.onreadystatechange = function() {processAXAH(elementContainer);};
	theHttpRequest.open("POST", url);
	theHttpRequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
   /*if(BrowserDetect.browser == "Firefox")
   {   theHttpRequest.send(postdata);}
   else
   {   theHttpRequest.send(postdata, false);}*/
   theHttpRequest.send(postdata);

		function processAXAH(elementContainer){
		   if (theHttpRequest.readyState == 4) {
			   if (theHttpRequest.status == 200) {
				   respuesta = theHttpRequest.responseText.split("@@@");
				   document.getElementById(elementContainer).innerHTML = respuesta[0];
					if(respuesta.length > 1)
					{
						for (i=1; i<respuesta.length; i++)
						{
                     //alert(respuesta[i]);
							eval(respuesta[i]);
						}
					}
			   } else {
				   document.getElementById(elementContainer).innerHTML="<p><span class='redtxt'>Error!<\/span> HTTP request return the following status message:&nbsp;" + theHttpRequest.statusText +"<\/p>";
			   }
		   }
		}
}

function getAXAH_confirm(url,elementContainer,postdata, async, msg){
   if(confirm(msg)){
	if (!async) var async = false;
//	screen.updateInterval=0;
	document.getElementById(elementContainer).innerHTML = '<table width="90%" height="60" align="center"><tr><td align="center" valign="middle"><img src="images/loading.gif" align="middle" border="0" alt="cargando"></td></tr></table>';
	var theHttpRequest = getNewHttpObject();
	theHttpRequest.onreadystatechange = function() {processAXAH(elementContainer);};
	theHttpRequest.open("POST", url, async);
	theHttpRequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
	theHttpRequest.send(postdata);

		function processAXAH(elementContainer){
		   if (theHttpRequest.readyState == 4) {
			   if (theHttpRequest.status == 200) {
				   respuesta = theHttpRequest.responseText.split("@@@");
				   document.getElementById(elementContainer).innerHTML = respuesta[0];
					if(respuesta.length > 1)
					{
						for (i=1; i<respuesta.length; i++)
						{
							eval(respuesta[i]);
						}
					}
			   } else {
				   document.getElementById(elementContainer).innerHTML="<p><span class='redtxt'>Error!<\/span> HTTP request return the following status message:&nbsp;" + theHttpRequest.statusText +"<\/p>";
			   }
		   }
		}
   }
}

function llamarasincrono_form(url, id_contenedor, formid)
{
	//alert('llamar_form:' + url + ' ' + id_contenedor + ' ' + formid);
   var pagina_requerida = false
   var Formulario = document.getElementById(formid);
   var longitudFormulario = Formulario.elements.length;
   var cadenaFormulario = ""
   var sepCampos
   sepCampos = ""
   for (var i=0; i <= Formulario.elements.length-1;i++) {
      InStr = cadenaFormulario.indexOf(Formulario.elements[i].name)+1;
      if (InStr == 0)
      {
         cadenaFormulario += sepCampos+Formulario.elements[i].name+'='+encodeURI(Formulario.elements[i].value);
         sepCampos="&";
      }
   }
   //alert(cadenaFormulario);
   document.getElementById(id_contenedor).innerHTML = '<table width="90%" height="60" align="center"><tr><td align="center" valign="middle"><img src="images/loading.gif" align="middle" border="0" alt="cargando"></td></tr></table>';
   if (window.XMLHttpRequest) 
   {// Si es Mozilla, Safari etc
      pagina_requerida = new XMLHttpRequest()
   } else if (window.ActiveXObject)
   { // pero si es IE
      try {
         pagina_requerida = new ActiveXObject("Msxml2.XMLHTTP")
      } 
      catch (e){ // en caso que sea una versión antigua
         try{
         pagina_requerida = new ActiveXObject("Microsoft.XMLHTTP")
         }
         catch (e){}
      }
   }
   else
      return false
   

   pagina_requerida.onreadystatechange=function(){ // función de respuesta
      cargarpagina(pagina_requerida, id_contenedor);
   }
   pagina_requerida.open('POST', url, true); // asignamos los métodos open y send
   pagina_requerida.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=ISO-8859-1');
   pagina_requerida.send(cadenaFormulario);
}

function llamarasincrono_confirm(url, id_contenedor, msg)
{
	document.getElementById(id_contenedor).innerHTML = '<table width="90%" height="60" align="center"><tr><td align="center" valign="middle"><img src="images/loading.gif" align="middle" border="0" alt="cargando"></td></tr></table>';
   if(confirm(msg))
   {
   var pagina_requerida = false
   if (window.XMLHttpRequest) 
   {// Si es Mozilla, Safari etc
      pagina_requerida = new XMLHttpRequest()
   } else if (window.ActiveXObject)
   { // pero si es IE
      try {
         pagina_requerida = new ActiveXObject("Msxml2.XMLHTTP")
      } 
      catch (e){ // en caso que sea una versión antigua
         try{
         pagina_requerida = new ActiveXObject("Microsoft.XMLHTTP")
         }
         catch (e){}
      }
   }
   else
      return false
   pagina_requerida.onreadystatechange=function(){ // función de respuesta
      cargarpagina(pagina_requerida, id_contenedor);
   }
   pagina_requerida.open('GET', url, true) // asignamos los métodos open y send
   pagina_requerida.send(null)
   }
   else
      return false;
}
function llamarasincrono(url, id_contenedor)
{
   var pagina_requerida = false
   if (window.XMLHttpRequest) 
   {// Si es Mozilla, Safari etc
      pagina_requerida = new XMLHttpRequest()
   } else if (window.ActiveXObject)
   { // pero si es IE
      try {
         pagina_requerida = new ActiveXObject("Msxml2.XMLHTTP")
      } 
      catch (e){ // en caso que sea una versión antigua
         try{
         pagina_requerida = new ActiveXObject("Microsoft.XMLHTTP")
         }
         catch (e){}
      }
   }
   else
      return false

   document.getElementById(id_contenedor).innerHTML = '<table width="90%" height="60" align="center"><tr><td align="center" valign="middle"><img src="images/loading.gif" align="middle" border="0" alt="cargando"></td></tr></table>';
   pagina_requerida.onreadystatechange=function(){ // función de respuesta
      cargarpagina(pagina_requerida, id_contenedor);
   }
   pagina_requerida.open('GET', url, true); // asignamos los métodos open y send
   pagina_requerida.send(null);
}
// todo es correcto y ha llegado el momento de poner la información requerida
// en su sitio en la pagina xhtml
function cargarpagina(pagina_requerida, id_contenedor)
{
//	alert('cargapag: ' + pagina_requerida + ' ' + id_contenedor);
	if (pagina_requerida.readyState == 4 && (pagina_requerida.status==200 || window.location.href.indexOf("http")==-1))
   {
	  respuesta = pagina_requerida.responseText.split("@@@");  //Codigo para evaluar JS incrustado en los modulos cargados por Axah
      document.getElementById(id_contenedor).innerHTML=respuesta[0];
	  if(respuesta.length > 1)
	  {
		  for (i=1; i<respuesta.length; i++)
		  {
			  eval(respuesta[i]);
		  }
	  }
   }
}


function numbersonly(e)
{
	var unicode=e.charCode? e.charCode : e.keyCodeJ
	if (unicode!=8)
	{ //if the key isn't the backspace key (which we should allow)
		if (unicode<48||unicode>57) //if not a number
		return false; //disable key press 
	}
}

function fieldNumber (e)
{
	var key;
	var keychar;

	key = e.charCode? e.charCode : e.keyCode; 
	keychar = String.fromCharCode(key);

	// control keys
	if ((key==null) || (key==0) || (key==8) || (key==9) || (key==13) || (key==27) )
		return true;

	// numbers
	else if ((("0123456789.").indexOf(keychar) > -1))
		return true;

	/*// decimal point jump
	else if (dec && (keychar == "."))
	{
		myfield.form.elements[dec].focus();
		return false;
	}*/
	else
		return false;
} 

//funcion para verificar los datos digitados en campos de texto
function fieldText (e) 
{ 
	var valorCampo; 
	var valor = true;
	var evento_key = e.charCode? e.charCode : e.keyCode; 
	//alert(evento_key);

	if (evento_key < 40 || evento_key > 90) //( - Z
	{	if (evento_key < 97 || evento_key > 122) //a - z
		{	
			e.keyCode = 0;
			e.charCode = 0;
			valor = false;
		}
	}
	
	if (evento_key > 96 && evento_key < 123 || evento_key == 241)
	{
		e.keyCode = evento_key - 32;
		e.charCode = evento_key - 32;
		valor = true;
	}

	// [enter] [espacio] _ ü é á - Ñ
	if (evento_key == 13 || evento_key == 32 || evento_key == 95 || evento_key == 129 || evento_key == 130 || evento_key == 209 || (evento_key > 159 && evento_key < 166)) 
	{	e.keyCode = evento_key;
		e.charCode = evento_key;
		valor = true;
	}

	return valor; 
} 

//funcion para verificar los datos digitados en campos de texto
function fieldTextEnter(objeto, tamano) 
{ 
	var valorCampo = objeto.value; 
	var valor = true;
	var evento_key = e.charCode? e.charCode : e.keyCode; 

	if (valorCampo.length > tamano)
	{
		objeto.value = valorCampo.substr(0,tamano);
		alert('Ha llegado al límite de caracteres que soporta el Campo!!');			
	}

	if (evento_key < 40 || evento_key > 90) //( - Z
	{	if (evento_key < 97 || evento_key > 122) //a - z
		{	
			e.keyCode = 0;
			e.charCode = 0;
			valor = false;
		}
	}
	
	if (evento_key > 96 && evento_key < 123 || evento_key == 241)
	{
		e.keyCode = evento_key - 32;
		e.charCode = evento_key - 32;
		valor = true;
	}

	// [enter] [espacio] _ ü é á - Ñ
	if (evento_key == 13 || evento_key == 32 || evento_key == 95 || evento_key == 129 || evento_key == 130 || evento_key == 209 || (evento_key > 159 && evento_key < 166)) 
	{	e.keyCode = evento_key;
		e.charCode = evento_key;
		valor = true;
	}

	return valor; 
} 


function redirect_confirm(url, msg)
{
	if(confirm(msg))
	{ 
		window.location.href = url; 
	}
	else
	{
		return false;
	}
}

function redirect_alert(url, msg)
{
	alert(msg); 
	window.location.href = url; 
	return false;
}

function Sumar(val1, val2, val3, total)
{
document.getElementById(total).value = parseFloat(document.getElementById(val1).value) + parseFloat(document.getElementById(val2).value) + parseFloat(document.getElementById(val3).value)
}

function poptastic(url)
{
	newwindow=window.open(url,null,"height=600,width=800,resizable=yes,scrollbars=yes,menubar=yes");
}

function poptastic_confirm(url, msg)
{
	if(confirm(msg))
	{ 
		poptastic(url); 
	}
	return false;
}

function switch_ctrl_disabled(ctrl, val, flag)
{
	if (document.getElementById(ctrl).disabled==true)
	{
		document.getElementById(ctrl).disabled=false;
		document.getElementById(val).value=0;
		document.getElementById(flag).value="";
		//alert("disabled" + control.disabled);
	}
	else
	{
		document.getElementById(ctrl).disabled=true;
		document.getElementById(val).value=1;
		document.getElementById(flag).value=1;
		//alert("enabled" + control.disabled);
	}
	//alert(document.getElementById(val).value);
}

function switch_value(val)
{
	if (document.getElementById(val).value==0)
	{
		document.getElementById(val).value=1;
		//alert("disabled" + control.disabled);
	}
	else
	{
		document.getElementById(val).value=0;
		//alert("enabled" + control.disabled);
	}
	//alert(document.getElementById(val).value);
}

function submit_click(id_Submit)
{
	document.getElementById(id_Submit).click();
	return true;
}

function cambia_color_celda(id_celda, color)
{
   celda = document.getElementById(id_celda);
   celda.style.backgroundColor=color;
}

function cambia_letreros(id_aviso, texto)
{
   document.getElementById(id_aviso).innerHTML = texto;
}

function VerificaCampos(passwordID, passwordConfID, img, flagID)
{
	var valor = true;
   var campo1 = document.getElementById(passwordID);
   var campo2 = document.getElementById(passwordConfID);
   var imagen = document.getElementById(img);
   var flag = document.getElementById(flagID);

   if (campo1.value == campo2.value && campo1.value.length > 5)
   {
      imagen.src = "images/ok.jpg";
      flag.value = "CA";
   }
   else
   {
      imagen.src = "images/bad.jpg";
      flag.value = "";
   }

   return true;
}

function clear_data(control, texto)
{
	var del, len;
	var toClear = document.getElementById(control);
	if (!toClear) alert ("error en:"+control);
	len = toClear.options.length;
	for (del = 0; del < len; del++)
	{
		toClear.options[del] = null;
	}
	toClear.options.length = 0;
	toClear.options[0] = new Option(texto, "0");
}

function populateData(ctr_lv1, ctr_lv2, ctr_lv3, ctr_lv4, level, arrayData, tex_lv2, tex_lv3, tex_lv4) 
{
	//alert(ctr_lv1);
	var i, len, val, del, hijo;
	string = ""; 
	count	= 1;
	var sel1 = document.getElementById(ctr_lv1);
	var sel2 = document.getElementById(ctr_lv2);
	var sel3 = ctr_lv3 ? document.getElementById(ctr_lv3) : null;
	var sel4 = ctr_lv4 ? document.getElementById(ctr_lv4) : null;

	if (level < 4 && sel4)
		clear_data (ctr_lv4, tex_lv4);
	if (level < 3 && sel3)
		clear_data (ctr_lv3, tex_lv3);
	if (level < 2)
		clear_data (ctr_lv2, tex_lv2);

	indez = sel1.selectedIndex;
	value1 = sel1.options[indez].value;
	prt_value = value1;
	//alert(name);

	if (level > 1)
	{
		indez = sel2.selectedIndex;
		value2 = sel2.options[indez].value;
		prt_value = value2;
		if (level > 2)
		{
			indez = sel3.selectedIndex;
			value3 = sel3.options[indez].value;
			prt_value = value3;
			index_value = 3;
			index_optio = 4;
			hijo = sel4;
		}
		else
		{
			index_value = 2;
			index_optio = 3;
			hijo = sel3;
		}
	}
	else
	{
		index_value = 1;
		index_optio = 2;
		hijo = sel2;
	}

	//alert(level+' - '+prt_value+' - '+arrayData[1]);
	for( i = 0; i < arrayData.length; i++ ) 
	{ 
		string = arrayData[i].split( "|" ); 

		if (level > 0)
			valor_if = string[0] == value1 ? true : false;
		if (level > 1)
			valor_if = valor_if && string[1] == value2 ? true : false;
		if (level > 2)
			valor_if = valor_if && string[2] == value3 ? true : false;

		if(valor_if)
		{ 
			//alert(string[0] + string[1] + string[2])
			hijo.options[count++] = new Option(string[index_optio], string[index_value]);
		} 
	} 
} 

function formatCurrency(num) 
{
   num = num.toString().replace(/\$|\,/g,'');
   if(isNaN(num))
      num = "0";
   sign = (num == (num = Math.abs(num)));
   num = Math.floor(num*100+0.50000000001);
   cents = num%100;
   num = Math.floor(num/100).toString();
   if(cents<10)
      cents = "0" + cents;

   for (var i = 0; i < Math.floor((num.length-(1+i))/3); i++)
      num = num.substring(0,num.length-(4*i+3))+','+ num.substring(num.length-(4*i+3));

   return (((sign)?'':'-') + '$' + num + '.' + cents);
}

function actualizaConversor (idSelOrigen, idSelDestino, idCantidad, idResultado)
{
	string = "$"; 
	var Orig = document.getElementById(idSelOrigen);
	var Dest = document.getElementById(idSelDestino);
	var Cant = document.getElementById(idCantidad);
   var Resultado = 0.00;

	indez = Orig.selectedIndex;
	valueOrig = parseFloat(Orig.options[indez].value);

	indez = Dest.selectedIndex;
	valueDest = parseFloat(Dest.options[indez].value);

   valueCant = parseFloat(Cant.value);

   Resultado = parseFloat((valueCant)*(valueOrig/valueDest));

   cadenaResultado = formatCurrency(Resultado);
   //alert(cadenaResultado);

   cambia_letreros (idResultado, cadenaResultado);
   return false;
}

 function getAbsolutePosx(el) {
	var SL = 0, ST = 0;
	var is_div = /^div$/i.test(el.tagName);
	if (is_div && el.scrollLeft)
		SL = el.scrollLeft;
	if (is_div && el.scrollTop)
		ST = el.scrollTop;
	var r = { x: el.offsetLeft - SL, y: el.offsetTop - ST };
	if (el.offsetParent) {
		var tmp = this.getAbsolutePosx(el.offsetParent);
      //alert(r.x + "-" + r.y);
		r.x += tmp.x;
		r.y += tmp.y;
	}
	return r;
}
/*
xtemp = "0px";
ytemp = "0px";
div = 0;
*/
function el_x_del_div(ref1, div1, x1, y1)
{
   punto = getAbsolutePosx(ref1);
   if (punto.x==0 && punto.y==0)
   {
      punto.x = 205;
      punto.y = 207;
   }
   xtemp = punto.x + x1;
   ytemp = punto.y + y1;
   div = div1;
   /*

   t = setTimeout("esperar_el_x_del_div()", 2000);  
}

function esperar_el_x_del_div()
{
   */
   div.style.left = xtemp + "px" ;
   div.style.top = ytemp + "px";
   //alert(x + "-" + y);
   //alert(punto.x + "-" + punto.y);
   //alert(div.style.left + "-" + div.style.top);
}


timerDerstacados = setTimeout("detenerDestacados()   ", 1);

function rotarDestacados()
{
   timerDerstacados = setTimeout("rotarDestacados()   ", 10000);
   rotarDestacadosVenta();
   rotarDestacadosArriendo();
   //alert("rotarDestacados");
}

function detenerDestacados()
{
   clearTimeout(timerDerstacados);
}

function rotarDestacadosVenta()
{
   DestacadoIndexVenta = document.getElementById("index1").value;
   srtMenuGris =  document.getElementById("srtMenuGris1").value;
   //alert('PHPID=ZGVzdGFjYWRvcw==&tipoNegocio=1&index='+DestacadoIndexVenta);
   getAXAH('action.php', 'venta_destacado', 'PHPID=ZGVzdGFjYWRvcw==&tipoNegocio=1&index='+DestacadoIndexVenta+'&srtMenuGris='+srtMenuGris, true);
}

function rotarDestacadosArriendo()
{
   DestacadoIndexArriendo = document.getElementById("index2").value;
   srtMenuGris =  document.getElementById("srtMenuGris2").value;
   //alert('PHPID=ZGVzdGFjYWRvcw==&tipoNegocio=2&index='+DestacadoIndexArriendo);
   getAXAH('action.php', 'arriendo_destacado', 'PHPID=ZGVzdGFjYWRvcw==&tipoNegocio=2&index='+DestacadoIndexArriendo+'&srtMenuGris='+srtMenuGris, true);
}

