﻿/// <reference path="./jquery-1.4.4-vsdoc.js">

var Helper = {};

// Miembros privados
Helper._controls    = null;
Helper._wndImagenes = null;
Helper._wndHelps = null;
Helper._elementsIds = {};

Helper._minWidthOnResize = 370;
Helper._windowMargen     = 215;

Helper.windowSize = function() 
{
    var myWidth = 0, myHeight = 0;

    if (typeof(window.innerWidth) == 'number') //Non-IE
    {
        myWidth = window.innerWidth;
        myHeight = window.innerHeight;
    } 
    else if(document.documentElement && (document.documentElement.clientWidth || document.documentElement.clientHeight)) //IE 6+ in 'standards compliant mode'
    {
        myWidth = document.body.parentNode.clientWidth;
        myHeight = document.body.parentNode.clientHeight;
    } 
    else if(document.body && (document.body.clientWidth || document.body.clientHeight)) //IE 4 compatible
    {
        myWidth = document.body.clientWidth;
        myHeight = document.body.clientHeight;
    }
    
    return { width: myWidth, height: myHeight };
}

Helper.elementDel = function(id) 
{
    if (id in Helper._elementsIds)
        delete Helper._elementsIds[id];
}
    
Helper.elementClear = function(id) 
{
    Helper._elementsIds = {};
}

Helper.elementGet = function(id) 
{
    var retorno;
    var doc = document;
    
    try
    {
        if (!(id in Helper._elementsIds))
        {
            var element = doc.getElementById(id);
            if (element == null)
                retorno = null;
            else
            {
                Helper.elementAdd(doc.getElementById(id));
                retorno = Helper._elementsIds[id];
            }
        }
        else
        {
            if ((Helper._elementsIds[id].sourceIndex == 0) || (Helper._elementsIds[id].parentNode == null)) /* verifica si el elemento fue removido del DOM */
            {
                Helper._elementsIds[id] = null;
                Helper._elementsIds[id] = doc.getElementById(id);
            }
            retorno = Helper._elementsIds[id];
        }
    }
    catch(e)
    {
        retorno = null;
    }
    
    return retorno;
}
    
Helper.elementAdd = function(element) 
{
    var id = element.id;
    if ((!(id in Helper._elementsIds)) || (element != Helper._elementsIds[id]))
        Helper._elementsIds[id] = element;
}

Helper.parseIntDef = function(valor, valorDefault)
{
	var ret = parseInt(valor);
	if (isNaN(ret))
		ret = valorDefault;
	return ret;
}

Helper.parseFloatDef = function(valor, valorDefault)
{
	var ret = parseFloat(valor);
	if (isNaN(ret))
		ret = valorDefault;
	return ret;
}

Helper.formatNumber = function(value, format)
{
	if (format == "") return value.toString();

	// descomponer formato
	if (format.indexOf(".") == -1) format += ".";
	fmt = format.split(".");

	// convertir valor a string
	str = value.toFixed(fmt[1].length);
	if (str.indexOf(".") == -1) str += ".";
	str = str.split(".");

	// rellenar parte entera
	ent = Math.abs(parseInt(str[0])).toString();
	siz = (fmt[0].length > ent.length) ? fmt[0].length : ent.length;
	ent = fmt[0] + ent;
	ent = ent.substr(ent.length - siz, siz);
	if (value < 0) ent = "-" + ent;
	
	// rearmar
	return (str[1] != "") ? ent + "." + str[1] : ent;
}

Helper.mostrarPopupImagen = function(imagen, ancho, alto)
{
    var url = "/SitioNosisWeb/MostrarPopupImagen.aspx"
        + "?Imagen=" + escape(imagen)
        + "&Ancho=" + ancho
        + "&Alto=" + alto;
    
    var x = parseInt((screen.width - ancho) / 2, 10);
    var y = parseInt((screen.height - alto) / 2, 10);
        
    var options = ""
        + "menubar=0"
        + ", toolbar=0"
        + ", status=0"
        + ", scrollbars=0"
        + ", width=" + (ancho + 25)
        + ", height=" + (alto + 25)
        + ", left=" + x
        + ", top=" + y;

    if (this._wndImagenes != null) this._wndImagenes.close();
    this._wndImagenes = window.open(url, "MostrarPopupImagen", options);
}


Helper.mostrarPopupHelp = function (urlHelp, ancho, alto, directa) {


    var url;

    directa = directa ? true : false;

    if (directa) {
        url = urlHelp;
    }
    else {

        url = escape(urlHelp)
        + "?Ancho=" + ancho
        + "&Alto=" + alto;
    }
    var x = parseInt((screen.width - ancho) / 2, 10);
    var y = parseInt((screen.height - alto) / 2, 10);

    var options = ""
        + "menubar=0"
        + ", toolbar=0"
        + ", status=0"
        + ", scrollbars=auto"
        + ", width=" + (ancho + 25)
        + ", height=" + (alto + 25)
        + ", left=" + x
        + ", top=" + y;

    if (this._wndHelps != null) this._wndHelps.close();
    this._wndHelps = window.open(url, "MostrarPopupHelp", options);
}

// Para la apertura de los links del area NOVEDADES [ Guille | 02-06-08 ]
Helper.mostrarNovedades = function(urlHelp, ancho, alto)
{
    // NOTA: si agrego el "escape" no me funciona
    var url = urlHelp
        + "?Ancho=" + ancho
        + "&Alto=" + alto;
        
    var x = parseInt((screen.width - ancho) / 2, 10);
    var y = parseInt((screen.height - alto) / 2, 10);
        
    var options = ""
        + "menubar=0"
        + ", toolbar=0"
        + ", status=0"
        + ", scrollbars=auto"
        + ", width=" + (ancho + 25)
        + ", height=" + (alto + 25)
        + ", left=" + x
        + ", top=" + y;
    
    if (this._wndHelps != null) this._wndHelps.close();
    this._wndHelps = window.open(url, "MostrarNovedades", options);
}


// Devuelve el elemento cuyo id termine con el parametro especificado
// Ej: clientId = ctl00_ContentPlaceHolderBody_<aspnetId>
Helper.getElement = function(aspnetId)
{
    // Carga perezosa del array de controles
    if (Helper._controls == null)
    {
        Helper._controls = new Array();
        Helper._addControls(document.forms[0]);
    }

    // Primero itenta resolver el id desde el array
    // y si no existe busca en el documento completo   
    var clientId = Helper._controls[aspnetId];
    if (clientId)
        return Helper.elementGet(clientId); //document.getElementById(clientId);
    else
        return Helper.elementGet(aspnetId); //document.getElementById(aspnetId);
}

// Asigna codigo html a traves de la property innerHtml
// En IE es medio conflictivo
Helper.setInnerHTML = function(node, html)
{
    if (node == null || node.innerHTML == null) return;
    node.innerHTML = html;
    node.innerHTML = node.innerHTML; // tweak para IE en algunas maquinas no refrescaba
}

// Carga los ID recorriendo recursivamente el DOM HTML
// Método privado 
Helper._addControls = function(node)
{
    while (node)
    {
        if (node.nodeType == 1) {
            var i = node.id.lastIndexOf("_");
            if (i >= 0)
            {
                var key = node.id.substring(i+1);
                Helper._controls[key] = node.id;
            }
            Helper._addControls(node.firstChild);
        }
        node = node.nextSibling;
    }
}


//Obtiene el texto seleccionado de un "objeto select" (combo)
Helper.objSelectText = function ( objSelect ) {
   var indxSelected = objSelect.selectedIndex;
   return objSelect.options[indxSelected].text;
}

Helper.cancelEnter = function(e)
{
    var characterCode = Helper.keyCode(e); //character code is contained in IE's keyCode property
    if(characterCode == 13)//if generated character code is equal to ascii 13 (if enter key)    
    {
        if(arguments.length > 1)
            arguments[1]();
        return false;
    }  
    return true;
}

Helper.keyCode = function(e)
{
    var keynum;
    if (window.event) // IE 
    { 
        keynum = e.keyCode;
    } 
    else if (e.which) // Netscape/Firefox/Opera 
    { 
        keynum = e.which;
    } 
    return keynum;
}

Helper.focus = function(ctrl)
{
    try { ctrl.focus(); } catch (ex) {}
}

Helper.ClearClass = function(obj)
{
    obj.setAttribute("className","")
    if (String(obj.getAttribute("title")).length > 0)
        obj.setAttribute("title","");
}

Helper.procesando = function()
{
    if( document.getElementById("ctl00_hideProcesando").value == "0")
    {
        document.getElementById("ctl00_hideProcesando").value = "1";
        return false;
    }
    else    
        return true;    
}

Helper.procesandoCancelar = function()
{
    document.getElementById("ctl00_hideProcesando").value = "0";
}

Helper.Resaltar = function(txtObj, opcion)
{
    var obj = Helper.getElement(txtObj);
    if (opcion == true) 
    { 
        Helper._setStyle(obj, 'font-weight:bold;text-decoration:underline;');
    }
    else
    { 
        Helper._setStyle(obj, 'font-weight:normal;text-decoration:none;');
    }
}

Helper._rzCC = function(s)
{
    for(var exp=/-([a-z])/; 
        exp.test(s); 
        s=s.replace(exp,RegExp.$1.toUpperCase()));
    return s;
}

Helper._setStyle = function(element, declaration) 
{
    if (declaration.charAt(declaration.length-1)==';')
        declaration = declaration.slice(0, -1);
    var k, v;
    var splitted = declaration.split(';');
    for (var i=0, len=splitted.length; i<len; i++) 
    {
        k = Helper._rzCC(splitted[i].split(':')[0]);
        v = splitted[i].split(':')[1];
        eval("element.style." + k + "='" + v + "'");
    }
}

Helper.replaceNodeText = function(element, text)
{
    var txtNode = document.createTextNode(text);
    Helper.removeAllChildNodes(element);
    element.appendChild(txtNode);
}

Helper.replaceTextInElement = function(element, text, isHTML)
{
    try
    {
        if (typeof(isHTML) == 'undefined')
            isHTML = false;
            
        if ((element.childNodes[0]) && (isHTML == false))
            element.childNodes[0].nodeValue = text;
        else if ((element.value) && (isHTML == false))
            element.value = text;
        else
            element.innerHTML = text;
    }
    catch(e)
    {
    }
}

Helper.removeAllChildNodes = function (node)
{
      if(!node || !node.childNodes) return;
      var nodeCount = node.childNodes.length;
      for(var i=nodeCount-1;i>=0;i--)
      {
          if (node.childNodes[i].childNodes)
              Helper.removeAllChildNodes(node.childNodes[i]);
      
          Helper.elementDel(node.childNodes[i].id);
            node.removeChild(node.childNodes[i]);
      }
}

Helper.removeElement = function(id)
{
    var element = Helper.getElement(id);
    if (element != null)
    {
        Helper.removeAllChildNodes(element);
        var perent = element.parentNode;
          Helper.elementDel(id);
        perent.removeChild(element);
    }
}


Helper.insertAfter = function(newElement,targetElement) 
{
    var parent = targetElement.parentNode;
    if (parent.lastChild == targetElement) 
    {
        parent.appendChild(newElement);
    }
    else
    {
        parent.insertBefore(newElement,targetElement.nextSibling);
    }
}

Helper.trim = function(str) 
{
	var whitespace = ' \n\r\t\f\x0b\xa0\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u200b\u2028\u2029\u3000';
	
	if (str == null)
	    str = "";
	    
	for (var i = 0; i < str.length; i++) {
		if (whitespace.indexOf(str.charAt(i)) === -1) {
			str = str.substring(i);
			break;
		}
	}
	for (i = str.length - 1; i >= 0; i--) {
		if (whitespace.indexOf(str.charAt(i)) === -1) {
			str = str.substring(0, i + 1);
			break;
		}
	}
	return whitespace.indexOf(str.charAt(0)) === -1 ? str : '';
}

/* Funciones Cookie */

Helper.getCookie = function(cookieName)
{
  if (document.cookie.length > 0)
  {
  	c_start = document.cookie.indexOf(cookieName + "=");
  	if (c_start != -1)
    { 
	    c_start = c_start + cookieName.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 "";
}

Helper.setCookie = function(cookieName, value, expiredays)
{
	var exdate = new Date();
	exdate.setDate(exdate.getDate() + expiredays);
	document.cookie = cookieName+ "=" +escape(value)
	                 +((expiredays==null) ? "" : ";expires="+exdate.toGMTString())
	                 + ";path=/";
	                 
}

Helper.eraseCookie = function(cookieName)
{
	Helper.setCookie(cookieName, "", -1);
}

/*
    informa al servidor por las excepciones en JS que ocurren en el sitio
*/
Helper.informarExcepcion = function (funcion, contenido, ex, respuesta) {

    try {

        return;

        if (typeof (respuesta) == "undefined")
            respuesta = "";

        var error = new SitioNosisWeb.Servicios.DtoLogException();

        error.funcion = funcion;
        jQuery.each(jQuery.browser, function (i, val) {
            if (val) { error.browser = i + ": " + jQuery.browser.version; }
        }
        );
        error.contenido = Helper.XToString(contenido);
        error.respuesta = respuesta;

        error.ex_name = ex.name;
        error.ex_message = ex.message;
        error.ex_number = ex.number + "";
        error.ex_description = ex.description;

        SitioNosisWeb.Servicios.ServiciosJavascript.LogException(
            error,
            Helper.controlErroresJS_onServiceSucceeded,
            Helper.controlErroresJS_onServiceFailed);
    }
    catch (exc) {
    }
}

Helper.XToString = function(valor)
{
    var retorno = "";
    try 
    {
        var _typeOf = Helper.type.of(valor);
        var _objToString = function(a, type)
        {
            var str;
            var key;
            
            str = (type=='array')?'[':'{';
            for (key in a) 
            { 
                str += key + ':' + _toString[Helper.type.of(a[key])](a[key]) + ','; 
            }
            str = str.replace(/\,$/, '') + ((type=='array')?']':'}');
            return str;
        };
            
        var _toString = {
            "null":function(a){
                return "null";
            },
            "undefined":function(a){
                return "undefined";
            },
            "nt":function(a){
                return "null/undefined";
            },
            "function":function(a){
                return a.toString();
            },
            "string":function(a){
                return a;
            },
            "array":function(a){
                return _objToString(a, "array");
            },
            "boolean":function(a){
                return (a)?"true":"false";
            },
            "date":function(a){
                return a.toString();
            },
            "html":function(a){
                return a.toString();
            },
            "number":function(a){
                return a.toString();
            },
            "object":function(a){
                return _objToString(a, "");
            },
            "regexp":function(a){
                return a.toString();
            }
        }
    
        retorno = _toString[_typeOf](valor);
    }
    catch(exc) {}
    
    return retorno;
}

Helper.delWait = function()
{                    
   if (jQuery('#capaPantallaCompleta').length!=0)
   {
      jQuery('#capaPantallaCompleta').remove();
   }
}
        
Helper.setWait = function(options)
{
   try
   {
      // corta si supera a 5 segundos
      setTimeout('Helper.delWait()', 5000);
   
      // seteos por defecto
      var defaults = {
         'element':'',
         'filter':0,
         'bgColor':'#FFFFFF',
         '_left':'0',
         '_top':'0',
         '_position':'fixed',
         '_width':jQuery(document).width(),
         '_height':jQuery(window).height(),
         '_container':document.body
      };
      
      // union de la configuracion por defecto y la del usuario
      var setting = jQuery.extend(defaults, options);   
   
      // configuracion de una pantalla
      if (setting.element!='')
      {
         setting._left = '';
         setting._top = '';
         setting._position = 'relative'; //absolute

         setting._container = setting.element;
         setting._width = jQuery(setting.element).width();
         setting._height = jQuery(setting.element).height();
      }
   
      // creacion del elemento con jQuery
      var xDiv = jQuery(((jQuery('#capaPantallaCompleta').length==0)?'<div id="capaPantallaCompleta"></div>':'#capaPantallaCompleta'))
         .css('background-color', setting.bgColor)
         .css('left', setting._left)
         .css('top', setting._top)
         .css('cursor', 'wait')
         .css('position', setting._position)
         .css('filter', 'alpha(opacity='+setting.filter+')')
         .css('-moz-opacity', (setting.filter/100))
         .css('opacity', (setting.filter/100))
         .css('width', setting._width)
         .css('height', setting._height);

      // insercion del elemento en el DOM container 
      jQuery(setting._container).append(xDiv);
   }
   catch(ex)
   {
   }
}

Helper.type = {

    of: function (a) {
        for (var i in Helper.type.is) {
            if (Helper.type.is[i](a))
                return i;
        }
    },

    is: {
        "null": function (a) {
            return a === null;
        },
        "undefined": function (a) {
            return (a === undefined) ? true : ((typeof (a) === 'object') ? (typeof (a.callee) !== 'undefined') : false);
        },
        "nt": function (a) {
            return (a === null || a === undefined);
        },
        "function": function (a) {
            return (typeof a === 'function') ? a.constructor.toString().match(/Function/) !== null : false;
        },
        "string": function (a) {
            return (typeof a === 'string') ? true : (typeof (a) === 'object') ? a.constructor.toString().match(/string/i) !== null : false;
        },
        "array": function (a) {
            return (typeof a === 'object') ? a.constructor.toString().match(/array/i) !== null || a.length !== undefined : false;
        },
        "boolean": function (a) {
            return (typeof a === 'boolean') ? true : (typeof (a) === 'object') ? a.constructor.toString().match(/boolean/i) !== null : false;
        },
        "date": function (a) {
            return (typeof a === 'date') ? true : (typeof (a) === 'object') ? a.constructor.toString().match(/date/i) !== null : false;
        },
        "html": function (a) {
            return (typeof a === 'object') ? a.constructor.toString().match(/html/i) !== null : false;
        },
        "number": function (a) {
            return (typeof a === 'number') ? true : (typeof (a) === 'object') ? a.constructor.toString().match(/Number/) !== null : false;
        },
        "object": function (a) {
            return (typeof a === 'object') ? a.constructor.toString().match(/object/i) !== null : false;
        },
        "regexp": function (a) {
            return (typeof a === 'function') ? a.constructor.toString().match(/regexp/i) !== null : false;
        }
    }
};

Helper.controlErroresJS_onServiceSucceeded = function (result, eventArgs) {
    try {
        if (result.respuesta != "") {
            var elemento = Helper.getElement(result.respuesta);
            elemento.innerHTML = "Ref. " + result.referencia;
        }
    }
    catch (ex) {
    }
};

Helper.controlErroresJS_onServiceFailed = function (error) {
};

Helper.CookieNotiLeidas = function (idNoticia) {

    var  
        notiLeidas = Helper.getCookie("notiLeidas"),
        idLeidos = new Array();

    if (notiLeidas.length > 0)
        idLeidos = notiLeidas.split(",");

    idLeidos[idLeidos.length] = idNoticia;
    Helper.setCookie("notiLeidas", idLeidos, 365);

}

Helper.T = function (indice) {
    try {
        if (typeof (dicRegional) == "undefined")
            return indice              // Retorna la texto en el idioma por defecto si no existe la variable de diccionario
        else if (typeof (dicRegional[indice]) == "undefined")
            return indice              // Retorna la texto en el idioma por defecto si no existe en el idioma traducido
        else
            return dicRegional[indice] // Retorna el texto traducido
    }
    catch (ex) {
        return indice;                // Retorna la texto en el idioma por defecto si sucede un error
    }
};

T = function (indice) { return Helper.T(indice); };

// reemplaza funcion open de window
Helper.window = new function () {

    // Private fields
    var w = window, s = screen, _self = this, whs = {}, isChrome = /chrome/.test(navigator.userAgent.toLowerCase());

    // Public Members
    this.focus = function (wh) {
        if (!wh) return;
        if (isChrome) wh.blur();
        wh.focus();
    };

    this.windowExists = function (wt) {
        return wt && whs[wt] && (typeof whs[wt]['closed'] != undefined) && !whs[wt].closed;
    };

    this.close = function (wt) {

        if (typeof whs[wt][close] != undefined) whs[wt].close();
        whs[wt] = null;

        return _self;
    };

    this.properties = function (wp) {

        wp = (wp || 'menubar=yes').toLowerCase();

        if (!(/menubar/.test(wp)))
            wp += 'menubar=yes';

        if (!(/location/.test(wp)))
            wp += ',location=yes';

        if (!(/width/.test(wp)))
            wp += ',width=' + (s.availWidth - 150);

        if (!(/height/.test(wp)))
            wp += ',height=' + (s.availHeight - 150);

        if (!(/scrollbars/.test(wp)))
            wp += ',scrollbars=yes';

        if (!(/resizable/.test(wp)))
            wp += ',resizable=yes';

        return wp;
    };

    this.open = function (url, wt, wp) {

        if (_self.windowExists(wt))
            return _self.close(wt).open(url, wt, wp);

        var urlOpen = '';
        if (typeof url == 'string') {
            urlOpen = url;
        } else if (jQuery(url).length > 0 && jQuery(url).get(0).tagName.toLowerCase() == 'a') {
            urlOpen = jQuery(url).attr('href');
        } else {
            urlOpen = 'about:blank';
        }

        wp = _self.properties(wp);
        wt = wt || "_blank";

        var wh = wp ? w.open(urlOpen, wt, wp) : w.open(urlOpen, wt);

        if (wh && "_blank" !== wt) {
            whs[wt] = wh;
            _self.focus(wh);
        }

        return wh;
    };

};

Helper.formatearCUIT = function (cuit) {
    cuit = Helper.limpiarCodigos(cuit, false);
    if (jQuery.trim(cuit).length == 11) {
        cuit = cuit.substr(0, 10) + "-" + cuit.substr(10);
        cuit = cuit.substr(0, 2) + "-" + cuit.substr(2);
    }
    return cuit;
};

Helper.limpiarCodigos = function (codigo, isDDN) {
    if (codigo) {
        if (codigo.indexOf("-") != -1)
            codigo = codigo.replace("-", "");
        if (codigo.indexOf("+") != -1)
            codigo = codigo.replace("+", "");
        if (codigo.indexOf(".") != -1)
            codigo = codigo.replace(".", "");
        if (codigo.indexOf(",") != -1)
            codigo = codigo.replace(",", "");
        if (codigo.indexOf(" ") != -1)
            codigo = codigo.replace(" ", "");

        if (isDDN && codigo.substr(0, 1) == "0") {
            while (codigo.substr(0, 1) == "0")
                codigo = codigo.substr(1);
        }
    }
    return jQuery.trim(codigo);
};

/* ### Funciones Cookie */

//FUNCIONES QUE EXTIENDEN OBJETOS DE JAVASCRIPT 
//String.prototype.trim = function(){ return this.replace(/^\s+/,'').replace(/\s+$/,''); }

/* JULI modifica el trim por Helper.trim(x) */

// the internal pad prototype
String.prototype._pad = function (width, padChar, side) {
    var str = [side ? "" : this, side ? this : ""];
    while (str[side].length < (width ? width : 0)
    && (str[side] = str[1] + (padChar ? padChar : " ") + str[0]));
    return str[side];
};

//  pad functions for general use
// "width" is the total width to pad to,
// "padChar" is the optional pad character -- default " "
String.prototype.padLeft = function (width, padChar) {
    return this._pad(width, padChar, 0)
};

String.prototype.format = function () {
    if (arguments.length == 0)
        return null;

    var str = this;

    for (var i = 0; i < arguments.length; i++) {
        var re = new RegExp('\\{' + (i) + '\\}', 'gm');
        str = str.replace(re, arguments[i]);
    }

    return str;
};

String.prototype.padRight = function (width, padChar) {
    return this._pad(width, padChar, 1)
};

Number.prototype.padLeft = function (width, padChar) {
    return ("" + this).padLeft(width, padChar)
};

Number.prototype.padRight = function (width, padChar) {
    return ("" + this).padRight(width, padChar)
};

/* CertiSur Seal (SITIO SEGURO) - JavaScript version 1.0 */
function Seal_Certificado(host_name, lang, version) {
    u1 = "https://seal.certisur.com/getseal?host_name=" + host_name + "&lang=" + lang + "&version=" + version;
    if (opener && !opener.closed) {
        opener.focus();
    } else {
        var w = 810,
            h = 512,
            x = (screen.width / 2) - (w / 2), 
            y = (screen.height / 2) - (h / 2) - 30,
            tbar = 'location=yes,status=yes,resizable=yes,scrollbars=yes,width=' + w + ',height=' + h + ',left=' + x + ',top=' + y,
            sw = window.open(u1, 'CS_Seal', tbar);

        if (sw) {
            sw.focus();
            opener = sw;
        }
    }
};
