﻿//Abre uma janela HTML
function openWebWindow(id, title, url, modal, params, executeOnClose) {
    var window;

    if (modal == false) {
        window = document.getElementById(id);

        if (window) {
            if (window.isClosed == false) {
                window.show();
                return window;
            }
        }
        return dhtmlwindow.open(id, "iframe", url, title, params, "recal", executeOnClose);
    } else {
        return dhtmlmodal.open(id, "iframe", url, title, params, "recal", executeOnClose);
    }
}

function openWebWindow2(id, title, url, modal, width, height, resize) {
    if (modal == false) {
        hs.htmlExpand(id, null, { objectType: 'iframe', outlineType: 'rounded-white',
            outlineWhileAnimating: true, preserveContent: false, width: width, height: height,
            minWidth: width, minHeight: height, headingText: title, src: url
        });
    } else {
        hs.htmlExpand(id, null, { objectType: 'iframe', outlineType: 'rounded-white',
            outlineWhileAnimating: true, preserveContent: false, width: width, height: height,
            minWidth: width, minHeight: height, headingText: title, src: url
        });
    }
}

//Abre uma nova janela do browser
function openBrowserWindow(url, title, modal, height, width, center, resize, scroll) {
    var params;

    if (modal == false) {
        params = "height=" + height + "px,width=" + width + "px,resizable=" + (resize ? "yes" : "no") +
        ",scrollbars=" + (scroll ? "yes" : "no") + ",status=no,toolbar=no,menubar=no,location=no";


        return window.open(url, null, params);
    } else {
        if (isInternetExplorer()) {
            /*params = "status:no;dialogHeight:" + height + "px;dialogWidth:" + width + "px;center:" +
            (center ? "yes" : "no") + ";resizable:" + (resize ? "yes" : "no") + ";scroll:" + (scroll ? "yes" : "no");
            
            return window.showModalDialog(url, null, params);*/

            params = "height=" + height + "px,width=" + width + "px,resizable=" + (resize ? "yes" : "no") +
           ",scrollbars=" + (scroll ? "yes" : "no") + ",status=no,toolbar=no,menubar=no,location=no";

            return window.open(url, null, params);
        } else {
            params = "height=" + height + "px,width=" + width + "px,resizable=" + (resize ? "yes" : "no") +
           ",scrollbars=" + (scroll ? "yes" : "no") + ",status=no,toolbar=no,menubar=no,location=no";

            try {
                netscape.security.PrivilegeManager.enablePrivilege('UniversalBrowserWrite');
                return window.open(url, null, params + ',modal=yes');
            } catch (e) {
                return window.open(url, null, params);
            }
        }
    }
}

//Abre uma janela nova janela
//Type=1: abre uma janela HTML
//Type=2: abre uma janela do browser
function openWindow(type, id, title, url, modal, height, width, center, resize, scroll, executeOnClose) {
    var params;

    if (type == 1) {
        /*params = "height=" + height + "px,width=" + width + "px,center=" + 
        (center ? "1" : "0") + ",resize=" + (resize ? "1" : "0") + ",scrolling=" + (scroll ? "1" : "0");
         
        return openWebWindow(id, title, url, modal, params, executeOnClose);*/

        return openWebWindow2(id, title, url, modal, width, height, resize);
    } else {
        return openBrowserWindow(url, title, modal, height, width, center, resize, scroll);
    }
}

//Fecha a janela HTML em que a página está contida
function closeWebWindow(id) {
    parent.closeHighSlideWindow(id);
    //parent.document.getElementById(id).close();
}

//Retorna se o browser é o IE
function isInternetExplorer(){
    if(navigator.appName.indexOf("Microsoft") >= 0){
        return true;
    }else{
      return false;
    }
}

//Muda o estilo do botao
function iconeOver(id, tipoEvento) {            
   var div = document.getElementById('ico_' + id);
   var label = document.getElementById('label_' + id);
   if (tipoEvento == 'over') {
       div.className = 'div_icone_over';                
       label.className = 'div_label_over';
   } else {
       div.className = 'div_icone';
       label.className = 'div_label';
   }
}

//Irá finalizar a sessão após 5 minutos, caso não haja mais nenhuma atividade
function finalizaSessao(){
   var oAjax = new retObjAjax();

   oAjax.onreadystatechange = function(){
      if(oAjax.readyState == 4){ //Status igual a 4 significa que o servidor fez o seu trabalho e enviou a resposta final
         //Não faz nada
      }
    }
    
    try {
        var vsKey = $get('__VIEWSTATE_KEY');
        oAjax.open("GET", getHost() + "FinalizaSessao.ashx?type=session" + (vsKey?'&vskey=' + vsKey.value:''), true);
        oAjax.setRequestHeader("Cache-Control", "no-store, no-cache, must-revalidate");
        oAjax.setRequestHeader("Cache-Control", "post-check=0, pre-check=0");
        oAjax.setRequestHeader("Pragma", "no-cache");
        oAjax.setRequestHeader("Content-Type", "application/x-www-form-urlencoded;");
        oAjax.send(null);
    } catch (e) {
        throw e;
    } finally {
        return true;
    }
}

//Desconecta o chat
function finalizaChat(){
   var oAjax = new retObjAjax();

   oAjax.onreadystatechange = function(){
      if(oAjax.readyState == 4){ //Status igual a 4 significa que o servidor fez o seu trabalho e enviou a resposta final
         //Não faz nada
      }
    }
    
    try {
        oAjax.open("GET", getHost() + "FinalizaSessao.ashx?type=chat", true);
        oAjax.setRequestHeader("Cache-Control", "no-store, no-cache, must-revalidate");
        oAjax.setRequestHeader("Cache-Control", "post-check=0, pre-check=0");
        oAjax.setRequestHeader("Pragma", "no-cache");
        oAjax.setRequestHeader("Content-Type", "application/x-www-form-urlencoded;");
        oAjax.send(null);
    } catch (e) {
        throw e;
    } finally {
        return true;
    }
}

//Retorna um objeto XMLHttpRequest
function retObjAjax() {
    var req;

    if (window.ActiveXObject) { // Versão ActiveX
        try { 
            req = new ActiveXObject("Microsoft.XMLHTTP");  // IE
        } catch(e) {
            req = new ActiveXObject("Msxml2.XMLHTTP"); // IE 7 ?
        }
    }
    else if (window.XMLHttpRequest) { // Objeto do Windows
        try {
            req = new XMLHttpRequest(); // Firefox, Safari, Opera, etc
            req.overrideMimeType("text/xml");
        } catch(e) {
            alert("Ocorreu um erro!\nDescrição:\n\n" + e.message);
            return false;
        }
    }

    if (!req) {
        alert("Seu navegador não oferece recursos para esta página!");
        return false;
    }
    
    return req;
}

//Retorna o endereço da página
function getHost() {
   var url = window.location.href;
   var nohttp = url.split('//');
   var hostPort;
   
   if(nohttp.length == 1)
      hostPort = nohttp[0];
   else
      hostPort = nohttp[1];
   
   if(hostPort.toLowerCase().lastIndexOf('/spalu/') > 0)
      hostPort = hostPort.substring(0, hostPort.toLowerCase().lastIndexOf('/spalu/'));
   else if(hostPort.toLowerCase().lastIndexOf('/sppro/') > 0)
      hostPort = hostPort.substring(0, hostPort.toLowerCase().lastIndexOf('/sppro/'));
   else if(hostPort.toLowerCase().lastIndexOf('/spfin/') > 0)
      hostPort = hostPort.substring(0, hostPort.toLowerCase().lastIndexOf('/spfin/'));
   else if(hostPort.toLowerCase().lastIndexOf('/spger/') > 0)
      hostPort = hostPort.substring(0, hostPort.toLowerCase().lastIndexOf('/spger/'));
   else
      hostPort = hostPort.substring(0, hostPort.lastIndexOf('/'));
   
   return 'http://' + hostPort + '/';
}
   
function showPopup(behaviorID){
   var popup = $find(behaviorID);
   
   if(popup != null)
      popup.show();
}

function hidePopup(behaviorID){
   var popup = $find(behaviorID);
   
   if(popup != null)
      popup.hide();
}

function getDropDownSelectedValue(id){
   var ret = null;
   var selectListID = document.getElementById(id);
   
   for (var i = 0; i < selectListID.options.length; i++) {
      var curOption = selectListID.options[i];

      if (curOption.selected) {
         ret = curOption.value;
         break;
      }
   }
   
   return ret;
}

function clickButton(b) {
    if (b.dispatchEvent)
    {
        var e = document.createEvent('MouseEvents');
        e.initEvent('click', true, true);
        b.dispatchEvent(e);
    }
    else
    {
        b.click();
    }
}

function retTotalRecebimentos(grid, label){
   var total = 0;
   
   for(i=2;i<=document.getElementById(grid).rows.length;i++){
      total = total + parseFloat(document.getElementById(grid + '_ctl' + i.zeroFormat(2, true, false) + '_txtValor').value.replace(',', '.'));
   }
   
   document.getElementById(label).innerHTML = 'R$ ' + total.toFixed(2).replace('.', ',');
}

function retTotalParcelas(grid, label, pagar){
   var total = 0;
   var valor = 0;
   var base = pagar ? -1 : 0;
   
   for(i=2;i<=document.getElementById(grid).rows.length;i++){
      if(isInternetExplorer()){
         valor = parseFloat(document.getElementById(grid).childNodes[0].childNodes[i - 1].childNodes[base + 2].innerHTML.replace(',', '.'));
      }else{
         valor = parseFloat(document.getElementById(grid).childNodes[1].childNodes[i - 1].childNodes[base + 3].innerHTML.replace(',', '.'));
      }
      valor = valor + parseFloat(document.getElementById(grid + '_ctl' + i.zeroFormat(2, true, false) + '_txtJuros').value.replace(',', '.'));
      valor = valor - parseFloat(document.getElementById(grid + '_ctl' + i.zeroFormat(2, true, false) + '_txtDesconto').value.replace(',', '.'));
      
      if(isInternetExplorer()){
         document.getElementById(grid).childNodes[0].childNodes[i - 1].childNodes[base + 6].innerHTML = valor.toFixed(2).replace('.', ',');
      }else{
         document.getElementById(grid).childNodes[1].childNodes[i - 1].childNodes[base + 7].innerHTML = valor.toFixed(2).replace('.', ',');
      }
      
      total = total + valor;
   }
   
   document.getElementById(label).innerHTML = 'R$ ' + total.toFixed(2).replace('.', ',');
}

Number.prototype.zeroFormat = function(n, f, r){
    return n = new Array((++n, f ? (f = (this + "").length) < n ? n - f : 0 : n)).join(0), r ? this + n : n + this;
};

//This prototype is provided by the Mozilla foundation and
//is distributed under the MIT license.
//http://www.ibiblio.org/pub/Linux/LICENSES/mit.license

if (!Array.prototype.indexOf)
{
  Array.prototype.indexOf = function(elt /*, from*/)
  {
    var len = this.length;

    var from = Number(arguments[1]) || 0;
    from = (from < 0)
         ? Math.ceil(from)
         : Math.floor(from);
    if (from < 0)
      from += len;

    for (; from < len; from++)
    {
      if (from in this &&
          this[from] === elt)
        return from;
    }
    return -1;
  };
}

if (!Array.prototype.lastIndexOf)
{
  Array.prototype.lastIndexOf = function(elt /*, from*/)
  {
    var len = this.length;

    var from = Number(arguments[1]);
    if (isNaN(from))
    {
      from = len - 1;
    }
    else
    {
      from = (from < 0)
           ? Math.ceil(from)
           : Math.floor(from);
      if (from < 0)
        from += len;
      else if (from >= len)
        from = len - 1;
    }

    for (; from > -1; from--)
    {
      if (from in this &&
          this[from] === elt)
        return from;
    }
    return -1;
  };
}

Array.prototype.compare = function(testArr) {
    if (this.length != testArr.length) return false;
    for (var i = 0; i < testArr.length; i++) {
        if (this[i].compare) { 
            if (!this[i].compare(testArr[i])) return false;
        }
        if (this[i] !== testArr[i]) return false;
    }
    return true;
}




// Correção da função que dispara o DefaultButton
function fixDefaultButton() { 
    if (typeof(WebForm_FireDefaultButton) != 'undefined' )

          var origFireDefaultButton = WebForm_FireDefaultButton;

     

    WebForm_FireDefaultButton = function(event, target) {

        if (event.keyCode == 13) {

            var src = event.srcElement || event.target;
            var srcTag = src.tagName.toLowerCase();
            if (src &&
                (srcTag == "textarea" ||
                (typeof(siw) != "undefined" && siw != null) ||
                srcTag == "a" ||
                srcTag == "tr" ||
                srcTag == "td" ||                
                (srcTag == "input" &&
                (src.type.toLowerCase() == "submit" || src.type.toLowerCase() == "button")))) {                
                return true;

            }

        }       

        return origFireDefaultButton(event, target);

    }
}

//Chama essa função ao terminar uma requisição via UpdatePanel
function endRequest(sender, endRequestEventArgs) {
    var error = endRequestEventArgs.get_error();
    if(error !== null){
        window.alert(error.message.replace(error.name + ": ", ""));
        endRequestEventArgs.set_errorHandled(true);
    }
}