﻿if (Tesla==undefined) var Tesla = function() { return this; }
if (Tesla.Utils==undefined) Tesla.Utils = function() { return this; } 

/*************************************************************************************************************************
* ******************************        Biblioteca Uteis      ************************************************************
* ************************************************************************************************************************/


Tesla.Utils = function()
{
    /// <summary>
    /// Construtor
    /// </summary>
    this.BackupComandos = new Array();
    this.CookieCaminhoPadrao = '';
    this.CookieDominioPadrao = document.location.hostname;
    return this;
}

Tesla.Utils.MarcaCheckBox = function(marcaCheckBox, nomeCheckPadrao, objFunc)
{
    /// <summary>
    /// MarcaCheckBox - Marca/Desmarca todos os checkboxes com o nome indicado por nomeCheckPadrao - MarcaCheckBox(true,'nome',FuncFazAlgo)
    /// <param name="marcaCheckBox">false ou true, indica se deve marcar ou desmarcar</param>
    /// <param name="nomeCheckPadrao">nome do checkbox, atenção todos os checkboxes devem ter esse nome</param>
    /// <param name="objFunc">Passa o objeto(this) para a função de callback indicada por objFunc</param>
    /// </summary>
    var strCheckCli = '';
    var objCheckBoxes = document.forms[0].elements[nomeCheckPadrao];
    if (!objCheckBoxes)
        return;
    var countCheckBoxes = objCheckBoxes.length;
    if (!countCheckBoxes)
        objCheckBoxes.checked = marcaCheckBox;
    else
    {
        for (var i = 0; i < countCheckBoxes; i++)
        {
            objCheckBoxes[i].checked = marcaCheckBox;
            objFunc(objCheckBoxes[i]);
        }
    }

}
Tesla.Utils.getCheckBoxArray = function(nomeCheckPadrao, verificaChecked)
{
    /// <summary>
    /// getCheckBoxArray - Retorna um array {value,checked} - getCheckBoxArray('nome')
    /// <param name="nomeCheckPadrao">nome do checkbox, atenção todos os checkboxes devem ter esse nome</param>
    /// <param name="verificaChecked">Se devo retornar todos = 0, somente os marcados=1, ou somente os desmarcados=-1</param>
    /// </summary>
    var strCheckCli = '';
    var arrRet = new Array();

    var objCheckBoxes = document.forms[0].elements[nomeCheckPadrao];
    if (objCheckBoxes == undefined || !objCheckBoxes)
        return arrRet;

    var countCheckBoxes = objCheckBoxes.length;
    for (var i = 0; i < countCheckBoxes; i++)
    {
        if (verificaChecked != undefined && verificaChecked != 0)
        {
            var verifica = verificaChecked == -1 ? false : true;
            if (objCheckBoxes[i].checked != verifica)
                continue;
        }

        var novoObjChk = { value: objCheckBoxes[i].value, checked: objCheckBoxes[i].checked ? 1 : 0 }
        
        arrRet.push(novoObjChk);
    }
    if (countCheckBoxes == undefined || countCheckBoxes == 0)
    {
        if (verificaChecked != undefined && verificaChecked != 0)
        {
            var verifica = verificaChecked == -1 ? false : true;
            if (objCheckBoxes.checked == verifica)
            {
                var novoObjChk = { value: objCheckBoxes.value, checked: objCheckBoxes.checked ? 1 : 0 }
                arrRet.push(novoObjChk);
            }
        }
    }

    return arrRet;
}
/*
* Date Format 1.2.3
* (c) 2007-2009 Steven Levithan <stevenlevithan.com>
* MIT license
*
* Includes enhancements by Scott Trenda <scott.trenda.net>
* and Kris Kowal <cixar.com/~kris.kowal/>
*
* Accepts a date, a mask, or a date and a mask.
* Returns a formatted version of the given date.
* The date defaults to the current date/time.
* The mask defaults to dateFormat.masks.default.
*/

Tesla.Utils.dateFormat = function()
{
    /// <summary>
    /// dateFormat - Formata a data  - Date.dateFormat('dd-mm-yyyy HH:MM:ss') - retorna por exemplo (23-04-2009 19:32:12)
    /// </summary>
    var token = /d{1,4}|m{1,4}|yy(?:yy)?|([HhMsTt])\1?|[LloSZ]|"[^"]*"|'[^']*'/g,
		timezone = /\b(?:[PMCEA][SDP]T|(?:Pacific|Mountain|Central|Eastern|Atlantic) (?:Standard|Daylight|Prevailing) Time|(?:GMT|UTC)(?:[-+]\d{4})?)\b/g,
		timezoneClip = /[^-+\dA-Z]/g,
		pad = function(val, len)
		{
		    val = String(val);
		    len = len || 2;
		    while (val.length < len) val = "0" + val;
		    return val;
		};

    // Regexes and supporting functions are cached through closure
    return function(date, mask, utc)
    {
        var dF = Tesla.Utils.dateFormat;

        // You can't provide utc if you skip other args (use the "UTC:" mask prefix)
        if (arguments.length == 1 && Object.prototype.toString.call(date) == "[object String]" && !/\d/.test(date))
        {
            mask = date;
            date = undefined;
        }

        // Passing date through Date applies Date.parse, if necessary
        date = date ? new Date(date) : new Date;
        if (isNaN(date)) throw SyntaxError("invalid date");

        mask = String(dF.masks[mask] || mask || dF.masks["default"]);

        // Allow setting the utc argument via the mask
        if (mask.slice(0, 4) == "UTC:")
        {
            mask = mask.slice(4);
            utc = true;
        }

        var _ = utc ? "getUTC" : "get",
			d = date[_ + "Date"](),
			D = date[_ + "Day"](),
			m = date[_ + "Month"](),
			y = date[_ + "FullYear"](),
			H = date[_ + "Hours"](),
			M = date[_ + "Minutes"](),
			s = date[_ + "Seconds"](),
			L = date[_ + "Milliseconds"](),
			o = utc ? 0 : date.getTimezoneOffset(),
			flags = {
			    d: d,
			    dd: pad(d),
			    ddd: dF.i18n.dayNames[D],
			    dddd: dF.i18n.dayNames[D + 7],
			    m: m + 1,
			    mm: pad(m + 1),
			    mmm: dF.i18n.monthNames[m],
			    mmmm: dF.i18n.monthNames[m + 12],
			    yy: String(y).slice(2),
			    yyyy: y,
			    h: H % 12 || 12,
			    hh: pad(H % 12 || 12),
			    H: H,
			    HH: pad(H),
			    M: M,
			    MM: pad(M),
			    s: s,
			    ss: pad(s),
			    l: pad(L, 3),
			    L: pad(L > 99 ? Math.round(L / 10) : L),
			    t: H < 12 ? "a" : "p",
			    tt: H < 12 ? "am" : "pm",
			    T: H < 12 ? "A" : "P",
			    TT: H < 12 ? "AM" : "PM",
			    Z: utc ? "UTC" : (String(date).match(timezone) || [""]).pop().replace(timezoneClip, ""),
			    o: (o > 0 ? "-" : "+") + pad(Math.floor(Math.abs(o) / 60) * 100 + Math.abs(o) % 60, 4),
			    S: ["th", "st", "nd", "rd"][d % 10 > 3 ? 0 : (d % 100 - d % 10 != 10) * d % 10]
			};

        return mask.replace(token, function($0)
        {
            return $0 in flags ? flags[$0] : $0.slice(1, $0.length - 1);
        });
    };
} ();

// Some common format strings
Tesla.Utils.dateFormat.masks = {
    "default": "ddd mmm dd yyyy HH:MM:ss",
    shortDate: "m/d/yy",
    mediumDate: "mmm d, yyyy",
    longDate: "mmmm d, yyyy",
    fullDate: "dddd, mmmm d, yyyy",
    shortTime: "h:MM TT",
    mediumTime: "h:MM:ss TT",
    longTime: "h:MM:ss TT Z",
    isoDate: "yyyy-mm-dd",
    isoTime: "HH:MM:ss",
    isoDateTime: "yyyy-mm-dd'T'HH:MM:ss",
    isoUtcDateTime: "UTC:yyyy-mm-dd'T'HH:MM:ss'Z'"
};

// Internationalization strings
Tesla.Utils.dateFormat.i18n = {
    dayNames: [
		"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat",
		"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"
	],
    monthNames: [
		"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec",
		"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"
	]
};

// For convenience...
Date.prototype.format = function(mask, utc)
{
    return Tesla.Utils.dateFormat(this, mask, utc);
};

Tesla.Utils.Cookie = function(name)
{
    /// <summary>
    /// Cookie - Construtor do cookie, pode-se adicionar variaves em tempo de execução - Ex. var cook= new Tesla.utils.Cookie('tesla_id_teste'); cook.Valor = 'teste'; cook.store(numTimeout);
    /// </summary>
    this.$name = name;  // Remember the name of this cookie


    var allcookies = document.cookie;
    if (allcookies == "") return;


    var cookies = allcookies.split(';');
    var cookie = null;
    for (var i = 0; i < cookies.length; i++)
    {
        var nameCookie = cookies[i].substr(0, name.length);
        var j = 0;
        for (j = 0; ; j++)
        {
            if (nameCookie.substring(0, 1) == ' ')
                nameCookie = cookies[i].substr(j, name.length);
            else
                break;
        }
        if (nameCookie == (name))
        {
            cookie = cookies[i].substring(j - 1);
            break;
        }
    }

    if (cookie == null) return;

    var cookieval = cookie.substring(name.length + 1);

    var a = cookieval.split('&');
    for (var i = 0; i < a.length; i++)
        a[i] = a[i].split(':');

    for (var i = 0; i < a.length; i++)
    {
        this[a[i][0]] = decodeURIComponent(a[i][1]);
    }
}

Tesla.Utils.Cookie.prototype.store = function(daysToLive, path, domain, secure)
{
    /// <summary>
    /// Cookie.store - Salva o cookie na maquina cliente
    /// <param name="daysToLive">dias para ficar na maquina do cliente</param>
    /// <param name="path">caminho dentro do dominio (ex. '/site/publico/cookies')</param>
    /// <param name="domain">dominio (ex. 'http://localhost/danone')</param>
    /// <param name="secure">Indica se deve usar a segurança no cookie</param>
    /// </summary>
    if (path == undefined)
        path = this.CookieCaminhoPadrao;

    if (domain == undefined)
        domain = this.CookieDominioPadrao;

    var cookieval = "";
    for (var prop in this)
    {
        if ((prop.charAt(0) == '$') || ((typeof this[prop]) == 'function'))
            continue;
        if (cookieval != "") cookieval += '&';
        cookieval += prop + ':' + encodeURIComponent(this[prop]);
    }

    var cookie = this.$name + '=' + cookieval;
    if (daysToLive || daysToLive == 0)
    {
        cookie += "; max-age=" + (daysToLive * 24 * 60 * 60);
    }

    if (path) cookie += "; path=" + path;
    if (domain) cookie += "; domain=" + domain;
    if (secure) cookie += "; secure";

    document.cookie = cookie;
}

Tesla.Utils.Cookie.prototype.remove = function(path, domain, secure)
{
    /// <summary>
    /// Cookie.remove - Remove o cookie da maquina
    /// <param name="path">caminho dentro do dominio (ex. '/site/publico/cookies')</param>
    /// <param name="domain">dominio (ex. 'http://localhost/danone')</param>
    /// <param name="secure">Indica se deve usar a segurança no cookie</param>
    /// </summary>
    // Delete the properties of the cookie
    for (var prop in this)
    {
        if (prop.charAt(0) != '$' && typeof this[prop] != 'function')
            delete this[prop];
    }

    // Then, store the cookie with a lifetime of 0
    this.store(0, path, domain, secure);
}


Tesla.Utils.Cookie.enabled = function()
{
    /// <summary>
    /// Retorna true se está habilitado o cookie na maquina cliente
    /// </summary>
    if (navigator.cookieEnabled != undefined) return navigator.cookieEnabled;

    if (Cookie.enabled.cache != undefined) return Cookie.enabled.cache;

    document.cookie = "testcookie=test; max-age=10000";

    var cookies = document.cookie;
    if (cookies.indexOf("testcookie=test") == -1)
    {
        return Cookie.enabled.cache = false;
    }
    else
    {
        document.cookie = "testcookie=test; max-age=0";  // Delete cookie
        return Cookie.enabled.cache = true;
    }
}

Tesla.Utils.MostraMsg = function(msgTexto, msgTipo, tituloMensagem)
{
    /// <summary>
    /// Retorna os comandos de determinado evento - getEvento('txtBox','onclick')
    /// </summary>
    /// <param name="nomeObj">Id do objeto</param>
    /// <param name="nomeEvento">Id do evento</param>
    MostraMensagem(msgTexto, msgTipo, tituloMensagem);
    if (tituloMensagem.length == 0)
        document.getElementById('tdAviso').innerHTML = '';
    
}

Tesla.Utils.EscondeMsg = function()
{
    /// <summary>
    /// Retorna os comandos de determinado evento - getEvento('txtBox','onclick')
    /// </summary>
    /// <param name="nomeObj">Id do objeto</param>
    /// <param name="nomeEvento">Id do evento</param>
    EscondeMensagem();
}

Tesla.Utils.getEvento = function(nomeObj, nomeEvento)
{
    /// <summary>
    /// Retorna os comandos de determinado evento - getEvento('txtBox','onclick')
    /// </summary>
    /// <param name="nomeObj">Id do objeto</param>
    /// <param name="nomeEvento">Id do evento</param>
    var objAux = document.getElementById(nomeObj);
    if (objAux != undefined)
    {
        var browser = this.retornaBrowser();
        if (browser.Tipo == 'ie')
            return this.getEventoIE(nomeObj, nomeEvento);
        else
            return objAux.attributes[nomeEvento].value;
    }
}

Tesla.Utils.setEvento = function(nomeObj, nomeEvento, scriptEvento)
{
    /// <summary>
    /// Configura os comandos para um determinado evento - setEvento('txtBox','onclick','alert("opa")')
    /// </summary>
    /// <param name="nomeObj">Id do objeto</param>
    /// <param name="nomeEvento">Id do evento</param>
    /// <param name="scriptEvento">comandos javascript</param>

    var objAux = document.getElementById(nomeObj);
    if (objAux != undefined)
    {
        var browser = this.retornaBrowser();

        if (browser.Tipo == 'ie')
        {

            //objAux.attributes[nomeEvento].value = new Function(scriptEvento);
            this.setEventoIE(nomeObj, nomeEvento, scriptEvento);
            //}
        }
        else if (browser.Tipo == 'firefox')
            objAux.attributes[nomeEvento].value = scriptEvento;

    }
}

Tesla.Utils.getEventoIE = function(nomeObj, nomeEvento)
{
    /// <summary>
    /// Configura os comandos para um determinado evento no IE - setEventoIE('txtBox','onclick','alert("opa")')
    /// </summary>
    /// <param name="nomeObj">Id do objeto</param>
    /// <param name="nomeEvento">Id do evento</param>
    /// <param name="script">comandos javascript</param>
    var objAux = document.getElementById(nomeObj);
    var strCmd = '';

    if (objAux != undefined)
    {
        switch (nomeEvento.toLowerCase())
        {
            case 'onclick':
                strCmd = objAux.onclick;
                break;
            case 'onkeypress':
                strCmd = objAux.onkeypress;
                break;
            case 'onkeydown':
                if (script.length > 0)
                    strCmd = objAux.onkeydown;
                break;
            case 'onkeyup':
                if (script.length > 0)
                    strCmd = objAux.onkeyup;
                break;
            case 'onmousedown':
                if (script.length > 0)
                    strCmd = objAux.onmousedown;
                break;
            case 'onmouseup':
                if (script.length > 0)
                    strCmd = objAux.onmouseup;
                break;
            case 'ondblclick':
                if (script.length > 0)
                    strCmd = objAux.ondblclick;
                break;
        }
    }
    if (strCmd.toString().length > 2)
    {
        strCmd = strCmd.toString().split('{')[1];
        strCmd = strCmd.toString().split('}')[0];
    }
    return strCmd;
}

Tesla.Utils.setEventoIE = function(nomeObj, nomeEvento, script)
{
    /// <summary>
    /// Configura os comandos para um determinado evento no IE - setEventoIE('txtBox','onclick','alert("opa")')
    /// </summary>
    /// <param name="nomeObj">Id do objeto</param>
    /// <param name="nomeEvento">Id do evento</param>
    /// <param name="script">comandos javascript</param>
    var objAux = document.getElementById(nomeObj);
    if (objAux != undefined)
    {
        switch (nomeEvento.toLowerCase())
        {
            case 'onclick':
                if (script.length > 0)
                    objAux.onclick = new Function(script);
                else
                    objAux.onclick = '';
                break;
            case 'onkeypress':
                if (script.length > 0)
                    objAux.onkeypress = new Function(script);
                else
                    objAux.onkeypress = '';
                break;
            case 'onkeydown':
                if (script.length > 0)
                    objAux.onkeydown = new Function(script);
                else
                    objAux.onkeydown = '';
                break;
            case 'onkeyup':
                if (script.length > 0)
                    objAux.onkeyup = new Function(script);
                else
                    objAux.onkeyup = '';
                break;
            case 'onmousedown':
                if (script.length > 0)
                    objAux.onmousedown = new Function(script);
                else
                    objAux.onmousedown = '';
                break;
            case 'onmouseup':
                if (script.length > 0)
                    objAux.onmouseup = new Function(script);
                else
                    objAux.onmouseup = '';
                break;
            case 'ondblclick':
                if (script.length > 0)
                    objAux.ondblclick = new Function(script);
                else
                    objAux.ondblclick = '';
                break;
        }
    }
}

Tesla.Utils.retornaBrowser = function()
{
    /// <summary>
    /// Retorna um objeto com os campos Tipo e Versão do Browser - var browser = retornaBrowser(); if(browser.Tipo=='firefox' && browser.Versao>=3) alert();
    /// </summary>
    var tipoBrowser = { Tipo: '', Versao: 0 };

    if (navigator.appName == 'Microsoft Internet Explorer')
    {
        var rv = -1;
        var ua = navigator.userAgent;
        var re = new RegExp("MSIE ([0-9]{1,}[\.0-9]{0,})");
        if (re.exec(ua) != null)
            rv = parseFloat(RegExp.$1);
        tipoBrowser.Tipo = 'ie';
        tipoBrowser.Versao = rv;
    }
    else if (/Firefox[\/\s](\d+\.\d+)/.test(navigator.userAgent))
    {
        var ffversion = new Number(RegExp.$1)
        tipoBrowser.Tipo = 'firefox';
        tipoBrowser.Versao = ffversion;
    }
    else if (/Opera[\/\s](\d+\.\d+)/.test(navigator.userAgent))
    {
        var oprversion = new Number(RegExp.$1)
        tipoBrowser.Tipo = 'opera';
        tipoBrowser.Versao = oprversion;
    }
    return tipoBrowser;
}

Tesla.Utils.setInnerTextObj = function(nomeObj, valor)
{
    /// <summary>
    /// Muda o texto html de determinado objeto - setInnerTextObj('spanObj','<strong>Não</strong>')
    /// </summary>
    /// <param name="nomeObj">Id do objeto</param>
    /// <param name="valor">Texto html</param>
    var objAux = document.getElementById(nomeObj);
    if (objAux != undefined)
    {
        if (document.all)
            objAux.innerText = valor;
        else
            objAux.textContent = valor;
    }
}
Tesla.Utils.getInnerTextObj = function(nomeObj)
{
    /// <summary>
    /// Retorna o texto html de determinado objeto
    /// </summary>
    /// <param name="nomeObj">Id do objeto</param>    
    var objAux = document.getElementById(nomeObj);
    if (objAux != undefined)
    {
        if (document.all)
            return objAux.innerText;
        else
            return objAux.textContent;
    }
}

Tesla.Utils.setInnerHtmlObj = function(nomeObj, valor)
{
    /// <summary>
    /// Muda o texto html de determinado objeto - setInnerTextObj('spanObj','<strong>Não</strong>')
    /// </summary>
    /// <param name="nomeObj">Id do objeto</param>
    /// <param name="valor">Texto html</param>
    var objAux = document.getElementById(nomeObj);
    if (objAux != undefined)
    {   
        objAux.innerHTML = valor;
    }
}
Tesla.Utils.getInnerHtmlObj = function(nomeObj)
{
    /// <summary>
    /// Retorna o texto html de determinado objeto
    /// </summary>
    /// <param name="nomeObj">Id do objeto</param>    
    var objAux = document.getElementById(nomeObj);
    if (objAux != undefined)
    {
        return objAux.innerHTML;
    }
}


Tesla.Utils.setCssName = function(nomeObj, nomeClasse)
{
    /// <summary>
    /// Muda a classe css de determinado objeto - setCssName('spanObj','classNova')
    /// </summary>
    /// <param name="nomeObj">Id do objeto</param>
    /// <param name="nomeClasse">Nome da Classe</param>
    var objAux = document.getElementById(nomeObj);
    if (objAux != undefined)
        objAux.className = nomeClasse;
}

Tesla.Utils.getCssName = function(nomeObj)
{
    /// <summary>
    /// Retorna a classe css de determinado objeto - getCssName('spanObj')
    /// </summary>
    /// <param name="nomeObj">Id do objeto</param>
    var objAux = document.getElementById(nomeObj);
    if (objAux != undefined)
        return objAux.className;
    return '';
}

Tesla.Utils.HabilitaObj = function(nomeObj, habilitar)
{
    /// <summary>
    /// habilita ou desabilita determinado objeto - HabilitaObj('txtBox',false)
    /// </summary>
    /// <param name="nomeObj">Id do objeto</param>
    /// <param name="habilitar">Indica se deve habilitar</param>
    
    var browser = Tesla.Utils.retornaBrowser();

    var objAux = document.getElementById(nomeObj);

    if (browser.Tipo == 'ie' && browser.Versao < 7 && objAux != undefined)
    {
        var strHabilita = '';
        if (habilitar == false)
            strHabilita = 'disabled';
        if (objAux != undefined)
        objAux.disabled = strHabilita;
    }
    else if (objAux != undefined)
        objAux.disabled = !habilitar;
    
    
}

Tesla.Utils.getHabilitado = function(nomeObj)
{
    /// <summary>
    /// habilita ou desabilita determinado objeto - HabilitaObj('txtBox',false)
    /// </summary>
    /// <param name="nomeObj">Id do objeto</param>
    /// <param name="habilitar">Indica se deve habilitar</param>
    var browser = Tesla.Utils.retornaBrowser();

    var objAux = document.getElementById(nomeObj);

    if (objAux != undefined)
        return !objAux.disabled;
    
}

Tesla.Utils.MostraTelaAguarde = function(mostraTela)
{
    /// <summary>
    /// Mostra uma tela de aguarde - MostraTelaAguarde(true)
    /// </summary>
    /// <param name="mostraTela">Indica se deve apresentar a tela</param>
    if (mostraTela)
        Tesla.Utils.MostraObj('divAguarde');
    else
        Tesla.Utils.EscondeObj('divAguarde');
}

Tesla.Utils.FormataBolleano = function(itemBooleano)
{
    /// <summary>
    /// Retorna 'Sim' ou 'Não' conforme item - FormataBolleano(tru)
    /// </summary>
    /// <param name="itemBooleano">Item para comparar</param>

    var isTrue = true;

    if (typeof (itemBooleano) == 'Boolean')
        isTrue = itemBooleano;
    else
    {
        if (itemBooleano == -1)
            return 'Pendente';
        isTrue = (itemBooleano == 1);
    }

    if (isTrue)
        return 'Sim';
    else
        return 'Não';
}

Tesla.Utils.getAtributo = function(nomeObj, nomeAtributo)
{
    /// <summary>
    /// Retorna o valor do atributo de determinado objeto - getAtributo('txtBox','onclick')
    /// </summary>
    /// <param name="nomeObj">Id do objeto</param>
    /// <param name="nomeAtributo">Id do atributo</param>
    var objAux = document.getElementById(nomeObj);
    if (objAux != undefined)
    {
        return objAux.getAttribute(nomeAtributo);
    }
}

Tesla.Utils.setAtributo = function(nomeObj, nomeAtributo, valor)
{
    /// <summary>
    /// Muda o valor do atributo de determinado objeto - setAtributo('txtBox','value','teste')
    /// </summary>
    /// <param name="nomeObj">Id do objeto</param>
    /// <param name="nomeAtributo">Id do atributo</param>
    /// <param name="valor">Valor do atributo</param>
    var objAux = document.getElementById(nomeObj);
    if (objAux != undefined)
    {
        objAux.setAttribute(nomeAtributo, valor);
    }
}

Tesla.Utils.RemoveAtributo = function(nomeObj, nomeAtributo)
{
    /// <summary>
    /// Remove o atributo de determinado objeto - RemoveAtributo('txtBox','onclick')
    /// </summary>
    /// <param name="nomeObj">Id do objeto</param>
    /// <param name="nomeAtributo">Id do atributo</param>
    var objAux = document.getElementById(nomeObj);
    if (objAux != undefined)
    {
        objAux.removeAttribute(nomeAtributo);
    }
}

Tesla.Utils.MostraObj = function(nomeObj)
{
    /// <summary>
    /// Exibe determinado objeto (display='') - MostraObj('txtBox')
    /// </summary>
    /// <param name="nomeObj">Id do objeto</param>
    var objAux = document.getElementById(nomeObj);
    if (objAux != undefined)
        objAux.style.display = '';
}

Tesla.Utils.EscondeObj = function(nomeObj)
{
    /// <summary>
    /// Esconde determinado objeto (display='none') - EscondeObj('txtBox')
    /// </summary>
    /// <param name="nomeObj">Id do objeto</param>
    var objAux = document.getElementById(nomeObj);
    if (objAux != undefined)
        objAux.style.display = 'none';
}

Tesla.Utils.setValorObj = function(nomeObj, valor)
{
    /// <summary>
    /// Muda o valor de determinado objeto - setValorObj('txtBox','ola isso e um teste')
    /// </summary>
    /// <param name="nomeObj">Id do objeto</param>
    /// <param name="valor">Valor</param>
    var objAux = document.getElementById(nomeObj);
    if (objAux != undefined)
        objAux.value = valor;
}


Tesla.Utils.getValorObj = function(nomeObj)
{
    /// <summary>
    /// Retorna o valor de determinado objeto - getValorObj('txtBox')
    /// </summary>
    /// <param name="nomeObj">Id do objeto</param>
    var objAux = document.getElementById(nomeObj);
    if (objAux != undefined)
        return objAux.value;
    return '';
}

Tesla.Utils.setCheckbox = function(nomeObj, valor)
{
    /// <summary>
    /// Muda o status de um checkbox - setCheckbox('chk',true)
    /// </summary>
    /// <param name="nomeObj">Id do objeto</param>
    /// <param name="valor">Valor (true ou false)</param>
    var objAux = document.getElementById(nomeObj);
    if (objAux != undefined)
        objAux.checked = valor;
}

Tesla.Utils.getCheckbox = function(nomeObj)
{
    /// <summary>
    /// Retorna o status de um checkbox - getCheckbox('chk')
    /// </summary>
    /// <param name="nomeObj">Id do objeto</param>
    var objAux = document.getElementById(nomeObj);
    if (objAux != undefined)
        return objAux.checked;
    return false;
}

Tesla.Utils.setFocusNext = function(nextKeyCode, evt, obj, sameTypeOnly)
{
    /// <summary>
    /// setFocusNext - Vai para o proximo tabindex, habilitado - Ex. setFocusNext(13,event,this,false);
    /// <param name="nextKeyCode">O keycode para usar a função, padrão é enter (13)</param>
    /// <param name="evt">Evento do objeto (event) </param>
    /// <param name="obj">objeto atual</param>
    /// <param name="sameTypeOnly">Indica se deve verificar se é do mesmo tipo, padrão é true</param>
    /// </summary>
    
    if (sameTypeOnly == undefined)
        sameTypeOnly == true;
    if (nextKeyCode == undefined || nextKeyCode == '')
        nextKeyCode = 13;

    if (this.getKeyCode(evt) == nextKeyCode)
    {
        //if (obj.value.length < obj.getAttribute('maxlength')) return;

        var lenFor = obj.form.elements.length;
        var tabValor = obj.tabIndex + 1;
        for (var i = 0; i < lenFor; i++)
        {
            var nextEl = obj.form.elements[i];
            if (nextEl &&
                nextEl.tabIndex == tabValor &&
                nextEl.focus &&
                (nextEl.disabled == undefined || nextEl.disabled == false) &&
                (obj.type == nextEl.type || sameTypeOnly==false)
                )
            {
                nextEl.focus();
                return true;
            }
            else if (nextEl &&
                nextEl.tabIndex == tabValor &&
                nextEl.focus &&
                obj.type == nextEl.type)
            {
                tabValor++;
                continue;
            }
        }
    }
    return false;
}

Tesla.Utils.setFocus = function(nomeObj)
{
    /// <summary>
    /// Muda o foco para determinado objeto - setFocus('txtBox')
    /// </summary>
    /// <param name="nomeObj">Id do objeto</param>
    var objAux = document.getElementById(nomeObj);
    if (objAux != undefined && objAux.style.display != 'none' && objAux.disabled == false)
    {
        objAux.focus();
        return true;
    }
    return false;
}

Tesla.Utils.CaracterValidoOuNumero = function(keynum)
{
    /// <summary>
    /// Retorna se é um caracter válido=0 (enter,backspace), numero=1, ou -1 para os demais - if(CaracterValidoOuNumero(8)==0) faz algo
    /// </summary>
    /// <param name="nomeObj">Id do objeto</param>
    
    // é caracter permitido
    if (keynum == 9 || keynum == 8 || keynum == 46 || keynum == 37 || keynum == 39 || keynum == 36 || keynum == 35 || keynum == 44)
        return 0;

    // é numero
    if ((keynum >= 48 && keynum <= 57) || (keynum >= 96 && keynum <= 105))
        return 1;

    // caracter invalido
    return -1;
}

Tesla.Utils.FormataDecimal = function(valor, separadorMilesimo, separadorDecimal, ignoraNegativo,isDig)
{
    /// <summary>
    /// Retorna o valor formatado para decimal BR (1.000,00) - FormataDecimal('340.23')/* retorna */; FormataDecimal('30400') /* retorna 304,00*/;
    /// </summary>
    /// <param name="valor">Valor para ser formatado</param>
    /// <param name="separadorMilesimo">Separador de milesimo, padrão "."</param>
    /// <param name="separadorDecimal">Separador de casas decimais padrão "," </param>
    var sep = 0;
    var key = '';
    var i = j = 0;
    var len = len2 = 0;
    var strCheck = '0123456789';
    var aux = aux2 = '';
    var negativoAux = '';
    
    if (separadorMilesimo == undefined)
        separadorMilesimo = '.';

    if (separadorDecimal == undefined)
        separadorDecimal = ',';

    if (valor == undefined || valor=='')
        return '0' + separadorDecimal + '00';
    else if (ignoraNegativo != undefined && ignoraNegativo == false && valor<0)
        negativoAux = '-';

    if (typeof (valor) != 'String')
        valor = valor.toString();

    valor = valor.toString().replace(/\,/g, '.');
    if (valor.indexOf('.') != -1)
        valor = parseFloat(valor).toFixed(2);
    else if (isDig == undefined || isDig == false)
        valor = parseFloat(valor).toFixed(2);


    len = valor.length;
    for (i = 0; i < len; i++)
        if ((valor.charAt(i) != '0') && (valor.charAt(i) != separadorDecimal))
        break;
    aux = '';
    for (; i < len; i++)
        if (strCheck.indexOf(valor.charAt(i)) != -1)
        aux += valor.charAt(i);
    aux += key;
    len = aux.length;
    if (len == 0)
        valor = '';
    if (len == 1)
        valor = '0' + separadorDecimal + '0' + aux;
    if (len == 2)
        valor = '0' + separadorDecimal + aux;
    if (len > 2)
    {
        aux2 = '';
        for (j = 0, i = len - 3; i >= 0; i--)
        {
            if (j == 3)
            {
                aux2 += separadorMilesimo;
                j = 0;
            }
            aux2 += aux.charAt(i);
            j++;
        }
        valor = '';
        len2 = aux2.length;
        for (i = len2 - 1; i >= 0; i--)
            valor += aux2.charAt(i);
        valor += separadorDecimal + aux.substr(len - 2, len);
    }
    return negativoAux + valor;

}

Tesla.Utils.preventDefault = function(e)
{
    if (e.preventDefault)
    { //standart browsers
        e.preventDefault()
    } else
    { // internet explorer
        e.returnValue = false
    }
}

Tesla.Utils.FormataReais = function(fld, milSep, decSep, e)
{
    /// <summary>
    /// Retorna o valor formatado para valor monetario BR (R$ 1.000,00) 
    /// </summary>
    /// <param name="fld">Objeto para ser formatado</param>
    /// <param name="milSep">Separador de milesimo</param>
    /// <param name="decSep">Separador de casas decimais </param>
    /// <param name="e">evento </param>

    var sep = 0;
    var key = '';
    var i = j = 0;
    var len = len2 = 0;
    var strCheck = '0123456789';
    var aux = aux2 = '';
    var whichCode = this.getKeyCode(e); //(window.Event) ? e.which : e.keyCode;
    var idFld = fld.id;
    if (whichCode == 13) return true;
    if (whichCode == 8)
    {
        this.preventDefault(e);
        var novoVal = fld.value.substring(0, fld.value.length - 1);
        this.setValorObj(idFld, novoVal);
        return false;
    }
    else if (whichCode == 9)
    {
        return true;
    }
    else if (this.VerificaNumero(e) == false)
    {
        if (this.CaracterValidoOuNumero(whichCode) != -1)
            return true;
        this.preventDefault(e);
        return true;
    }
    else
    {
        this.preventDefault(e);
        key = String.fromCharCode(whichCode);  // Valor para o código da Chave
        var novoVal = fld.value;
        novoVal = novoVal.toString().replace(/\,/g, '');
        novoVal = novoVal.toString().replace(/\./g, '');
        novoVal = novoVal + key;
        this.setValorObj(idFld, this.FormataDecimal(novoVal, milSep, decSep, true, true));
    }

    return true;
}

Tesla.Utils.getKeyCode = function(evt)
{
    /// <summary>
    /// retorna o keycode a partir do evento
    /// </summary>
    /// <param name="evt">evento </param>
    var keynum ;//= evt.charCode || evt.keyCode || evt.which;
    if (window.event) // IE
    {
        keynum = evt.keyCode;
    }
    else  // Netscape/Firefox/Opera
    {
        keynum = evt.charCode || evt.keyCode || evt.which;
    }
    return keynum;
}

Tesla.Utils.VerificaNumero = function(evt)
{
    /// <summary>
    /// Valida se é numero, do contrário não permitte a inserção do caractere a partir do evento
    /// </summary>
    /// <param name="evt">evento</param>
    var keynum = this.getKeyCode(evt);

    //if (keynum == 9 || keynum == 8 || keynum == 46 || keynum == 37 || keynum == 39 || keynum == 36 || keynum == 35 || keynum == 44)
    switch (this.CaracterValidoOuNumero(keynum))
    {
        case 0: return false; break;
        case 1: return true; break;
        default:
            if (evt.preventDefault)
                evt.preventDefault();
            else
                evt.returnValue = false;

            return false;
            break;
    }
}

Tesla.Utils.ValidaFormatoData = function(dataValor)
{
    /// <summary>
    /// Valida se a data está no formato correto - ValidaFormatoData('10/10/1987')
    /// </summary>
    /// <param name="dataValor">Valor da data</param>

    var dataArray = dataValor.split('/');

    if (dataArray.length < 3 || dataArray.length > 3)
        return false;

    if (dataArray[0] > 31)
        return false;
    if (dataArray[1] > 12)
        return false;
    if (dataArray[2] < 1900 || dataArray[2] > 9999)
        return false;

    return true;
}

Tesla.Utils.ComparaData = function(dataValorIni, dataValorFim)
{
    /// <summary>
    /// Compara duas datas no formato dd/mm/yyyyy
    /// </summary>
    /// <param name="dataValor">Valor da data</param>
    if (this.ValidaFormatoData(dataValorIni) && this.ValidaFormatoData(dataValorFim))
    {
        var dataArrayIni = dataValorIni.split('/');
        var dataArrayFim = dataValorFim.split('/');
        var dateIni = new Date();
        var dateFim = new Date();


        dateIni.setDate(dataArrayIni[0]);
        dateIni.setMonth(dataArrayIni[1] - 1);
        dateIni.setFullYear(dataArrayIni[2]);

        dateFim.setDate(dataArrayFim[0]);
        dateFim.setMonth(dataArrayFim[1] - 1);
        dateFim.setFullYear(dataArrayFim[2]);

        var um_dia = 1000 * 60 * 60 * 24; // em milisegundos
        return Math.ceil((dateFim.getTime() - dateIni.getTime()) / (um_dia));
    }
    return -999;
}

Tesla.Utils.RetornaChar = function(keynum)
{
    /// <summary>
    /// Retorna o caracter a partir do keycode - RetornaChar(96)
    /// </summary>
    /// <param name="keynum">KeyCode </param>
    var strVal = '';
    switch (keynum)
    {
        case 96: strVal = '0'; break;
        case 97: strVal = '1'; break;
        case 98: strVal = '2'; break;
        case 99: strVal = '3'; break;
        case 100: strVal = '4'; break;
        case 101: strVal = '5'; break;
        case 102: strVal = '6'; break;
        case 103: strVal = '7'; break;
        case 104: strVal = '8'; break;
        case 105: strVal = '9'; break;
        default: strVal = String.fromCharCode(keynum); break;
    }
    return strVal;
}

Tesla.Utils.Trim = function(str) { return str.replace(/^\s+|\s+$/g, ""); }


Tesla.Utils.FormataDataObj = function(objData, tipoData)
{
    /// <summary>
    /// Formata a data de um input para o padrão dd/mm/yyyy - MascaraData(objData,event,'txtBox,TxtBox1') vai tentar ir para txtbox,se não existir no contexto, vai para o proximo
    /// </summary>
    /// <param name="obj">Objeto</param>
    /// <param name="evt">Evento</param>
    /// <param name="nomeObjetos">objetos que deseje setar o foco quando finalizar a formatação</param>

    if (objData == null || objData == undefined)
        return '&nbsp;-&nbsp;';
    //return '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;-&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;';
    //return '&nbsp;';

    if (tipoData == 1)
        return objData.format("dd/mm/yyyy HH:MM")
    else
        return objData.ToString("dd/MM/yyyy")
    //.ToString("dd/MM/yyyy HH:mm")

}
Tesla.Utils.FormataObjVazio = function(objString)
{
    /// <summary>
    /// Formata o valor do objeto, caso seja vazio retorna " - "
    /// </summary>
    /// <param name="objString">String para ser formatada</param>
    
    if (objString == null || objString == undefined)
        return '&nbsp;-&nbsp;';
        //return '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;-&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;';

    var valor = Tesla.Utils.Trim(objString.ToString());
    if (valor.length == 0)
        return '&nbsp;-&nbsp;';
        //return '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;-&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;';

    valor = valor.replace(' ', '&nbsp;');
    return valor;
}

Tesla.Utils.MascaraData = function(obj, evt, nomeObjetos)
{
    /// <summary>
    /// Formata a data de um input para o padrão dd/mm/yyyy - MascaraData(objData,event,'txtBox,TxtBox1') vai tentar ir para txtbox,se não existir no contexto, vai para o proximo
    /// </summary>
    /// <param name="obj">Objeto</param>
    /// <param name="evt">Evento</param>
    /// <param name="nomeObjetos">objetos que deseje setar o foco quando finalizar a formatação</param>
    
    var keynum = this.getKeyCode(evt);

    if (Tesla.Utils.VerificaNumero(evt))
    {
        if (obj.value.length == 2 && keynum != 8)
            obj.value = obj.value + "/";
        if (obj.value.length == 5 && keynum != 8)
            obj.value = obj.value + "/";


        if (obj.value.length >= 9 && keynum != 8)
        {

            var strNomeObj = new Array();

            if (nomeObjetos != undefined && nomeObjetos.length > 0)
                strNomeObj = nomeObjetos.split(',');

            obj.value = obj.value + this.RetornaChar(keynum);
            var browser = this.retornaBrowser();
            if (browser.Tipo == 'ie')
            {
                evt.returnValue = false;
            }
            else
            {
                evt.stopPropagation();
                evt.preventDefault();
            }

            obj.value = obj.value.slice(0, 10);

            if (!this.ValidaFormatoData(obj.value))
            {
                alert('Data no formato invalido. Informar data no formato dd/mm/aaaa. ex. 22/03/2000');
                return;
            }
            if (nomeObjetos.length > 0)
            {
                for (var i = 0; i < strNomeObj.length; i++)
                {
                    if (!this.setFocus(strNomeObj[i]))
                    {
                        continue;
                    }
                    this.setValorObj(strNomeObj[i], "");
                }

            }

        }
    }
}

Tesla.Utils.ExisteBackup = function(objBkp)
{
    /// <summary>
    /// Informa se determinado parametro está backup (memória) - ExisteBackup('onclick_TextBox') 
    /// </summary>
    /// <param name="nomeBackup">Id do parametro </param>

    if (this.BackupComandos == undefined)
        this.BackupComandos = new Array();

    for (var i = 0; i < this.BackupComandos.length; i++)
    {
        if (this.BackupComandos[i].Nome == objBkp.Nome)
            return true;
    }
    return false;
}

Tesla.Utils.getBackup = function(nomeBackup)
{
    /// <summary>
    /// Retorna o valor de um parametro no backup (memória) - getBackup('onclick_TextBox') 
    /// </summary>
    /// <param name="nomeBackup">Id do parametro </param>
    var tamBackup = this.BackupComandos.length;
    for (var i = 0; i < tamBackup; i++)
    {
        if (this.BackupComandos[i].Nome == nomeBackup)
            return this.BackupComandos[i].Valor;
    }
    return '';
}

Tesla.Utils.AddBackup = function(valores, chrDelimitador)
{
    /// <summary>
    /// Adiciona um item backup (memória) - AddBackup('onclick_TextBox:valor',':') 
    /// </summary>
    /// <param name="valores">String delimitada "nomeparametro:valor" </param>
    /// <param name="chrDelimitador">Delimitador da string</param>
    var novoBackup = { Nome: 0, Valor: 0 };
    novoBackup.Nome = valores.toString().split(chrDelimitador)[0];
    novoBackup.Valor = valores.toString().split(chrDelimitador)[1];

    if (!this.ExisteBackup(novoBackup))
        this.BackupComandos.push(novoBackup);
}

Tesla.Utils.RemoveBackup = function(nomeBackup)
{
    /// <summary>
    /// Remove um item backup (memória) - RemoveBackup('onclick_TextBox') 
    /// </summary>
    /// <param name="nomeBackup">Id do parametro </param>
    var arrAux = new Array();
    var tamBackup = this.BackupComandos.length;
    for (var i = 0; i < tamBackup; i++)
    {
        if (this.BackupComandos[i].Nome == nomeBackup)
            continue;
        arrAux.push(this.BackupComandos[i]);
    }
    this.BackupComandos = arrAux;
}

Tesla.Utils.LimpaComboBox = function(nomeObj)
{
    /// <summary>
    /// Limpa um objeto select (html) 
    /// </summary>
    /// <param name="nomeObj">Id do objeto </param>
    var objAux = document.getElementById(nomeObj);
    if (objAux != undefined)
    {
        objAux.options.length = 0;
    }
}
Tesla.Utils.AddComboOption = function(nomeObj, texto, valor, selecionado, padrao)
{
    /// <summary>
    /// Adiciona um optiona em um objeto select (html) 
    /// </summary>
    /// <param name="nomeObj">Id do objeto </param>
    /// <param name="texto">texto do option </param>
    /// <param name="valor">Valor do option </param>
    /// <param name="selecionado">Se estará selecionado </param>
    /// <param name="selecionado">indica se é option padrão </param>
    var objAux = document.getElementById(nomeObj);
    if (objAux != undefined)
    {
        var novaOpcao = new Option(texto, valor, selecionado, padrao);
        objAux.options[objAux.options.length] = novaOpcao;
    }
}

Tesla.Utils.GeraGuid = function()
{
    /// <summary>
    /// retorna um guid
    /// </summary>
    var result, i, j;
    result = '';
    for (j = 0; j < 32; j++)
    {
        if (j == 8 || j == 12 || j == 16 || j == 20)
            result = result + '-';
        i = Math.floor(Math.random() * 16).toString(16).toUpperCase();
        result = result + i;
    }
    return result
}

var oLastBtn = 0;

bIsMenu = false;


/*
if (window.Event)
    document.captureEvents(Event.MOUSEUP);

document.oncontextmenu = nocontextmenu;

document.onmousedown = norightclick;

*/

Tesla.Utils.nocontextmenu = function()
{
    /// <summary>
    /// nocontextmenu - desabilita o menu de contexto
    /// </summary>
    event.cancelBubble = true

    event.returnValue = false;

    return false;

}

Tesla.Utils.norightclick = function(e)
{
    /// <summary>
    /// norightclick - Bloqueia o uso do botao direito no browser
    /// <param name="e">evento </param>
    /// </summary>
    if (window.Event)
    {

        if (e.which != 1)

            return false;

    }

    else

        if (event.button != 1)
    {

        event.cancelBubble = true

        event.returnValue = false;

        return false;

    }

}
Tesla.Utils.BloqueiaRetornoBrowser = function()
{
    /// <summary>
    /// BloqueiaRetornoBrowser - Bloqueia o retorno pelo backspace
    /// </summary>
    var numKeyCode = this.getKeyCode(event);
    
    //(event.altKey) ||
    
    if ( ((numKeyCode == 8) &&

                           (event.srcElement.type != "text" &&

                            event.srcElement.type != "textarea" &&

                            event.srcElement.type != "password"))
                            )                            
    {

        event.keyCode = 0;

        event.returnValue = false;

    }

}

Tesla.Utils.BloqueiaF5 = function()
{
    /// <summary>
    /// BloqueiaF5 - Bloqueia o uso de F5
    /// </summary>
    var numKeyCode = this.getKeyCode(event);

    if (
        (
            (event.ctrlKey) &&
            (
                (event.keyCode == 78) || (event.keyCode == 82)
            )
         ) ||
            (event.keyCode == 116)
         )
    {

        event.keyCode = 0;

        event.returnValue = false;

    }

}


Tesla.Utils.Ajax = function() {

    this.request = null;
    this.url = '';
    this.metodo = Tesla.Utils.Enums.RequestType.GET;
    this.dados = '';
    this.tipoDados = Tesla.Utils.Enums.ResponseType.JSON;
    this.callBackFunction = null;
    this.CreateXMLHttpRequest = function() {
        /* Does this browser support the XMLHttpRequest object? */
        if (window.XMLHttpRequest) {
            if (typeof XMLHttpRequest != 'undefined')
                try {
                this.request = new XMLHttpRequest();
            } catch (e) {
                this.request = false;
            }
        }
        else if (window.ActiveXObject) {
            try {
                this.request = new ActiveXObject('Msxml2.XMLHTTP');
            } catch (e) {
                try {
                    this.request = new ActiveXObject('Microsoft.XMLHTTP');
                } catch (e) {
                    this.request = false;
                }
            }
        }
    }

    this.onreadyFuncResponse = function() {
        this.request = this;
        //var List = eval(objList);
        var AjaxObj = this;
        if (this.request.readyState == 4) {
            if (this.request.status == 200) {
                var RetornoDados = '';

                // XML
                if (AjaxObj.tipoDados == Tesla.Utils.Enums.ResponseType.XML) {
                    var xmlString = this.request.responseText;
                    var response = null;

                    if (window.ActiveXObject) {
                        response = new ActiveXObject('Microsoft.XMLDOM');
                        response.async = false;
                    } else if (document.implementation &&
                document.implementation.createDocument)
                        response = document.implementation.createDocument('', '', null);

                    response.loadXML(xmlString);
                    RetornoDados = response;
                }
                else if (AjaxObj.tipoDados == Tesla.Utils.Enums.ResponseType.JSON) {
                    var jsonString = this.request.responseText;
                    RetornoDados = eval('(' + jsonString + ')');
                }
                else
                    RetornoDados = this.request.responseText;

                // executa o callback
                if (AjaxObj.callBackFunction != undefined)
                    AjaxObj.callBackFunction(RetornoDados);


            } else
                alert('Erro ao retornar os dados: \n' +
                this.request.statusText);
            this.request = null;
        }
    }



    this.RequestData = function(p_dados, p_url, p_callback, p_onreadyFunc, p_metodo) {

        if (this.request == null || this.request == undefined)
            this.CreateXMLHttpRequest();

        if (p_metodo != undefined && p_metodo != null)
            this.metodo = p_metodo;

        if (p_url != undefined && p_url != null)
            this.url = p_url;

        if (p_dados != undefined && p_dados != null)
            this.dados = p_dados;

        if (this.request) {

            if (p_callback != undefined)
                this.callBackFunction = p_callback;

            this.request.tipoDados = this.tipoDados;
            this.request.callBackFunction = this.callBackFunction;

            if (this.metodo == Tesla.Utils.Enums.RequestType.GET)
                this.request.open('GET', this.url + '?' + this.dados, true);
            else
                this.request.open('POST', this.url, true)

            if (this.tipoDados == Tesla.Utils.Enums.ResponseType.JSON) {
                this.request.setRequestHeader('Content-Type', 'text/json');
                this.request.setRequestHeader('encoding', 'ISO-8859-1');
            }
            else if (this.tipoDados == Tesla.Utils.Enums.ResponseType.XML) {
                this.request.setRequestHeader('Content-Type', 'text/xml');
                this.request.setRequestHeader('encoding', 'ISO-8859-1');
            }
            else {
                this.request.setRequestHeader('Content-Type', 'text/html');
                this.request.setRequestHeader('encoding', 'ISO-8859-1');
            }
            var objList = '[{tipoDados:' + this.tipoDados + ',callBackFunction:' + this.callBackFunction + '}]';

            if (p_onreadyFunc != undefined && p_onreadyFunc != null)
                this.request.onreadystatechange = p_onreadyFunc;
            else {
                this.request.onreadystatechange = this.onreadyFuncResponse;

            }

            if (this.metodo == Tesla.Utils.Enums.RequestType.GET)
                this.request.send();
            else
                this.request.send(this.dados);

        }
    }
    return this;
}

Tesla.Utils.JsRepeater = function(nameRpt, execContructor) {
    /// <summary>
    /// Gera um objeto do tipo repeater em javascript
    /// </summary>
    /// <param name="nomeRpt">Id do objeto</param>

    this.name = nameRpt;
    this.Html = Tesla.Utils.getInnerHtmlObj(this.name);
    /*
    if (this.Html.slice(0, 4) == '<!--') {
        this.Html = this.Html.slice(4, this.Html.length);
        this.Html = this.Html.slice(0, this.Html.length - 3);
    }*/
    this.HeaderTagIni = '<!--<header>-->';
    this.HeaderTagEnd = '<!--</header>-->';
    this.FooterTagIni = '<!--<footer>-->';
    this.FooterTagEnd = '<!--</footer>-->';
    this.ItemTemplateTagIni = '<!--<item>-->';
    this.ItemTemplateTagEnd = '<!--</item>-->';
    this.IndicatorIni = "(%";
    this.IndicatorEnd = "%)";
    this.Header = null;
    this.Footer = null;
    this.ItemTemplate = null;

    this.BindTemplate = function(template, DataItem) {
        /// <summary>
        /// Efetua o bind, ou seja executa todo o conteudo e retorna o resultado
        /// </summary>
        /// <param name="template">string contendo o template para ser executado</param>
        /// <param name="DataItem">Item, para o caso de utilização de Array </param>
        if (template == null)
            return '';
        else
            template = unescape(template);
        if (DataItem == null)
            DataItem = '';

        var rt = '';
        var idx = 0;
        for (var i = 0; i < template.length; i++) {
            i = template.indexOf(this.IndicatorIni, i);
            if (i < 0) {
                rt += template.substring(idx, template.length);
                break;
            }
            rt += template.slice(idx, i);
            rt += eval(template.slice(i + this.IndicatorIni.length, template.indexOf(this.IndicatorEnd, i)));
            i = idx = (template.indexOf(this.IndicatorEnd, i) + this.IndicatorEnd.length);
        }
        return rt;
    }

    this.Bind = function(DataList) {
        /// <summary>
        /// Executa o repeater, conforme o que existir em cada template
        /// </summary>
        /// <param name="DataList">Array contendo os itens</param>
        var lenFor = DataList.length;
        var htmlItem = this.BindTemplate(this.Header); ;
        Tesla.Utils.EscondeObj(this.name);

        for (var i = 0; i < lenFor; i++) {
            htmlItem += this.BindTemplate(this.ItemTemplate, DataList[i]);
        }
        htmlItem += this.BindTemplate(this.Footer);
        Tesla.Utils.setInnerHtmlObj(this.name, htmlItem);
        Tesla.Utils.MostraObj(this.name);
    }

    this.ReturnTemplate = function(templateTagIni, templateTagEnd, value) {
        /// <summary>
        /// Retorna o conteudo do template informado atraves das tags
        /// </summary>
        /// <param name="templateTagIni">Tag Inicial, ex. <header></param>
        /// <param name="templateTagEnd">Tag Final, ex. </header></param>
        /// <param name="value">html contendo os valores da tag</header></param>

        var tagIniSize = templateTagIni.length;
        var tagEndSize = templateTagEnd.length;

        var idxIni = value.toLowerCase().indexOf(templateTagIni.toLowerCase(), 0);
        if (idxIni < 0)
            return '';
        var idxEnd = value.toLowerCase().indexOf(templateTagEnd.toLowerCase(), idxIni);
        if (idxEnd < 0)
            return '';
        var retVal = value.slice((idxIni + tagIniSize), (idxEnd));
        return retVal;
    }
    this.Clear = function() {
        /// <summary>
        /// Limpa o conteudo do repeater
        /// </summary>
        Tesla.Utils.setInnerHtmlObj(this.name, '');
    }

    this.InitTemplates = function() {
        /// <summary>
        /// Efetua a captura dos templates, deve ser executado antes do Bind()
        /// </summary>

        this.Header = this.ReturnTemplate(this.HeaderTagIni, this.HeaderTagEnd, this.Html);
        this.Footer = this.ReturnTemplate(this.FooterTagIni, this.FooterTagEnd, this.Html);
        this.ItemTemplate = this.ReturnTemplate(this.ItemTemplateTagIni, this.ItemTemplateTagEnd, this.Html);
    }

    if (execContructor == undefined || execContructor == true)
        this.InitTemplates();

    return this;

}

Function.prototype.GetName = function() {
    if (this.name)
        return this.name;
    var fn = this.toString();

    if (fn == '[function]') {
        var cn = this;
        if (cn == String)
            this.name = 'String';
        else if (cn == Number)
            this.name = 'Number';
        else if (cn == Function)
            this.name = 'Function';
        else if (cn == Date)
            this.name = 'Date';
        else if (cn == Error)
            this.name = 'Error';
        else if (cn == Boolean)
            this.name = 'Boolean';
        else if (cn == Array)
            this.name = 'Array';
        else
            this.name = 'Object';
        return this.name;
    }
    var start = fn.indexOf('function') + 9;
    for (; fn.charAt(start) == ' '; )
        start++;
    var end = start;
    while (fn.charAt(end) != ' ' && fn.charAt(end) != '(')
        end++;
    this.name = fn.substring(start, end)
    return this.name;
}


Tesla.Utils.resetMedidorSenha = function(div, table)
{
    document.getElementById(table).style.width = "0px";
    document.getElementById(div).innerHTML = '';
}


Tesla.Utils.validaSenha = function(senha, div, table, tamanho)
{
    var intScore = 0;
    var strVerdict = "Fraca";
    if (senha.length < 8)
    {
        alert('A senha deve possuir no mínimo 8 e no máximo 20 caracteres.');
        return false;
    }
    else if (senha.length >= 8 && senha.length < tamanho)
    {
        //DEFINE SCORE INICIAL
        intScore = 5;

        // LETRAS
        if (senha.match(/[a-z]/))
        {
            intScore = (intScore + 7);
        }

        // LETRAS MAIUSCULAS
        if (senha.match(/[A-Z]/))
        {
            intScore = (intScore + 7);
        }

        // NUMEROS
        if (senha.match(/\d+/))
        {
            intScore = (intScore + 7);
        }
        
        // CARACTERES ESPECIAIS
        if (senha.match(/.[!,@,#,$,%,^,&,*,?,_,]/))
        {
            intScore = (intScore+7);
        }
    }

    // TAMANHO MAIOR que tamanho
    else if (senha.length >= tamanho)
    {
        alert('O campo de senha não pode ultrapassar ' + tamanho + ' caracteres.');
        return false;
    }

    // ACENTUAÇÃO
    if (senha.match(/.[~,´,',`,^,<,>, ,]/))
    {
        alert('O campo de senha não pode possuir caracteres com acentuação.');
        return false;
    }


    if (senha == '')
    {
        alert('A senha deve conter letras maiúsculas, minúsculas, números e caracteres especiais. Use ao menos 3 desses 4 tipos de caracteres');
        return false;
        //strVerdict = "Fraca"
        //document.getElementById(table).style.width = "0px";
    }
    else if (intScore < 15)
    {
        alert('A senha deve conter letras maiúsculas, minúsculas, números e caracteres especiais. Use ao menos 3 desses 4 tipos de caracteres');
        return false;
        //strVerdict = "Fraca"
        ///document.getElementById(table).style.width = "10px";
    }
    else if (intScore >= 15 && intScore < 25)
    {
        alert('A senha deve conter letras maiúsculas, minúsculas, números e caracteres especiais. Use ao menos 3 desses 4 tipos de caracteres');
        return false;
        //strVerdict = "Média"
        //document.getElementById(table).style.width = "50px";
    }
    else if (intScore >= 25)
    {
        return true;
        //strVerdict = "Forte"
        //document.getElementById(table).style.width = "98px";
    }


    document.getElementById(div).innerHTML = strVerdict;

}


Tesla.Utils.post_to_url = function(path, params, method) {
    method = method || "post"; // Set method to post by default, if not specified.
    
    // The rest of this code assumes you are not using a library.
    // It can be made less wordy if you use one.
    var form = document.createElement("form");
    form.setAttribute("method", method);
    form.setAttribute("action", path);

    for (var i = 0; i < params.length; i++) {
        var hiddenField = document.createElement("input");
        hiddenField.setAttribute("type", "hidden");
        hiddenField.setAttribute("name", params[i].name);
        hiddenField.setAttribute("value", params[i].value);

        form.appendChild(hiddenField);
    }

    document.body.appendChild(form);    // Not entirely sure if this is necessary
    form.submit();
}

/*************************************************************************************************************************
* ******************************   Fim - Biblioteca Uteis     ************************************************************
* ************************************************************************************************************************/


