// Funções de utilização pública em JavaScript
//
// -----------------------------------------------------------------------------------------

// Calcula a soma dos borders e padding Lef/Right de um objeto

function iqf_calculaBorPaddRL(vsourceobj)

{
    var vborderLeft = parseInt(document.getElementById(vsourceobj).style.borderLeftWidth);
    if (isNaN(vborderLeft))  { vborderLeft = 0; }
    var vborderRight = parseInt(document.getElementById(vsourceobj).style.borderRightWidth);
    if (isNaN(vborderRight)) { vborderRight = 0; }
    var vpadLeft = parseInt(document.getElementById(vsourceobj).style.paddingLeft);
    if (isNaN(vpadLeft)) { vpadLeft = 0; }
    var vpadRight = parseInt(document.getElementById(vsourceobj).style.paddingRight);
    if (isNaN(vpadRight)) { vpadRight = 0; }
    vsourceWidth = vborderLeft + vborderRight + vpadLeft + vpadRight;
    
    return vsourceWidth;
}

// Calcula a largura total de um objeto  ( Multi-Browser )

function iqf_calculawidth(vsourceobj)

{

    var vsourceWidth = parseInt(document.getElementById(vsourceobj).style.width);
    if (isNaN(vsourceWidth)) { 
        vsourceWidth = parseInt(document.getElementById(vsourceobj).width);
        if (isNaN(vsourceWidth))  { vsourceWidth = 0; }
    }
    var vborderLeft = parseInt(document.getElementById(vsourceobj).style.borderLeftWidth);
    if (isNaN(vborderLeft))  { vborderLeft = 0; }
    var vborderRight = parseInt(document.getElementById(vsourceobj).style.borderRightWidth);
    if (isNaN(vborderRight)) { vborderRight = 0; }
    var vpadLeft = parseInt(document.getElementById(vsourceobj).style.paddingLeft);
    if (isNaN(vpadLeft)) { vpadLeft = 0; }
    var vpadRight = parseInt(document.getElementById(vsourceobj).style.paddingRight);
    if (isNaN(vpadRight)) { vpadRight = 0; }
    vsourceWidth = vsourceWidth + vborderLeft + vborderRight + vpadLeft + vpadRight;
    
    return vsourceWidth;
}

// -------------------------------------------------------------------------------------------

// calcula a altura total de um objeto  ( Multi-Browser )

function iqf_calculaheight(vsourceobj)

{

    var vsourceHeight = parseInt(document.getElementById(vsourceobj).style.height);
    if (isNaN(vsourceHeight)) { 
        vsourceHeight = parseInt(document.getElementById(vsourceobj).height);
        if (isNaN(vsourceHeight))  { vsourceHeight = 0; }
    }
    var vborderTop = parseInt(document.getElementById(vsourceobj).style.borderTopWidth);
    if (isNaN(vborderTop))  { vborderTop = 0; }
    var vborderBottom = parseInt(document.getElementById(vsourceobj).style.borderBottomWidth);
    if (isNaN(vborderBottom)) { vborderBottom = 0; }
    var vpadTop = parseInt(document.getElementById(vsourceobj).style.paddingTop);
    if (isNaN(vpadTop)) { vpadTop = 0; }
    var vpadBottom = parseInt(document.getElementById(vsourceobj).style.paddingBottom);
    if (isNaN(vpadBottom)) { vpadBottom = 0; }
    vsourceHeight = vsourceHeight + vborderTop + vborderBottom + vpadTop + vpadBottom;
    
    return vsourceHeight;
}

// --------------------------------------------------------------------------------------------

// Função para pegar as coordenadas de um objeto no browser

function iqf_GetTopLeft(vobj) {

var x, y = 0;

// Offset do Objeto   
x = vobj.offsetLeft;
y = vobj.offsetTop;

// Pega o objeto que contem o primeiro

vobj = vobj.offsetParent;

// Rotina recursiva que vai somando os offset dos objetos pais até não haver mais pais.

while(vobj != null)
{
    x = parseInt(x) + parseInt(vobj.offsetLeft);
    y = parseInt(y) + parseInt(vobj.offsetTop);
    vobj = vobj.offsetParent;
}

// Retorna Top and Left como um objeto

return {Top:y, Left:x};
}

// ---------------------------------------------------------------------------------------------

// Função que determina a largura do browser

function iqf_getBrowserWidth()

{
    if (window.innerWidth)
    
        {
          return window.screen.width;
        }
    else if (document.documentElement && document.documentElement.clientWidth != 0)
    
        {
         return document.documentElement.clientWidth;
        }
    else if (document.body)
    
        {
        return document.body.clientWidth;
        }
    else if (window.screen)  
      
        {        
        return window.screen.width;   
        }
    
    return 0;
}

// ---------------------------------------------------------------------------------------------


// Função para pegar as coordenadas do Mouse.
// Não esta sendo usada aqui, pois funciona bem apenas para Internet Explorer.

function iqf_GetMousePos(e)

 {
	var posx = 0;
	var posy = 0;

	if (!e) var e = window.event;
	if (e.pageX || e.pageY) 	{
		posx = e.pageX;
		posy = e.pageY;
	}
	else if (e.clientX || e.clientY) 	{
		posx = e.clientX + document.body.scrollLeft + document.documentElement.scrollLeft;
		posy = e.clientY + document.body.scrollTop + document.documentElement.scrollTop;
	}

	// posx e posy contem a posição do mouse no documento

 
       return{Left:posx , Top:posy};

}

// Função que realiza um click num objeto ----------------------------------------------------

function iqf_ClickOnObject (vobj)
{
var vToClick = document.getElementById(vobj);
vToClick.onclick();
}

// Função que retorna o Tipo e a versão do browser --------------------------------------------

function iqf_GetBrowser()
{

var ua = navigator.userAgent.toLowerCase();
// alert(ua);
var vbrowser = "";
var vversao = "";
if ( (ua.indexOf("msie") != -1) && (ua.indexOf("opera") == -1) && (ua.indexOf("webtv") == -1) )
   { vbrowser = "IE" ; vversao = parseFloat(ua.substr(ua.indexOf('msie ') + 5,3)); }
else if (ua.indexOf("firefox") != -1)
   { vbrowser = "FIREFOX" ; vversao = parseFloat(ua.substr(ua.indexOf('firefox/') + 8,6)); }
else if (ua.indexOf("chrome") != -1)
   { vbrowser = "CHROME" ; vversao = parseFloat(ua.substr(ua.indexOf('chrome/') + 7,6));}  
   //{ vbrowser = "CHROME" ; vversao = ua.substr(ua.indexOf('chrome/') + 7,8);}   
else if (ua.indexOf("safari") != -1)
   // { vbrowser = "SAFARI" ; vversao = parseFloat(ua.substr(ua.indexOf('safari/') + 7,8)); }
   { vbrowser = "SAFARI" ; vversao = parseFloat(ua.substr(ua.indexOf('version/') + 8,6)); }
else if (ua.indexOf("opera") != -1)
   { vbrowser = "OPERA" ; vversao = parseFloat(ua.substr(ua.indexOf('opera/') + 6,4)); }
// var isKonqueror = (ua.indexOf("konqueror") != -1);
// var konquerorVersion = parseFloat(ua.substring(ua.indexOf('konqueror/') + 10));
// var isNetscape = (ua.indexOf("netscape") != -1);
// var netscapeVersion = parseFloat(ua.substring(ua.lastIndexOf('/') + 1));

return {browserName:vbrowser , browserVersion:vversao}

}

// ---------------------------------------------------------------------------------------------


// Função que retorna o idioma usado no Browser ------------------------------------------------

function iqf_GetBrowserLanguage(vobjClientID)

  {
      var vBrowserLang = ""
      if ( navigator ) 
       {
        if ( navigator.language )             { vBrowserLang = navigator.language; }
        else if ( navigator.browserLanguage ) { vBrowserLang = navigator.browserLanguage; }
        else if ( navigator.systemLanguage )  { vBrowserLang = navigator.systemLanguage; }
        else if ( navigator.userLanguage )    { vBrowserLang = navigator.userLanguage; }
       }
     
     if (vobjClientID != "") { var x = document.getElementById(vobjClientID); x.value = vBrowserLang; }
     else { return vBrowserLang; }
    
    }
    
// ---------------------------------------------------------------------------------------------

// Função para registro de assinaturas para LooKup-Tables --------------------------------------

var vIQPublicAssObj = new Array();
var vIQPublicAssKey = new Array();
var vContadorAss = 0;
 
function iqf_ObjectAssLT(vAss,vObjClID)
{
    vIQPublicAssObj[vContadorAss] = vObjClID;
    vIQPublicAssKey[vContadorAss] = vAss;
    vContadorAss++;
}
 
// Função para preecher os valores dos objetos de acordo com as assinaturas ( LooKup-Tables ) --

function iqf_ObjectSetLT(vAss,vVal)
{
  for (var i = 0; i < vIQPublicAssKey.length; i++)
      {
       if (vIQPublicAssKey[i] == vAss)
          {
            var x = document.getElementById(vIQPublicAssObj[i]);
            x.value = vVal;
          }
      }
}

// ----------------------------------------------------------------------------------------------

// Função que detecta se o Plugin do QuickTime esta instalado

function iqf_soundPlugins()
{
var vQTin = false;

if (navigator.plugins) 
   { 
     for (i=0; i < navigator.plugins.length; i++ ) 
         { 
           var vpg = navigator.plugins[i].name.toLowerCase();
           if (vpg.indexOf("quicktime") >= 0) 
              { vQTin = true; 
              } 
         } 
    } 
return  vQTin;  
}    
 
// Função que retorna a data e hora atual ----------------------------------------------------------------------
function iqf_GetDateTimeNow()
{  var data = new Date();                        // Obtém a data/hora atual
   var dia     = data.getDate();                 // 01-31
   if (dia <10) { dia = "0" + dia; }
   var dia_sem = data.getDay();                  // 0-6 (zero=domingo)
   var mes     = data.getMonth() + 1;            // 0-11 (zero=janeiro) + 1
   if (mes <10) { mes = "0" + mes; }
   var ano2    = data.getYear();                 // 2 dígitos
   var ano4    = data.getFullYear();             // 4 dígitos
   var hora    = data.getHours();                // 0-23
   if (hora <10) { hora = "0" + hora; }
   var min     = data.getMinutes();              // 0-59
   if (min <10) { min = "0" + min; }
   var seg     = data.getSeconds();              // 0-59
   if (seg <10) { seg = "0" + seg; }
   var mseg    = data.getMilliseconds();         // 0-999
   var tz      = data.getTimezoneOffset();       // em minutos

   var st_data = dia + '/' + (mes) + '/' + ano4; // Formata a data e a hora (note o mês + 1)
   var st_hora = hora + ':' + min + ':' + seg;   //

   return (st_data + ' ' + st_hora)
}

// Função que calcula e verifica os dígitos verificadores do CNPJ  --------------------------------------------
function iqf_CNPJ_dv(vCNPJ)
{
    if (vCNPJ.length != 14) { return false; }
     
    var vTotal = 0;
    vTotal += vCNPJ.substr(0,1) * 6
    vTotal += vCNPJ.substr(1,1) * 7
    vTotal += vCNPJ.substr(2,1) * 8
    vTotal += vCNPJ.substr(3,1) * 9
    vTotal += vCNPJ.substr(4,1) * 2
    vTotal += vCNPJ.substr(5,1) * 3
    vTotal += vCNPJ.substr(6,1) * 4
    vTotal += vCNPJ.substr(7,1) * 5
    vTotal += vCNPJ.substr(8,1) * 6
    vTotal += vCNPJ.substr(9,1) * 7
    vTotal += vCNPJ.substr(10,1) * 8
    vTotal += vCNPJ.substr(11,1) * 9
    var vDv1 = vTotal - ((parseInt( vTotal / 11 )) * 11)
    if (vDv1 == 10) { vDv1 = 0; }
 
    vTotal = 0;
    vTotal += vCNPJ.substr(0,1) * 5
    vTotal += vCNPJ.substr(1,1) * 6
    vTotal += vCNPJ.substr(2,1) * 7
    vTotal += vCNPJ.substr(3,1) * 8
    vTotal += vCNPJ.substr(4,1) * 9
    vTotal += vCNPJ.substr(5,1) * 2
    vTotal += vCNPJ.substr(6,1) * 3
    vTotal += vCNPJ.substr(7,1) * 4
    vTotal += vCNPJ.substr(8,1) * 5
    vTotal += vCNPJ.substr(9,1) * 6
    vTotal += vCNPJ.substr(10,1) * 7
    vTotal += vCNPJ.substr(11,1) * 8
    vTotal += vDv1 * 9

    var vDv2 = vTotal - ((parseInt( vTotal / 11 )) * 11)
    if (vDv2 == 10) { vDv2 = 0; }
    var vDvCNPJ = (vDv1*10) + vDv2

    if ( parseInt(vCNPJ.substr(12,2)) == parseInt(vDvCNPJ)) { return true;  }
    else                                                    { return false; }
}
 
// Função que calcula e verifica os dígitos verificadores do CPF  ---------------------------------------------
function iqf_CPF_dv(vCPF)
{
    if (vCPF.length != 11) { return false; }
     
    var vTotal = 0;
    vTotal += vCPF.substr(0,1) * 1
    vTotal += vCPF.substr(1,1) * 2
    vTotal += vCPF.substr(2,1) * 3
    vTotal += vCPF.substr(3,1) * 4
    vTotal += vCPF.substr(4,1) * 5
    vTotal += vCPF.substr(5,1) * 6
    vTotal += vCPF.substr(6,1) * 7
    vTotal += vCPF.substr(7,1) * 8
    vTotal += vCPF.substr(8,1) * 9
    var vDv1 = vTotal - ((parseInt( vTotal / 11 )) * 11)
    if (vDv1 == 10) { vDv1 = 0; }
  
    vTotal = 0;
    vTotal += vCPF.substr(0,1) * 0
    vTotal += vCPF.substr(1,1) * 1
    vTotal += vCPF.substr(2,1) * 2
    vTotal += vCPF.substr(3,1) * 3
    vTotal += vCPF.substr(4,1) * 4
    vTotal += vCPF.substr(5,1) * 5
    vTotal += vCPF.substr(6,1) * 6
    vTotal += vCPF.substr(7,1) * 7
    vTotal += vCPF.substr(8,1) * 8
    vTotal += vDv1 * 9

    var vDv2 = vTotal - ((parseInt( vTotal / 11 )) * 11)
    if (vDv2 == 10) { vDv2 = 0; }
    var vDvCPF = (vDv1*10) + vDv2

    if ( parseInt(vCPF.substr(9,2)) == parseInt(vDvCPF) ) { return true;  }
    else                                                  { return false; }
}

// Função para verificar o dígito verificador do Cpf ou Cnpj -----------------------------------------------------------
function iqf_testaCpfCnpf(sender, args)
{
    var y = args.Value.length;
    if (y > 11) { var x = iqf_CNPJ_dv(args.Value); }
    else        { var x = iqf_CPF_dv(args.Value); }
   
    return args.IsValid = x;
}

// Funções para verificação de um Range Validator ----------------------------------------------------------------------
function iqf_RangeValidator(sender,args)
{  
    var vRet = false;
    var vMin = parseInt(sender.IQRangeValidatorMinimo,10);
    var vMax = parseInt(sender.IQRangeValidatorMaximo,10);
    
    if (args.Value >= vMin && args.Value <= vMax)
       { vRet=true;  }
    else
       { vRet=false; }

    return args.IsValid = vRet;
}

// Função de cronômetro de Contagem regressiva -------------------------------------------------------------------------

var vCronometroA = "";
var vCronometroB = "";
var vCronoMetroDateInitA = new Date();
var vCronoMetroDateInitB = new Date();
var vCronoExecFinalA = "";
var vCronoExecFinalB = "";

function iqf_CronometroRegressivo(vSegundos,vClientID,vID,vExecFuncFinalCronometro)
{   
    if (vID=="A") { vCronoExecFinalA = vExecFuncFinalCronometro; vCronometroA = setInterval("iqf_ShowCronometro(" + vSegundos + ",'" + vClientID + "','A')",1000); }
    if (vID=="B") { vCronoExecFinalB = vExecFuncFinalCronometro; vCronometroB = setInterval("iqf_ShowCronometro(" + vSegundos + ",'" + vClientID + "','B')",1000); }
}
function iqf_ShowCronometro(vSegundos,vClientID,vID)
{
    var vObj = document.getElementById(vClientID);
    var vDtNow = new Date();
    var vTempo = 0; var vDifHoras = 0; var vDifMinutos = 0;  var vDifSegundos = 0;
    
    if (vID=="A") 
       { vDifHoras = (vDtNow.getHours() - vCronoMetroDateInitA.getHours()) * 3600
         vDifMinutos = (vDtNow.getMinutes() - vCronoMetroDateInitA.getMinutes()) * 60;
         vDifSegundos = (vDtNow.getSeconds() - vCronoMetroDateInitA.getSeconds());
         vTempo = vSegundos - (vDifHoras + vDifMinutos + vDifSegundos) ;  
       }
    
    if (vID=="B") 
       { vDifHoras = (vDtNow.getHours() - vCronoMetroDateInitB.getHours()) * 3600
         vDifMinutos = (vDtNow.getMinutes() - vCronoMetroDateInitB.getMinutes()) * 60;
         vDifSegundos = (vDtNow.getSeconds() - vCronoMetroDateInitB.getSeconds());
         vTempo = vSegundos - (vDifHoras + vDifMinutos + vDifSegundos);  
       }
    
    
    if (vTempo >= 0)
       {  var vStMinutos = parseInt(vTempo/60,10);
          if (vStMinutos < 10) { vStMinutos = "0" + vStMinutos ; }
          var vStSegundos = parseInt(((vTempo/60) - parseInt(vTempo/60)) * 60,10);
          if (vStSegundos < 10) { vStSegundos = "0" + vStSegundos; }
          vObj.innerHTML = vStMinutos + ":" + vStSegundos; 
          vObj.style.color = "red";
       }

    if (vTempo <= 0) 
       {  if (vID=="A") { clearInterval(vCronometroA); eval(vCronoExecFinalA); }
          if (vID=="B") { clearInterval(vCronometroB); eval(vCronoExecFinalB); }
       }
}
function iqf_InitDataCronometro(vID)
{
    var vDtInit = "";
    if (vID=='A') { vCronoMetroDateInitA = new Date(); vDtInit = vCronoMetroDateInitA.toString(); }
    if (vID=='B') { vCronoMetroDateInitB = new Date(); vDtInit = vCronoMetroDateInitB.toString(); }
    var x = PageMethods.IQSH_SetDataCronometroJS(vDtInit,iqf_InitDataCronOK,iqf_InitDataCronERR);
}
function iqf_InitDataCronOK(vRet,vParam) {}
function iqf_InitDataCronERR(vRet,vParam) {}
function iqf_SetDataCronometro(vData,vID)
{   
    if (vID=='A') { vCronoMetroDateInitA = new Date(vData); }
    if (vID=='B') { vCronoMetroDateInitB = new Date(vData); }
}
function iqf_StopCronometro(vID)
{
    if (vID=='A') { clearInterval(vCronometroA); }
    if (vID=='B') { clearInterval(vCronometroB); }
}
// --------------------------------------------------------------------------------------------------------------------------------------------

// Função que Realiza um fadeIn / Out em um panel no canto inferior direito da tela ---------------------------------------------

var vContaOpa = 0;
function iqf_FadeAlertPanel(vPanel,vDelay,vPosTop,vPosLeft)
{   document.getElementById(vPanel).style.display = "block";
    document.getElementById(vPanel).style.opacity = 0;
    document.getElementById(vPanel).style.filter = 'alpha(opacity=' + 0 + ')'; 
    setTimeout("iqf_FadeAlertPanel_A('" + vPanel + "'," + vPosTop + "," + vPosLeft + ")",vDelay);
}
function iqf_FadeAlertPanel_A(vPanel,vPosTop,vPosLeft)
{  
    var vBrowseW = iqf_GetBrowser();
    if ( vBrowseW.browserName == "IE")
       {  var vhWindow = parseInt(document.documentElement.clientHeight);
          var vwWindow = parseInt(iqf_getBrowserWidth());
          var vhPadding = 15; var vwPadding = 15;
       }
    else
       { var vhWindow = parseInt(window.innerHeight);
         var vwWindow = parseInt(window.innerWidth);
         var vhPadding = 15;   var vwPadding = 25;
       }   
          
    var vPanelW = iqf_calculawidth(vPanel);
    var vPanelH = iqf_calculaheight(vPanel);

    if (vPosTop == "" || typeof(vPosTop) == "undefined" )
       { document.getElementById(vPanel).style.top = parseInt(vhWindow - vPanelH - vhPadding) + 'px'; }
    else
       { document.getElementById(vPanel).style.top = parseInt(vPosTop) + 'px'; }
    if (vPosLeft == ""  || typeof(vPosLeft) == "undefined" )  
       { document.getElementById(vPanel).style.left = parseInt(vwWindow - vPanelW - vwPadding) + 'px'; }
    else
       { document.getElementById(vPanel).style.top = parseInt(vPosLeft) + 'px'; }   
                    
    vMx = setInterval("iqf_FadePanelInOut('S','" + vPanel + "')",50); 
}
function iqf_FadePanelInOut(vShowHide,vPanel)
{   var vBrowseW = iqf_GetBrowser();
    if (vShowHide == 'S')
       { vContaOpa += 0.01;
         if (vContaOpa > 1) { clearInterval(vMx); vContaOpa = 1; setTimeout("iqf_FadeOut('" + vPanel + "')",3000);}
         if ( vBrowseW.browserName == "IE") { document.getElementById(vPanel).style.filter = 'alpha(opacity=' + vContaOpa*100 + ')'; }
         else                               { document.getElementById(vPanel).style.opacity = vContaOpa; }
       }
    else
       { vContaOpa = vContaOpa - 0.01;
         if (vContaOpa < 0) { clearInterval(vMx); vContaOpa = 0; }
         if ( vBrowseW.browserName == "IE") { document.getElementById(vPanel).style.filter = 'alpha(opacity=' + vContaOpa*100 + ')'; }
         else                               { document.getElementById(vPanel).style.opacity = vContaOpa; }
        }     
}  
function iqf_FadeOut(vPanel)
{   vMx = setInterval("iqf_FadePanelInOut('H','" + vPanel + "')",50);  }

// Função para inserir um HTML object - embed num panel para passar um filme ------------------------------------------------------------------

function iqf_ShowFilmeTutorial(vHTML,vPanel)
{   vHTML = vHTML.replace(/&gt;/g,">");
	vHTML = vHTML.replace(/&lt;/g,"<");
	document.getElementById(vPanel).innerHTML = vHTML;
} 

// --------------------------------------------------------------------------------------------------------------------------------------------

// ============================================================================================================================================
// O mistério do xmlhttprequest em resolução

function iqf_GetClientFile(vUrl) {
    try { 
        xmlhttp = new ActiveXObject("MSXML2.XMLHTTP"); 
    } catch (e) { 
        try { 
            xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); 
        } catch (E) { 
            xmlhttp = false; 
        } 
    } 

    if  (!xmlhttp && typeof  XMLHttpRequest != 'undefined' ) { 
        try  { 
            xmlhttp = new  XMLHttpRequest(); 
        } catch  (e) { 
            xmlhttp = false ; 
        } 
    }

    if (xmlhttp) {
       
        vUrl = vUrl.replace(/\\/g, "\\\\");
        fso = new ActiveXObject( "Scripting.FileSystemObject" );
        if ( !fso.FileExists(vUrl) )
           {
            alert("Can't open file.");
            return;
           }
        
         xmlhttp.onreadystatechange = iqp_processadorMudancaEstado;
        
        
        // var xmlhttp = this.createXMLHttpRequest();
        //xmlhttp.open("POST", "Handler_Teste.ashx?Arquivo=" + vUrl + "&Time=De" , false);
        // xmlhttp.open("GET", "http://localhost/images/smiley.gif",false);
        xmlhttp.open("GET", vUrl,false);
        xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
        //xmlHhttp.send("sessionId="+this.sessionId);
        
        //xmlhttp.open("GET", "Handler_Teste.ashx?Arquivo=" + vUrl + "&Time=De" ,false);

        xmlhttp.send("a1");
        return xmlhttp.responseBody ; 
    }
}

function iqp_processadorMudancaEstado () {
    if ( xmlhttp.readyState == 4) { // Completo 
        if ( xmlhttp.status == 200) { // resposta do servidor OK 
        vPubImg = xmlhttp.responseBody
        } else { 
            alert( "Problema: " + xmlhttp.statusText );  
        } 
    }
}


// ===========================================================

