var m_fnIE6CenterMsgBox_szId;
var g_IsSaved = false;

function WindowOpen(szURL,szTarget,szOptions)
{
   var wnd;

   if ( szOptions == undefined )
   {
      szOptions = "";
   }

   if ( szOptions.indexOf("resizable") == -1)
   {
      szOptions += ",resizable=1";
   }
   
   try
   {
       /* Se abre la ventana */
       szOptions="";
       wnd = window.open(szURL,szTarget,szOptions);
   }
   catch(e){}

   /* Se pasa el foco */
   try
   {
      wnd.focus();
      //wnd.location.reload();
   }

   /* Si falla, se cierra, se vuelve a abrir y se le pasa el foco */
   catch(e)
   {
      wnd.close();
      wnd = window.open(szURL,szTarget,szOptions);
      wnd.focus();

   }

   return false;
}

function setCookie (doc,name, value, days)
{ 
   var expdate = new Date(); 

   if ( !days )
   {
      days = 1;
   }

   expdate.setTime(expdate.getTime() + days*24*60*60*1000); 

   doc.cookie = name + "=" + escape(value) + "; expires=" + expdate.toGMTString(); 

} 

function setFocusControl(szControlName)
{
   try
   {
      document.getElementById(szControlName).focus();
   }
   catch(e){}
}

function getCookie (doc,name)
{
   var dc = doc.cookie;
   var cname = name + "=";
   var clen = dc.length;
   var cbegin = 0;

   while (cbegin < clen)
   { 
      var vbegin = cbegin + cname.length;

      if (dc.substring(cbegin, vbegin) == cname)
      { 
         var vend = dc.indexOf (";", vbegin);
         if (vend == -1) vend = clen;
         return unescape(dc.substring(vbegin, vend));
      }

      cbegin = dc.indexOf(" ", cbegin) + 1;

      if (cbegin== 0)
      {
         break;
      }
   }
   return null;
}

function Reposition(
szTable,
szCellContents,
nExtraWidth,
nExtraHeight) 
{
   var MSEX = document.all;

   if ( MSEX )
   {
      return;
   }

   if ( nExtraWidth == undefined )
   {
      nExtraWidth = 0;
   }

   if ( nExtraHeight == undefined )
   {
      nExtraHeight = 0;
   }

   nWidthWindow = (MSEX)?document.body.clientWidth:window.innerWidth;
   nHeightWindow = (MSEX)?document.body.clientHeight:window.innerHeight;

   try
   {
      document.getElementById(szTable).width = nWidthWindow - nExtraWidth;
   }
   catch(e){}

   try
   {
      document.getElementById(szCellContents).height = nHeightWindow - nExtraHeight;
   }
   catch(e){}
}

function ChangeView (
szControlName,
fDisplay)
{

   var ctl = document.getElementById(szControlName);
   
   /* Si no se indico visibilidad, se toma la opuesta */
   if (fDisplay == null)
   {
       if ( ctl.style.display == "none" )
       {
          ctl.style.display = "block";
       }
       else
       {
          ctl.style.display = "none";
       }
  }  
  /* Si SI se indico visibilidad, se toma la indicada */
  else
  {
      if ( fDisplay == true )
      {
          ctl.style.display = "block";
      }
      else
      {
          ctl.style.display = "none";
      }
  }  	
   return false;
}

function SubmitEnter(oEvento, oFormulario)
{
   var iAscii; 

   if (oEvento.keyCode) 
   {
      iAscii = oEvento.keyCode; 
   }
   else if (oEvento.which) 
   {
      iAscii = oEvento.which; 
   }
   else 
   {
      return false;
   }

   if (iAscii == 13) 
   {
      oFormulario.submit();
   }

   return true;
}

function ResizeBody(szSize)
{
   try
   {
      document.getElementsByTagName('body')[0].style.fontSize = szSize;
   }
   catch(e){}
}

function GetWindowSize()
{
	var widthViewport;
	var heightViewport;

	var xScroll;
	var yScroll;

	var widthTotal;
	var heightTotal;

	try
	{
		/* Si no esta dentro de una ventana, se toman las dimensiones del area cliente del Navegador */
		if (typeof window.innerWidth != 'undefined')
		{
			widthViewport = window.innerWidth;
			heightViewport = window.innerHeight;
		}
		/* Si esta dentro de una ventana, se toman las dimensiones del area de la misma */
		else if(typeof document.documentElement != 'undefined' && typeof document.documentElement.clientWidth != 'undefined' && document.documentElement.clientWidth != 0)
		{
			widthViewport  = document.documentElement.clientWidth;
			heightViewport = document.documentElement.clientHeight;
		}
		/* En cualquier otro caso, se toman las dimensiones del "body" */
		else
		{
			widthViewport  = document.getElementsByTagName('body')[0].clientWidth;
			heightViewport = document.getElementsByTagName('body')[0].clientHeight;
		}
	
		xScroll = self.pageXOffset || (document.documentElement.scrollLeft + document.body.scrollLeft);
		yScroll = self.pageYOffset || (document.documentElement.scrollTop  + document.body.scrollTop);
	
		
		widthTotal =  Math.max(document.documentElement.scrollWidth,  document.body.scrollWidth,  widthViewport);
		heightTotal = Math.max(document.documentElement.scrollHeight, document.body.scrollHeight, heightViewport);
	
		/* Se retorna */
		return [widthViewport, heightViewport, xScroll, yScroll, widthTotal, heightTotal];
	}
	catch(e)
	{
		return [0, 0, 0, 0, 0, 0];
	}
}
	
function CenterObject(
szId)
{

    var pnlParent           = document.getElementById("pnlLayout");
	var anData		        = GetWindowSize();
	var objContainer	    = document.getElementById(szId);
	var nMsgBoxWidth	    = parseInt(objContainer.offsetWidth);
	var nMsgBoxHeight	    = parseInt(objContainer.offsetHeight);
	var nVertScrollBarWidth = 26;
	var nHortScrollBarHeight = 32;
    
    /* Se resetean los margenes */
    objContainer.style.marginLeft = 0;
    objContainer.style.marginTop = 0;

    /* Se corrige el padre */
    pnlParent.appendChild(objContainer);

	/************/
	/* Vertical */
	/************/
	try
	{
		/* Si el Scroll vertical se paso de la altura maxima y no hay alto suficiente */
		if( (anData[3] + nMsgBoxHeight ) > anData[1] && 
		     (nMsgBoxHeight -1 -1) > anData[1])
		{
			objContainer.style.top  = (anData[3] + anData[1] - nMsgBoxHeight - 1 -1)  - nHortScrollBarHeight + 'px';
		}
		else
		{
			objContainer.style.top  = (anData[1] / 2 + anData[3] - nMsgBoxHeight / 2) - nHortScrollBarHeight + 'px';
		}
	}
	catch(e){}

	/**************/
	/* Horizontal */	
	/**************/
	/* Si el Scroll horizontal se paso de la ancho maximo y no hay ancho suficiente */
	try
	{
		if ( (anData[2] + nMsgBoxWidth + nVertScrollBarWidth) > anData[0] && 
		     (( nMsgBoxWidth + nVertScrollBarWidth) > anData[0]) )
		{
			objContainer.style.left  = (anData[2] + anData[0] - nMsgBoxWidth ) - nVertScrollBarWidth + 'px';
	
		}
		else
		{
			objContainer.style.left  = ( (anData[0] - nVertScrollBarWidth) / 2 + anData[2] - nMsgBoxWidth  / 2) + nVertScrollBarWidth + 'px';
		}
    }
	catch(e){}
}

function GetInnerWidthFromObject(
objObject)
{
   if ( objObject.clientWidth == undefined )
   {
      return objObject.innerWidth;
   }
   else
   {
      return objObject.clientWidth;
   }
}

function GetInnerHeightFromObject(
objObject)
{
   if ( objObject.clientWidth == undefined )
   {
      return objObject.innerHeight;
   }
   else
   {
      return objObject.clientHeight;
   }
}

function SetColorFromCboToTxt(
cboCombo,
txtBox)
{
    var szBuffer;

    szBuffer = "" + cboCombo.id;

    if (szBuffer.length > 3 )
    {
        if (szBuffer.toLowerCase().substring(0,3) == "cbc" )
        {
            txtBox.style.backgroundColor = txtBox.value;
            cboCombo.style.backgroundColor = txtBox.value;
        }
    }
}

function ComboMakeEditable(
szCombo,
szTextBox)
{
	var cboCombo;
	var txtBox;
	var aszData;
	var szArrayName;

	/* Se toman los objetos */
	cboCombo = document.getElementById(szCombo);
	txtBox = document.getElementById(szTextBox);
	txtBox.style.position = "absolute";
	txtBox.style.borderWidth = "0";

    SetColorFromCboToTxt(cboCombo, txtBox);

	/* Se inicializa sin Item seleccionado */
	//cboCombo.selectedIndex = -1;

	/* Se almacenan en un Buffer */
	//szArrayName = "a" + szCombo;
	//aszData = new Array();

	/* Se buscan los duplicados */
	//for(var nOption = 0; nOption < cboCombo.options.length ; nOption++)
	//{
	//	aszData[0, nOption] = cboCombo.options[nOption].value;
	//	aszData[1, nOption] = cboCombo.options[nOption].text;
	//}

	/* Se almacena el array en la pagina */
	//window[szArrayName] = aszData;

//???cboCombo.style.width = "300px";
//window[szArrayName][0,0];

	/* Sincronizacion de ComboBox -> TextBox */
	RegisterEvent(cboCombo, "change", function () {
txtBox.value = cboCombo.options[cboCombo.selectedIndex].text;
txtBox.focus();

SetColorFromCboToTxt(cboCombo, txtBox);
return;
						/* Se eliminan todos los valores */
						cboCombo.options.length = 0;

						/* Se cargan todos */
						for(var nOption = 0; nOption < aszData.length ; nOption++)
						{
							cboCombo.options[cboCombo.options.length] = new Option (aszData[0, nOption], aszData[1, nOption]);
						}

} );


	/* Sincronizacion de TextBox -> ComboBox */
	RegisterEvent(txtBox, "changeX", function ()
					{
						/* Se eliminan todos los valores */
						//cboCombo.options.length = 0;

/* Si no hay item seleccionado, se filtra */
if ( cboCombo.selectedIndex == -1 )
{

						/* Si no esta duplicado, se aņade a la lista */
						for(var nOption = 0; nOption < aszData.length ; nOption++)
						{
							if ( FindCharInString(txtBox.value, aszData[0, nOption] ) )
							{
								cboCombo.options[cboCombo.options.length] = new Option (aszData[0, nOption], aszData[1, nOption]);
							}
						}
						cboCombo.selectedIndex = -1;
}

					}
				);

	/* Sincronizacion de TextBox -> ComboBox */
	RegisterEvent(txtBox, "change", function ()
					{
                        var nOption = 0;
                        
						/* Si tiene valor */
						if ( txtBox.value != "" )
						{
							/* Se buscan los duplicados */
							for(nOption = 0; nOption < cboCombo.options.length ; nOption++)
							{
								if ( txtBox.value == cboCombo.options[nOption].text )
								{
								    cboCombo.selectedIndex = nOption;
									return;
								}
							}
						}
						
					return;
					
						/* Si tiene valor */
						if ( txtBox.value != "" )
						{
							/* Se buscan los duplicados 
							for(var nOption = 0; nOption < cboCombo.options.length ; nOption++)
							{
								if(cboCombo.options[nOption].text == txtBox.value)
								{
									return;
								}
							}
						}

						/* Aņade la opcion y se selecciona */
						cboCombo.options[cboCombo.options.length] = new Option (txtBox.value, txtBox.value);
						cboCombo.selectedIndex = cboCombo.options.length -1;
					}
				});

	var nPaddingLeft = 3;
	var nPaddingTop = 2;

	/* Dimensiones */
	try
	{
	   txtBox.style.left = cboCombo.offsetLeft + 1 + "px";
    }
    catch(e){}
	try
	{
	   txtBox.style.top = cboCombo.offsetTop + 1 + "px";
    }
    catch(e){}
	try
	{
	   txtBox.style.width = (cboCombo.offsetWidth - GetScrollWidth() - nPaddingLeft - 2 -2 -1-1) + "px";
    }
    catch(e){}
	try
	{
	   txtBox.style.height = (cboCombo.offsetHeight  - nPaddingTop - 2-1) + "px";
    }
    catch(e){}
    
	/* Padding */
	txtBox.style.paddingLeft = nPaddingLeft + "px";
	txtBox.style.paddingTop = nPaddingTop + "px";
}

function ComboBoxClearItems(
szId)
{
	var cboToClear;
	var objParent;
	var cboCloned;

	/* Se busca el combo */
	cboToClear = document.getElementById(szId);

	/* Se toma el padre */
	objParent = cboToClear.parentNode;

	/* Se hace una copia del combo */
	cboCloned = cboToClear.cloneNode(false);

	/* Se sustituye el combo original por el nuevo */
	objParent.replaceChild(cboCloned, cboToClear);

	/* Se retorna el Combo clonado */
	return cboCloned;
}

function FindCharInString(
szChars,
szString)
{
	var nPosChar;
	var nPosString = 0;
	var fFound = true;	

	/* Se normalizan los textos */
	szChars = szChars.toLowerCase();
	szString = szString.toLowerCase();

	/* Se recorren los caracteres de busqueda */
	for(nPosChar = 0; nPosChar < szChars.length ; nPosChar++)
	{
		/* Se busca en la cadena */
		nPosString = szString.indexOf( szChars.substr(nPosChar, 1), nPosString );

		/* Si no la encuentra, se sale */
		if ( nPosString == -1 )
		{
			fFound = false;
			break;
		}
		nPosString += 1;
	}

	/* Se retorna */
	return fFound;
}

function Ajax_SubmitFormBefore(
szPage,
szFormId)
{
    g_IsSaved = true;
    Ajax_SubmitFormEx(szPage, szFormId);
}

function Ajax_SubmitForm(
szPage,
szFormId)
{
    if ( !g_IsSaved )
    {
        Ajax_SubmitFormEx(szPage, szFormId);
    }
    else
    {
        g_IsSaved = false;
    }
}

function Ajax_SubmitFormEx(
szPage,
szFormId)
{

    var xhrRequest;
    var szData;
    
    /* Se toma la informacion a enviar */
    szData = "?" + GetSubmitFormData(szFormId) + "&AjaxSubmit=1&" + Math.random();
    xhrRequest = GetXmlRequest();

    /* Se prepara el envio */
    xhrRequest.open("GET", szPage + szData, false);
   
    /* Se envia la informacion */
    xhrRequest.send(szData);
}

function GetSubmitFormData(
szFormId)
{
    var frmForm;
    var aData;
    var szData;

    /* Se prepara */
    aData = new Array();  
    
    /* Se toma el formulario */
    frmForm = document.getElementById(szFormId);

    /* Se procesa */
    for(var nItem = 0; nItem < frmForm.length ; nItem++)
    {
        /* Se valida */
        switch( frmForm[nItem].type.toLowerCase() )
        {
            case "text":
            case "textarea":
            case "select-one":
            {
                aData.push(frmForm[nItem].name + '=' + encodeURIComponent(frmForm[nItem].value) );
                break;
            }
            case "checkbox":
            {   
                aData.push(frmForm[nItem].name + '=' + encodeURIComponent((frmForm[nItem].checked) ? '1' : '0') );
                break;
            }
            
            case "radio":
            {
                /* Si esta marcado */            
                if ( frmForm[nItem].checked )
                {
                    aData.push(frmForm[nItem].name + '=' + encodeURIComponent(frmForm[nItem].value) );
                }
                break;
            }
        }
    }
    
    /* Se compone la informacion */
    szData = aData.join('&');

    /* Se retorna */
    return szData;
}

function Find(
aszArray,
szIdToFind)
{
    /* Se realiza la busqueda */
    for(var nItem = 0; nItem < aszArray.length ; nItem++)
    {
        if ( aszArray[nItem] == szIdToFind )
        {
            return nItem;
        }
    }
    
    /* Llegado aqui, no se encontro */
    return -1;
};

function FindIdFromArray(
aszArray,
szIdToFind)
{
    /* Se realiza la busqueda */
    for(var nItem = 0; nItem < aszArray.length ; nItem++)
    {
        if ( aszArray[nItem] == szIdToFind )
        {
            return nItem;
        }
    }
    
    /* Llegado aqui, no se encontro */
    return -1;
}

function Trim(
szString)
{
    return szString.replace(/^\s+/g,'').replace(/\s+$/g,'');
}

function ReplaceAll(
szString,
szStringToFind,
szNewString)
{
    var szBuffer = szString;
    var nPos;

    for(;;)
    {
        /* Se busca, si no lo encuentra, se sale */
        nPos = szBuffer.indexOf(szStringToFind, nPos);
        if ( nPos == -1 )
        {
            break;
        }
        
        /* Se reemplaza */
        szBuffer = szBuffer.substring(0, nPos) + szNewString + szBuffer.substring(nPos + szStringToFind.length);

        /* Se desplaza, para no repetir busquedas */
        nPos = nPos + szNewString.length;
    }
    return szBuffer;
}

function Split(
szString,
szSplitter)
{
    var szBuffer = szString;
    var aszBuffer;
    var nIndex = -1;
    var nPos;

    /* Se prepara el Arrar */
    aszBuffer = new Array;

    for(;;)
    {
        /* Se busca, si no lo encuentra, se sale */
        nPos = szBuffer.indexOf(szSplitter);
        if ( nPos == -1 )
        {
            /* Se almacena */
            nIndex++;
            aszBuffer[nIndex] = szBuffer;
            break;
        }
        
        /* Se almacena */
        nIndex++;
        aszBuffer[nIndex] = szBuffer.substring(0, nPos);

        /* Se quita el texto analizado */
        
        /* Se reemplaza */
        szBuffer = szBuffer.substring(nPos + szSplitter.length);
    }
 
    /* Se retorna */
    return aszBuffer;
}

function SetHeights()
{
	var aChildren = SetHeights.arguments;
	var nItem;
	var tdParent;
	var pnlChild;

	/* Se recorren los hijos */
	for (nItem = 0; nItem < aChildren.length; nItem++)
	{
	    try
	    {
		    pnlChild = document.getElementById(aChildren[nItem]);
		    pnlChild.style.height = pnlChild.parentNode.offsetHeight + "px";
        }
	    catch(e){}
	}
}

function Ajax_ClientKeepAlive(
szPageDummy,
nInterval)
{
    var xhrRequest;
    var szData;
    
    /* Se toma la informacion a enviar */
    szData = "?Dummy=" + Math.random();
    xhrRequest = GetXmlRequest();

    /* Se prepara el envio */
    xhrRequest.open("GET", szPageDummy + szData, false);
   
    /* Se envia la informacion */
    xhrRequest.send(szData);
    
    /* Se repite */
    setTimeout ( "Ajax_ClientKeepAlive('" + szPageDummy + "'," + nInterval + ")", nInterval);
    
}

function CreateHidden(
szFormId,
szNameId)
{
    var frmForm = document.forms[szFormId.toLowerCase()];
    var hdnInput = document.createElement("input");
    
    /* Se crea el elemento */
    hdnInput.setAttribute("type", "hidden");
    hdnInput.setAttribute("name", szNameId);
    hdnInput.setAttribute("id", szNameId);
    frmForm.appendChild(hdnInput);
    
    /* Se retorna */
    return hdnInput;
}
