﻿//---------------------------------------------------------------
// Rutinas de base SB para Javascript
//---------------------------------------------------------------

//Centra la ventana en la que se esta parado
function centrarEstaVentana()
{
    centrarVentana(window);
}

//Centra la ventana indicada
function centrarVentana(xVentana)
{
    var sPosVtana

    sPosVtana = calcularPosVtanaCentrada(xVentana);
    xVentana.moveTo(sPosVtana[0], sPosVtana[1]);
}

function calcularSizeVentana(xVentana)
{
    var sAncho, sAlto;
    
    if( typeof( xVentana.innerWidth ) == 'number' ) {
        //No IE
        sAncho = xVentana.innerWidth;
        sAlto = xVentana.innerHeight;
    }else if( xVentana.document.documentElement && ( xVentana.document.documentElement.clientWidth || xVentana.document.documentElement.clientHeight ) ) {
        //IE 6+ in 'standards compliant mode'
        sAncho = xVentana.document.documentElement.clientWidth;
        sAlto = xVentana.document.documentElement.clientHeight;
    } else if( xVentana.document.body && ( xVentana.document.body.clientWidth || xVentana.document.body.clientHeight ) ) {
        //IE 4 compatible
        sAncho = xVentana.document.body.clientWidth;
        sAlto = xVentana.document.body.clientHeight;
    }else{
        sAncho = screen.width;
        sAlto = screen.height;
    }
    
    return (new Array(sAncho, sAlto));
}

//calcula el TOP y LEFT de una ventana para q este centrada
function calcularPosVtanaCentrada(xVentana)
{
    var sSize;
    
    sSize = calcularSizeVentana(xVentana)
    
    return calcularPosVtanaCentradaDeSize(sSize[0], sSize[1]);
}

//calcula el TOP y LEFT de una ventana para q este centrada a partir del tamaño
function calcularPosVtanaCentradaDeSize(xWidth, xHeight)
{
    var sTop, sLeft;
    
    //calculo la posicion
    sLeft = (screen.width - xWidth) / 2;
    sTop = (screen.height - xHeight) / 2;
	
	return (new Array(sLeft, sTop));
    
}

function ObtenerObjetoAJAX(){
  var xmlHttp;
  if (window.XMLHttpRequest) { // Mozilla, Safari,...
		xmlHttp = new XMLHttpRequest();
  if (xmlHttp.overrideMimeType) {
		xmlHttp.overrideMimeType('text/xml');
	}
	} else if (window.ActiveXObject) { // IE
		try {
			xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
		} catch (e) {
			try {
				xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
			} catch (e) {}
		}
  }
  return xmlHttp;
}


//Devuelve los primeros "n" caracteres de "str"
function Left(str, n){
	if (n <= 0)
	    return "";
	else if (n > String(str).length)
	    return str;
	else
	    return String(str).substring(0,n);
}
//Devuelve los ultimos "n" caracteres de "str"
function Right(str, n){
    if (n <= 0)
       return "";
    else if (n > String(str).length)
       return str;
    else {
       var iLen = String(str).length;
       return String(str).substring(iLen, iLen - n);
    }
}

function open_window_max( aURL, aWinName )
{
   var wOpen;
   var sOptions;

   sOptions = 'status=yes,menubar=yes,scrollbars=yes,resizable=yes,toolbar=yes';
   sOptions = sOptions + ',width=' + (screen.availWidth - 10).toString();
   sOptions = sOptions + ',height=' + (screen.availHeight - 122).toString();
   sOptions = sOptions + ',screenX=0,screenY=0,left=0,top=0';

   wOpen = window.open( '', aWinName, sOptions );
   wOpen.location = aURL;
   wOpen.focus();
   wOpen.moveTo( 0, 0 );
   wOpen.resizeTo( screen.availWidth, screen.availHeight );
   return wOpen;
}


function setTamanioVentana(xAlto,xAncho){
window.resizeTo(xAlto , xAncho);
}

// Ajusta el tamaño de la ventana para que no sea necesario scrollear
//  LOS NUMEROS SUMADOS A LOS OFFSET SON AJUSTADOS POR APROXIMACION.
function ajustarVentana(){
    if((document.body.offsetWidth + 20) == screen.availWidth){  //Ventana maximizada
        return;
    }

    var sWidth = document.body.offsetWidth + 28;
    var sHeight = document.body.scrollHeight + 64;
    
    if(sWidth>screen.availWidth){   //Respeto el ancho de la pantalla
        sWidth = screen.availWidth;
    }
    
    if(sHeight>screen.availHeight){ //Respeto el alto de la pantalla
        sHeight = screen.availHeight;
    }
    
    try{
        //  Como los skins aberrantes de XP y Vista afectan al comportamiento del resizeTo, lo hago
        //  en funcion del cambio de tamanio del contenido de la pagina.

        window.resizeBy(document.body.scrollWidth - document.documentElement.clientWidth, document.body.scrollHeight - document.documentElement.clientHeight);
    }catch(ex){
    }
}


function wait(millis) 
{
    var date = new Date();
    var curDate = null;

    do { curDate = new Date(); } 
    while(curDate-date < millis);
}


/**
Muestra en pantalla/Oculta un cartel para evitar que se puedan clickear los controles en pantalla
    xHab: si se debe mostrar u ocultar
    xMsg: Override del texto 'Guardando datos...' del cartel
    
    Tambien oculta/muestra todos los combos de la pantalla porque IE los muestra por encima del splash
**/

//var mutex = false;  //Exclusion cuando OCULTAR se ejecuta mas rapido que MOSTRAR
//var showCount = 0;  //Evitar multiples MOSTRAR y OCULTAR
function showSplash(xHab){
    
    var theBody = document.getElementsByTagName('BODY')[0];

    if(xHab){
        var splashscreen = document.createElement('div');
        splashscreen.id = 'splash';
        splashscreen.style.zindex = '200';
    	
    	var sHTML;
    	
    	sHTML = '<table style="width: 100%; height: 100%; vtext-align: center;" aling="center">';
    	sHTML += '<tr><td style="vertical-align:middle; text-align: center;">';
    	sHTML += '<table style="background-color: white; width: 200px; height: 40px;"><tr><td><img alt="Cargando" src="./Images/Loading.gif" /></td><td style="text-align: center; width: 150px;">Cargando ...</td></tr></table>';
		sHTML += '</td></tr>';
    	sHTML += '</table>';
    	
        splashscreen.innerHTML =  sHTML;
        
        theBody.appendChild(splashscreen);
        
        jQuery("#splash").dialog({
			height: 40,
			modal: true, 
			draggable: false,
			width: 200,
			closeOnEscape: false,
			zIndex: 3999
		});

        
    }else{
        if(jQuery("#splash") != null)
            jQuery("#splash").dialog("destroy");
    }
//    var operaCombos = false;
//    var theBody = document.getElementsByTagName('BODY')[0];

//    if(xHab){
//        showCount++;
//    }else{
//        showCount--;
//    }

//    //if(xHab && !mostrandoSplash){
//    if(xHab && (showCount == 1)){
//        mostrandoSplash = true;
//            
//        var splashscreen = document.createElement('div');
//        splashscreen.id = 'splash';
//        splashscreen.style.position = 'absolute';
//        splashscreen.style.zindex = '200';
//        splashscreen.style.top = '0px';
//        splashscreen.style.left = '0px';
//        splashscreen.style.padding = '0px';
//        splashscreen.style.margin = '0px';
//        splashscreen.style.width = '100%';
//        splashscreen.style.height = '100%';
//    	
//    	var sHTML;
//    	
//    	sHTML = '<table style="width: 100%; height: 100%; vtext-align: center;" aling="center">';
//    	sHTML += '<tr><td style="vertical-align:middle; text-align: center;">';
//    	
//        if(xMsg == null){
//		    sHTML += '<table style="background-color: White; border: solid 1px black"><tr><td><img style="z-index: 255;" alt="Congelados Artico S.A." src="Images/logo.png"/></td><td style="text-align:center">Procesando...<br/>Por favor aguarde un momento.</td></tr></table>';
//		}else{
//		    sHTML += '<table style="background-color: White; border: solid 1px black"><tr><td><img style="z-index: 255;" alt="Congelados Artico S.A." src="Images/logo.png"/></td><td style="text-align:center">' + xMsg + '<br/>Por favor aguarde un momento.</td></tr></table>';
//		}
//		
//    	sHTML += '</td></tr>';
//    	sHTML += '</table>';

//    	//Agrego el fondo oscurecido
//    	//sHTML += '<div style="position: absolute; z-index: -1; top: 0px; left: 0px; width: 100%; height: ' + document.documentElement.scrollHeight + 'px; opacity: .4; filter: alpha(opacity=40); background-color:transparent; background-color: #333333 !important;"></div>';
//    	sHTML += '<div style="position: absolute; z-index: -1; top: 0px; left: 0px; width: 100%; height: ' + document.documentElement.scrollHeight + 'px; filter: progid:DXImageTransform.Microsoft.AlphaImageLoader(src="overlay.png", sizingMethod="scale"; background-color:transparent; background-color: #333333;background-image: url(overlay.png)"></div>';
//    	
//    	
//        splashscreen.innerHTML =  sHTML;
//        
//        if(!mutex){
//            theBody.appendChild(splashscreen);
//            operaCombos = true;
//        }else{
//            xHab = false;    //Simulo que se esta ocultando
//            mutex = false;    //Simulo que se esta ocultando
//        }
//        
//        mutex = false;
//    }else if(!xHab && showCount == 0){
//        var theSplash = document.getElementById('splash');
//        
//        if(theSplash != null){
//            theBody.removeChild(theSplash);
//            operaCombos = true;
//        }else if(mostrandoSplash){
//            mutex = true;   //Evito mostrar la pantalla
//        }

//        mostrandoSplash = false;
//    }
//    
//    if(!operaCombos){
//        return;
//    }
//    
//    //OCULTO/MUESTRO los combos porque IE los muestra ENCIMA del Splash
//    for(x in document.body.all){
//        if (document.body.all[x].tagName == "SELECT"){
//            if (xHab){
//                document.body.all[x].style.visibility = "hidden";
//            }else{
//                document.body.all[x].style.visibility = "visible";
//            }
//        }
//    }
}

/**
El XML debe tener una estructura comun para poder utilizar esta funcion:
    Elemento Error:     [0|1] -> indica si ocurrio un error.
    Elemento ErrorDesc: [String] -> si ocurrio error, contiene el mensaje de error a mostrar.
    
Parametros:
    xGETStr:        Direccion de la pagina/XML a llamar
    xParseFunction: Funcion de retorno a ser llamada luego que se comprobó que la operación no devolvió error
    xSplash:        (Opcional|Default: true) Si debe mostrar un splashscreen
    xErrorReturn:   Función de retorno al ocurrir recibir mensaje de error de la página
    
Función de retorno:    xParseFunction(dsRoot); xErrorReturn(dsRoot);
    dsRoot: Objeto XML devuelto por el objeto AJAX. Utilizado para
             parsear el XML restante en otra función.
             
    En el caso de xErrorReturn, si ocurre un error inesperado (como un XML mal formado), dsRoot vale null
             
Prerequicitos:
    Debe existir la funcion setError(xError) que muestre en pantalla el error ocurrido
**/
function operacionAJAX(xGETStr, xParseFunction, xSplash, xErrorReturn, xASync){
    var oAJAX = ObtenerObjetoAJAX();
       
    if(xSplash==null){
        xSplash = true;
    }
    
    if(xASync==null){
        xASync = true;
    }
        
    if(oAJAX!=null){
        oAJAX.onreadystatechange = 
        function(){
             if(oAJAX.readyState != 4)
                return;
	         if(oAJAX.status != 200)
	            return;
                         
             showSplash(false);
             	        
             var reader = new XMLReader(oAJAX.responseXML.documentElement);

             if(!reader.XMLValido){
		        setError('Error al realizar la transacción.');
                if(xErrorReturn!=null){
                    xErrorReturn(null);
                }
		        return;
		     }else if(reader.read('Error') == "1"){
                setError(reader.read('ErrorDesc'));
                //Se agrega la posibilidad de saber cuando devolvió error
                if(xErrorReturn!=null){
                    //Agrego la posiblidad de parsear XMLs de error con datos extra
                    xErrorReturn(reader);
                }
                return;
             }else if(xParseFunction!=null){
			    xParseFunction(reader);
             }
         }
	    
        oAJAX.open("GET", xGETStr + "&rand=" + nocacheGETString(), xASync);
        oAJAX.setRequestHeader('Content-Type','text/xml'); 
        oAJAX.send(null);  
       
        if(xSplash){
            showSplash(true);
        }
    }else{
        setError('Su explorador de Internet parece no ser compatible.');
    }
}

//Creo un parametro GET unico para evitar problemas por cacheado de páginas
function nocacheGETString(){
    return "nocache=" + new Date().toString() + Math.random();
}

function XMLReader(xXML){
    if(typeof(xXML) == "string"){   //Es un XML en texto plano
        var sXML=new ActiveXObject("Microsoft.XMLDOM");
        sXML.async="false";
        this.XMLValido = sXML.loadXML(xXML);

    }else if(typeof(xXML) == "object"){ //ESPERO que sea un objeto xmlDocument, sino no se que puede pasar
        sXML = xXML;
        this.XMLValido = (xXML != null); 
    }
    
    this.XMLDOM = sXML;
    
    this.read = function(xfield){   //Lee el valor del primer campo con ese nombre
        return this.XMLDOM.getElementsByTagName(xfield)[0].text;
    }
    
    this.readBoolean = function(xfield){    //Lee el valor del primer campo con ese nombre y lo compara contra "1"
        return (this.read(xfield) == "1");
    }
    
    if(this.XMLValido){ //No es un XML, No asigno las funciones compatibles
        this.xml = this.XMLDOM.xml;     //Acceso al texto XML en bruto
        this.getElementsByTagName = function(xTag){ return this.XMLDOM.getElementsByTagName(xTag); };
    }}
    
    //Abre un ABM con los parámetros indicados
    function abrirABM(xURL,xModo,xWidth,xHeight,xGrilla,xClave,xParams)
    {
        var sURL;
        var sPosWin;

        sParamsGet = "Oper=" + xModo;
        //Completo el Get con las claves
        
        if (xModo!='A')
        {
            //traigo las claves 
            sArrayClaves = obtenerClavesTabla(xGrilla,xClave);
            if (sArrayClaves !=null)
                for (i=0;i<xClave.length ;i++)
	                sParamsGet += "&" + xClave[i] + "=" + sArrayClaves[i];
	        else
	            //No seleccionó ningún elemento de la grilla
	            return;
	    }
	    if (xParams !='')
	        sParamsGet += "&" + xParams
    	    
        sURL = xURL + '?' + sParamsGet;

	    //calculo la posicion
	    sPosWin = calcularPosVtanaCentradaDeSize(xWidth, xHeight);
	    window.open(sURL, '_blank', 'width=' + xWidth + ', height=' + xHeight + ', menubar=1, resizable=1, statusbar=1, scrollbars=1, location=0, top='+sPosWin[1] +', left='+sPosWin[0] );
    	
        //Para que no haga el postback de la grilla
        try{
            igtbl_cancelPostBack(xGrilla);
        }catch(ex){}

    }

    //Devuelve un array con los campos clave de la tabla
    function obtenerClavesTabla(xGrilla,xClave)
    {
        var sFilaAct;
        var sGrilla = igtbl_getGridById(xGrilla); //busco la grilla
        
        if (sGrilla != null){
            sFilaAct = sGrilla.getActiveRow();
            if (sFilaAct != null){
                var sArrayClaves = new Array();
                for (i=0;i<xClave.length ;i++)
                {
                    sArrayClaves[i] = sFilaAct.getCellFromKey(xClave[i]).getValue();
                }
                return sArrayClaves;
            }
        }
        //si llego aca es xq no pudo obtener la clave
        return null;
    }
    
    //Muestra el valor de un parámetro enviado a la página por GET
    //Funciona como el Request.QueryString de ASP .NET
    //xKey --> Parametro a ver
    //xWindow --> objeto ventana del cual tomar los parámetros
    function JS_QueryString(xKey, xWindow)
        {
        var sQuery = new String("");
        var sKeys = new Array();
        var i;
        if (xKey == null)
            return null;
        sQuery = xWindow.location.search;//obtiene la parte de los parámetros 
        if (sQuery.length > 0)
            sQuery = sQuery.substring(1,sQuery.length);
        if (sQuery.length == 0)
            return null;
        sKeys = sQuery.split('&');//separa los parámetros
        for (i=0; i<sKeys.length; i++)
            {//separa el nombre del parámetro del valor
            //nombre = valor
            if(sKeys[i].split("=")[0].toLowerCase() == xKey.toLowerCase())
				return unescape(sKeys[i].split("=")[1]);
            }
        return null;
        }

    function DblClickGrillaDummy(xGrid, xCell)
    {
        return false;
    }