﻿//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(id, 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";


      var w = window.open(url, id, params);
      w.focus();

      return w;
   }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";

         var w = window.open(url, id, params);
         w.focus();

         return w;
      }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');
            
            var w = window.open(url, id, params + ',modal=yes');
            w.focus();

            return w;
         }catch(e){
             var w = window.open(url, id, params);
             w.focus();
             return w;
         }
      }
   }
}

//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(id, 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:''), false);
        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&id=" + document.getElementById('hdfChatID').value, false);
        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('/spcad/') > 0)
      hostPort = hostPort.substring(0, hostPort.toLowerCase().lastIndexOf('/spcad/'));
   else if(hostPort.toLowerCase().lastIndexOf('/spdid/') > 0)
      hostPort = hostPort.substring(0, hostPort.toLowerCase().lastIndexOf('/spdid/'));
   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 if(hostPort.toLowerCase().lastIndexOf('/spaju/') > 0)
      hostPort = hostPort.substring(0, hostPort.toLowerCase().lastIndexOf('/spaju/'));
   else if(hostPort.toLowerCase().lastIndexOf('/sprel/') > 0)
      hostPort = hostPort.substring(0, hostPort.toLowerCase().lastIndexOf('/sprel/'));
   else if(hostPort.toLowerCase().lastIndexOf('/speditor/') > 0)
      hostPort = hostPort.substring(0, hostPort.toLowerCase().lastIndexOf('/speditor/'));
   else if (hostPort.toLowerCase().lastIndexOf('/spest/') > 0)
       hostPort = hostPort.substring(0, hostPort.toLowerCase().lastIndexOf('/spest/'));
   else if (hostPort.toLowerCase().lastIndexOf('/spnet/') > 0)
       hostPort = hostPort.substring(0, hostPort.toLowerCase().lastIndexOf('/spnet/'));
    else if (hostPort.toLowerCase().lastIndexOf('/spavisos/') > 0)
       hostPort = hostPort.substring(0, hostPort.toLowerCase().lastIndexOf('/spavisos/'));
   else if (hostPort.toLowerCase().lastIndexOf('/sppedido/') > 0)
      hostPort = hostPort.substring(0, hostPort.toLowerCase().lastIndexOf('/sppedido/'));
   else if (hostPort.toLowerCase().lastIndexOf('/spbib/') > 0)
       hostPort = hostPort.substring(0, hostPort.toLowerCase().lastIndexOf('/spbib/'));
   else if (hostPort.toLowerCase().lastIndexOf('/sppesquisa/') > 0)
       hostPort = hostPort.substring(0, hostPort.toLowerCase().lastIndexOf('/sppesquisa/'));
   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);

    }
}

function client_OnTreeNodeChecked(evt)
{
   var obj;
   
   if(window.event)
      obj = window.event.srcElement;
   else
      obj = (evt ? evt : (window.event ? window.event : null)).target; 

   var treeNodeFound = false;
   var checkedState;
   
   if (obj.tagName == "INPUT" && obj.type == "checkbox" ) 
   {
       checkedState = obj.checked;
       
       do{
           obj = obj.parentNode;
       }while (obj.tagName != "TABLE")

       var parentTreeLevel = obj.rows[0].cells.length;
      
       //get the current node's parent node.
       var tables = obj.parentNode.getElementsByTagName("TABLE");
       var numTables = tables.length;
       
       if (numTables >= 1){
           for (i=0; i < numTables; i++){
               if (tables[i] == obj){
                   treeNodeFound = true;
                   i++;
                   if (i == numTables) return;
               }
              
               if (treeNodeFound == true){
                   var childTreeLevel = tables[i].rows[0].cells.length;
                   if (childTreeLevel > parentTreeLevel){
                       var cell = tables[i].rows[0].cells[childTreeLevel - 1];
                       var inputs = cell.getElementsByTagName("INPUT");
                       inputs[0].checked = checkedState;
                   }else
                       return;
               }
           }
       }
   }
}

//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);
    }
}

//se a tecla for Enter executa o click do botao
function sendClick(evt, buttonId) {
    var keynum;

    if (window.event) { // IE
        keynum = window.event['keyCode'];
        if (keynum == 9)
            freezeEvent(window.event);
    }
    else // Netscape/Firefox/Opera
        keynum = evt['keyCode'];

    if (keynum == 9) {
        document.getElementById(buttonId).click();
        //document.getElementById(hiddenID).value = val;
    }
}

function isNumeric(key) {
    if ((key < 96 || key > 105) && (key < 48 || key > 57))
        return false;
    else
        return true;
}

function isCtrlKey(key) {
    if (key != 8 && key != 9 && key != 46 && key != 17 && (key < 35 || key > 40))
        return true;
    else
        return false;
}

function stopEvent(pE) {
    if (!pE) {
        if (window.event)
            pE = window.event;
        else
            return;
    }

    if (pE.cancelBubble != null)
        pE.cancelBubble = true;

    if (pE.stopPropagation)
        pE.stopPropagation();

    if (pE.preventDefault)
        pE.preventDefault();

    if (window.event)
        pE.returnValue = false;

    if (pE.cancel != null)
        pE.cancel = true;
}

function trim(str) {
    return str.replace(/^\s+|\s+$/g, "");
}

function retDiaSemana(dia) {
    switch (dia) {
        case 0:
            return "Domingo";
            break;
        case 1:
            return "Segunda-Feira";
            break;
        case 2:
            return "Terça-Feira";
            break;
        case 3:
            return "Quarta-Feira";
            break;
        case 4:
            return "Quinta-Feira";
            break;
        case 5:
            return "Sexta-Feira";
            break;
        case 6:
            return "Sábado";
            break;
    }
}

var timeout_id;

function showHint(operacao, arg, userControl, e) {
    var hint_id;
    var posicaox, posicaoy;
    
    if (timeout_id)
        clearTimeout(timeout_id);

    if (!e)
        e = window.event;

    hint_id = arg;

    if (e.pageX || e.pageY) {
        posicaox = e.pageX;
        posicaoy = e.pageY;
    } else if (e.clientX || e.clientY) {
        posicaox = e.clientX + document.body.scrollLeft + document.documentElement.scrollLeft;
        posicaoy = e.clientY + document.body.scrollTop + document.documentElement.scrollTop;
    }

    timeout_id = setTimeout('CallBackHint("' + operacao + '", ' + hint_id + ', ' + posicaox + ', ' + posicaoy + ', ' + userControl + ')', 1000);
}

function hideHint(userControl) {
    var div;

    if (userControl)
        div = 'divInfoUserControl';
    else
        div = 'divInfoAluno';
    
    if (timeout_id)
        clearTimeout(timeout_id);

    document.getElementById(div).style.display = 'none';
}

function CallBackHint(operacao, arg, posx, posy, userControl) {
    var div;

    if (userControl)
        div = 'divInfoUserControl';
    else
        div = 'divInfoAluno';

    if (parseInt(arg) > 0) {
        document.getElementById(div).innerHTML = '<img src="' + getHost() + 'images/hintLoading.gif" />';
        document.getElementById(div).style.top = posy + "px";
        document.getElementById(div).style.left = posx + 30 + "px";
        document.getElementById(div).style.display = 'block';

        if (userControl)
            CallBackGeralUserControl(operacao + '»' + arg, '');
        else
            CallBackGeralPagina(operacao + '»' + arg, '');
    }
}

function ReceiveServerDataCallBackGeralPagina(rValue) {
    if (rValue.indexOf("»") >= 0) {
        var operacao = rValue.substring(0, rValue.indexOf("»"));
        var retorno = rValue.substring(rValue.indexOf("»") + 1);

        if ((operacao == 'hintAluno') || (operacao == 'integrantesTurma')) {
            var div = 'divInfoAluno';

            if (retorno.length >= 0) {
                document.getElementById(div).innerHTML = retorno;
            }
        }
    }
}

function ReceiveServerDataCallBackGeralUserControl(rValue) {
    if (rValue.indexOf("»") >= 0) {
        var operacao = rValue.substring(0, rValue.indexOf("»"));
        var retorno = rValue.substring(rValue.indexOf("»") + 1);

        if ((operacao == 'hintAluno') || (operacao == 'integrantesTurma')) {
            var div = 'divInfoUserControl';

            if (retorno.length >= 0) {
                document.getElementById(div).innerHTML = retorno;
            }
        }
    }
}

function daysInMonth(month, year) {
    var m = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
    
    if (month != 2) 
        return m[month - 1];
    
    if (year % 4 != 0) 
        return m[1];
    
    if (year % 100 == 0 && year % 400 != 0) 
        return m[1];
    
    return m[1] + 1;
} 

function validaDataDigitada(txt) {
    var d = txt.value;
    var ano = parseInt(d.substring(6, 10));
    var mes = parseInt(d.substring(3, 5));
    var dia = parseInt(d.substring(0, 2));

    if (mes < 1)
        mes = 1;
    else if (mes > 12)
        mes = 12;

    if (dia < 1)
        dia = 1;
    else if (dia > daysInMonth(mes, ano))
        dia = daysInMonth(mes, ano);

    if (!isNaN(dia) && !isNaN(mes) && !isNaN(ano))
        txt.value = dia.zeroFormat(2, true, false) + '/' + mes.zeroFormat(2, true, false) + '/' + ano.zeroFormat(4, true, false);
    else
        txt.value = '';
}

function OnProgress(progressBar) {
    var extraData = progressBar.getExtraData();

    if (extraData) {
        if ((extraData.indexOf("pronto:") == 0) && (progressBar.getValue() == 100)) {
            extraData = extraData.substring(7);

            if (extraData.indexOf("relatorio:") == 0)
                window.open(getHost() + "SPRel/ReportViewer.aspx?file=" + extraData.substring(10) + ".pdf", "_blank");
            else if (extraData.indexOf("remessa:") == 0)
                window.open(getHost() + 'Download.aspx', '_blank');
            else if (extraData.indexOf("email:") == 0) {
                extraData = extraData.substring(6);

                if (extraData.indexOf("erro:") == 0)
                    window.alert(extraData.substring(5));
                else {
                    extraData = extraData.substring(3);

                    var txt1 = extraData.substring(0, extraData.indexOf(":"));
                    var txt2 = extraData.substring(extraData.indexOf(":") + 1);

                    $get(txt1.split("»")[0]).innerHTML = txt1.split("»")[1];
                    $get(txt2.split("»")[0]).innerHTML = txt2.split("»")[1];
                    
                    showPopup("mpeLogEnvioBoletoBehavior");
                }
            }

            var div = document.getElementById("divStatus");
            div.innerHTML = "Geração concluída.";

            closeProgress();

            Sys.WebForms.PageRequestManager.getInstance().abortPostBack();
        } else if (extraData.indexOf("erro:") == 0) {
            window.alert('Não foi possível concluir a geração.\n\n' + extraData.substring(5));

            closeProgress();

            Sys.WebForms.PageRequestManager.getInstance().abortPostBack();
        } else {
            var div = document.getElementById("divStatus");
            div.innerHTML = extraData;
        }
    }
}

function selecionaImagemClassificacao(combo, img) {
    if (combo.value.indexOf("»") >= 0) {
        var src = combo.value.substring(combo.value.indexOf("»") + 1);

        img.src = getHost() + src;

        img.style.visibility = 'visible';
    } else {
        img.style.visibility = 'hidden';
    }
}

function GetRadioButtonListSelectedValue(id) {
    var RB1 = document.getElementById(id);
    var radio = RB1.getElementsByTagName("input");
    for (var i = 0; i < radio.length; i++) {
        if (radio[i].checked) {
            return radio[i].value;
        }
    }
    return '';
} 