var tmr;
var tmr2;
var cor;

//Loading na pagina
n=document.layers
ie=document.all

ns4 = (document.layers) ? true : false;
ie4 = (document.all) ? true : false;

//TESTE DE ALTERACAO NO ARQUIVO

function selecionaGrid(elemento)
{
    cor = elemento.style.backgroundColor;
    
    elemento.style.backgroundColor = "#FFFF99"; //"#ECF3B8";
}

function deSelecionaGrid(elemento)
{
    elemento.style.backgroundColor = cor;
}

function MudarFoco(pObj)
{
    try
	{
	    if(pObj != null)
	    {
            if(pObj.getAttribute("maxlength") != null)
            {
                if(pObj.getAttribute("maxlength") > 0)
                {
	                if(pObj.getAttribute("maxlength") == pObj.value.length)
	                {
		                for(i = 0; i < pObj.form.elements.length; i++)
		                {
                            if(pObj.form.elements[i].name == pObj.id)
                            {
                                pObj.form.elements[i + 1].focus();
		                    }
		                }
	                }
	            }
            }	
	    }
	}catch(e){}
}

function ZerarCampo(pObj)
{
	if(pObj.value == '')
	{
		pObj.value = 0;
	}
}

function SomenteNumeros()
{
	var keyCode = event.keyCode;
	
	if(!(keyCode > 47 && keyCode < 58))
	{
		event.keyCode = 0;
	}
}

function SomenteNumeros(event) {
    var keyCode = event.keyCode ? event.keyCode : event.which ? event.which : event.charCode;

    if (!(keyCode > 47 && keyCode < 58)) {
        if (event.keyCode) {
            event.keyCode = 0;
        }
        else {
            return false;
        }
    }
}

function SomenteNumerosDecimais(pObj)
{
	var keyCode = event.keyCode;
	
	//Bloqueia virgulas repetidas
	if ((pObj.value.indexOf(',') > -1) && (keyCode == 44))
	{
	    event.keyCode = 0;
	}
	
	//Bloqueia caracteres que nao sao numericos e nem virgulas
	if(!(keyCode > 47 && keyCode < 58) && (keyCode != 44))
	{
		event.keyCode = 0;
	}
}

function AbrirPopup1(url, largura, altura)
{
	topo     = (screen.height/2)-(altura/2);
	esquerda = (screen.width/2) - (largura/2);
	
	window.open(url, "popup", 'width=' + largura + ',height=' + altura + ',toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=no,resizable=no,top=' + topo + ',left=' + esquerda);
}

function AbrirPopup2(url, largura, altura, scroll)
{
	topo     = (screen.height/2)-(altura/2);
	esquerda = (screen.width/2) - (largura/2);
	
	if(scroll != "1")
	{
	    scroll = "no";
	}
	else
	{
	    scroll = "yes";
	}

	OcultarAguarde();
	
	window.open(url, "_blank", 'width=' + largura + ',height=' + altura + ',toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=' + scroll + ',resizable=no,top=' + topo + ',left=' + esquerda);
	
	return false;
}

function AbrirPopup3(url, largura, altura, scroll) {
    topo = (screen.height / 2) - (altura / 2);
    esquerda = (screen.width / 2) - (largura / 2);

    if (scroll != "1") {
        scroll = "no";
    }
    else {
        scroll = "yes";
    }

    OcultarAguarde();

    window.open(url, "_blank", 'width=' + largura + ',height=' + altura + ',toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=' + scroll + ',resizable=yes,top=' + topo + ',left=' + esquerda);

    return false;
}


function AbrirPopup4(url, scroll) {
//    topo = (screen.height / 2) - (altura / 2);
//    esquerda = (screen.width / 2) - (largura / 2);

    if (scroll != "1") {
        scroll = "no";
    }
    else {
        scroll = "yes";
    }

    OcultarAguarde();

    window.open(url, "_blank", 'width=' + screen.width + ',height=' + screen.height + ',toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=' + scroll + ',resizable=yes,top=0,left=0');

    return false;
}

function SelecionarItemCombo(pCombo, pValor)
{
    var combo = document.getElementById(pCombo);
    
    if (combo != null)
    {
        for(i = 0; i < combo.options.length; i++)
        {
            if(combo.options[i].value == pValor)
            {
                combo.selectedIndex = i;
                
                break;
            }
        }
    }
}

function CriaMascara(_RefObjeto, _Modelo)
{ 
    var valorAtual = _RefObjeto.value;
    var valorNumerico = '';
    var nIndexModelo = 0;
    var nIndexString = 0;
    var valorFinal = '';
    var adicionarValor = true;
			  
			 
	// limpa a string valor atual para verificar
	// se todos os caracteres são números
	for (i=0;i<_Modelo.length;i++)
    {
        if (_Modelo.substr(i,1) != '#')
        {
            valorAtual = valorAtual.replace(_Modelo.substr(i,1),'');
        }
    }
    
	// verifica se todos os caracteres são números
    for (i=0;i<valorAtual.length;i++)
    {
        if (!isNaN(parseFloat(valorAtual.substr(i,1))))
        {
            valorNumerico = valorNumerico + valorAtual.substr(i,1);
        }
    }
    
    // aplica a máscara ao campo informado usando
    // o modelo de máscara informado no script
    for (i = 0; i < _Modelo.length; i++)
    {
        if (_Modelo.substr(i,1) == '#')
        {
            if (valorNumerico.substr(nIndexModelo,1) != '')
            {
                valorFinal = valorFinal + valorNumerico.substr(nIndexModelo,1);
                nIndexModelo++;
                nIndexString++;
            }
            else 
            {
                adicionarValor = false;
            }
        }
  		else 
        {
            if (adicionarValor && valorNumerico.substr(nIndexModelo,1) != '')
            {
                valorFinal = valorFinal + _Modelo.substr(nIndexString,1)
                nIndexString++;
            }
        }
    }
	
    _RefObjeto.value = valorFinal
}

function CriaMascaraAlpha(_RefObjeto, _Modelo)
{
    var valorAtual = _RefObjeto.value;
    var valorNumerico = '';
    var nIndexModelo = 0;
    var nIndexString = 0;
    var valorFinal = '';
    var adicionarValor = true;
    
	// limpa a string valor atual para verificar
	// se todos os caracteres são números
	for (i=0;i<_Modelo.length;i++)
    {
        if (_Modelo.substr(i,1) != '#')
        {
            valorAtual = valorAtual.replace(_Modelo.substr(i,1),'');
        }
    }
    
	// verifica se todos os caracteres são números
    for (i=0;i<valorAtual.length;i++)
    {
        //if (isNaN(parseFloat(valorAtual.substr(i,1))) ||
        //    !isNaN(parseFloat(valorAtual.substr(i,1))))
        //{
            valorNumerico = valorNumerico + valorAtual.substr(i,1);
        //}
    }
    
    // aplica a máscara ao campo informado usando
    // o modelo de máscara informado no script
    for (i = 0; i < _Modelo.length; i++)
    {
        if (_Modelo.substr(i,1) == '#')
        {
            if (valorNumerico.substr(nIndexModelo,1) != '')
            {
                valorFinal = valorFinal + valorNumerico.substr(nIndexModelo,1);
                nIndexModelo++;
                nIndexString++;
            }
            else 
            {
                adicionarValor = false;
            }
        }
  		else 
        {
            if (adicionarValor && valorNumerico.substr(nIndexModelo,1) != '')
            {
                valorFinal = valorFinal + _Modelo.substr(nIndexString,1)
                nIndexString++;
            }
        }
    }
	
    _RefObjeto.value = valorFinal
}

function ExibirDiv(pObj, pVisivel)
{
    if(pObj != null)
    {
        if(pVisivel)
        {
            document.getElementById(pObj).style.display = 'block';
        }
        else
        {
            document.getElementById(pObj).style.display = 'none';
        }
    }
}

function MudarCorLabel(pObj, pMudar)
{
    if(pObj != null)
    {        
        if(pMudar)
        {
            document.getElementById(pObj).style.color = '#FF0000';            
        }
        else
        {
            document.getElementById(pObj).style.color = '#000000';            
        }
    }
}

function SetarTexto(pObj, pTexto)
{
    if(pObj != null)
    {
        document.getElementById(pObj).innerHTML = pTexto;
    }
}

function CampoDecimal(Campo, precisao) 
{
	var Caracteres="0123456789,";
	var Keyascii = event.keyCode;
	
	var carac = String.fromCharCode(Keyascii);
	
	if (Caracteres.indexOf(String.fromCharCode(Keyascii))==-1)
	{
		event.returnValue = 0;
		return;
	}

	if(Campo.value.indexOf(",")!=-1)
	{
		if(carac==",")
		{
			//impede mais de uma virgula
			event.returnValue = 0;
			return;
		}
	
		var arrChar = Campo.value.split(",")
		var x = arrChar[1];
		
		if(x.length >= precisao)
		{
			event.returnValue = 0;
			return;
		}
	}
	else
	{
		if(Campo.value.length<(Campo.maxLength - precisao))
		{
			if(Campo.value.length==(Campo.maxLength - precisao - 1))
			{
				if(carac!=",")
				{
					event.returnValue = 0;
				}
			}
		}
		else
		{
			event.returnValue = 0;
		}
		return;		
	}
}

function findPos(obj) {
	var curleft = curtop = 0;
	
	if (obj.offsetParent) 
	{
		curleft = obj.offsetLeft;
		curtop = obj.offsetTop;
		
		while (obj = obj.offsetParent)
		{
			curleft += obj.offsetLeft
			curtop += obj.offsetTop
		}
	}
	
	return [curleft,curtop];
}

function SomenteEmail(e) {
	var keyNumber = (isIE) ? event.keyCode : e.which;
	if 	(
			!( 
				( 	
					((keyNumber > 43) && (keyNumber<58))  ||
					((keyNumber > 63) && (keyNumber<91))  ||
					((keyNumber > 96) && (keyNumber<123)) ||
					((keyNumber > 191) && (keyNumber<221)) ||
					((keyNumber > 223) && (keyNumber<253)) ||
					(keyNumber==32) || 
					(keyNumber==8) ||
					(keyNumber==95)
				) && 
				(keyNumber!=168)
			)
		)
	{
		if (isIE) {
			event.keyCode=0
		}
		return false;
	}
	return true;
}

function PreloadImages() 
{
    var d = document;
    
    if(d.images)
    {
        if(!d.MM_p)
        {
            d.MM_p = new Array();
        }
        
        var i, j = d.MM_p.length, a = PreloadImages.arguments; 
        
        for(i = 0; i < a.length; i++)
        {
            if (a[i].indexOf("#") != 0)
            {
                d.MM_p[j] = new Image;
                d.MM_p[j++].src = a[i];
            }
        }
    }
}

function Bloquear_Enter()
{
	var objEvent = event.srcElement;
	
	if(event.keyCode == 13 && objEvent.id == "")
	{ 
		// Cancela o evento default
		event.returnValue = false; 
		event.cancel = true; 
		
		//btn.click(); 
	}
}

function ForcarOnKeyPress(pObj)
{
    var obj = document.getElementById(pObj);
    
    if(obj != null)
    {
        try
        {
            obj.onkeypress();
        }
        catch(e)
        {
            a = e.toString();
        }
    }
}

function currencyFormat(fld, milSep, decSep, e) {
	var sep = 0;
	var key = '';
	var i = j = 0;
	var len = len2 = 0;
	var strCheck = '0123456789';
	var aux = aux2 = '';
	var whichCode = (window.Event) ? e.which : e.keyCode;
	
	if (whichCode == 13) return true;  // Enter

	key = String.fromCharCode(whichCode);  // Get key value from key code

	if (strCheck.indexOf(key) == -1) return false;  // Not a valid key

	len = fld.value.length;

	for(i = 0; i < len; i++)
		if ((fld.value.charAt(i) != '0') && (fld.value.charAt(i) != decSep)) break;

	aux = '';

	for(; i < len; i++)
	if (strCheck.indexOf(fld.value.charAt(i))!=-1) aux += fld.value.charAt(i);
	aux += key;

	len = aux.length;

	if (len == 0) fld.value = '';
	if (len == 1) fld.value = '0'+ decSep + '0' + aux;
	if (len == 2) fld.value = '0'+ decSep + aux;

	if (len > 2) {
		aux2 = '';
		
		for (j = 0, i = len - 3; i >= 0; i--) {
			if (j == 3) {
				aux2 += milSep;
				j = 0;
			}
		aux2 += aux.charAt(i);
		j++;
	}

	fld.value = '';
	len2 = aux2.length;

        for (i = len2 - 1; i >= 0; i--)
	        fld.value += aux2.charAt(i);

        fld.value += decSep + aux.substr(len - 2, len);
    }
    
	return false;
}


function MM_swapImgRestore() { //v3.0
  var i,x,a=document.MM_sr; for(i=0;a&&i<a.length&&(x=a[i])&&x.oSrc;i++) x.src=x.oSrc;
}

function MM_findObj(n, d) { //v4.01
  var p,i,x;  if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {
    d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
  if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
  for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document);
  if(!x && d.getElementById) x=d.getElementById(n); return x;
}

function MM_swapImage() { //v3.0
  var i,j=0,x,a=MM_swapImage.arguments; document.MM_sr=new Array; for(i=0;i<(a.length-2);i+=3)
   if ((x=MM_findObj(a[i]))!=null){document.MM_sr[j++]=x; if(!x.oSrc) x.oSrc=x.src; x.src=a[i+2];}
}

function MM_showHideLayers() { //v6.0
  var i,p,v,obj,args=MM_showHideLayers.arguments;
  for (i=0; i<(args.length-2); i+=3) if ((obj=MM_findObj(args[i]))!=null) { v=args[i+2];
    if (obj.style) { obj=obj.style; v=(v=='show')?'visible':(v=='hide')?'hidden':v; }
    obj.visibility=v; }
}

function MM_openBrWindow(theURL,winName,features) { //v2.0
  window.open(theURL,winName,features);
}

function dateDifference(strDate1, strDate2)
{
     var date1 = document.getElementById(strDate1).value;
     var date2 = document.getElementById(strDate2).value;

     date1 = date1.split("/");
     date2 = date2.split("/");

     var sDate = new Date(date1[1]+"/"+date1[0]+"/"+date1[2]);
     var eDate = new Date(date2[1]+"/"+date2[0]+"/"+date2[2]);

     var daysApart = Math.abs(Math.round((sDate-eDate)/86400000))+ 1;
     
     if(eDate < sDate)
     {
        return -1;
     }
     else
     {     
        return daysApart;
     }
 }

function Load_Page()
{
    if(ie || n)
    {
	    if(n)
	    {
	        if(document.divLoadCont != null)
	        {
	            document.divLoadCont.visibility="hidden"
	        }
	    }
	    else
	    {
	        if(divLoadCont != null)
	        {
	            divLoadCont.style.visibility="hidden"
	        }
	    }
    }
}

function pause(numberMillis) 
{
    var now = new Date();
    var exitTime = now.getTime() + numberMillis;
    
    while (true) 
    {
        now = new Date();
        if (now.getTime() > exitTime)
        return;
    }
}

function trataBackSpaceMascaraValorRT(campo, event)
{
   NumDig = campo.value;
   TamDig = NumDig.length;
   TamDig--;
   Contador = 0;
   if ((TamDig >= 0) && (event.keyCode == 8))
    {
      numer = "";
      for (i = TamDig; (i >= 0); i--){
          if ((parseInt(NumDig.substr(i,1))>=0) && (parseInt(NumDig.substr(i, 1))<=9))
            {
             Contador++;
             /*alert(NumDig.substr(i, 1) + " Contador " + Contador+ " numer "+ numer+ " TamDig " +TamDig + " i " + i );*/
             if ((Contador == 4) && ((TamDig -i) < 5))
              {numer = ","+numer;
               Contador = 0;
               }
             else if ((Contador == 3) && ((numer.length) > 4))  
              {numer = "."+numer;
               Contador = 0;
              }
              
             numer = NumDig.substr(i, 1)+numer;
            
            }
        }
            if (numer == "001" || numer == "000" || numer == "002" || numer == "003" || numer == "004" || numer == "005" || numer == "006" || numer == "007" || numer == "008" || numer == "009") 
                numer="";       
            if ((numer.length) == 3 )
                numer= "0," + numer;

        campo.value = numer;
      };
}
function mascaraValorRT(fld, milSep, decSep, e) {   
    var sep = 0;
    var key = '';
    var i = j = 0;
    var len = len2 = 0;
    var strCheck = '0123456789';
    var aux = aux2 = '';
    var whichCode = (window.Event) ? e.which : e.keyCode;


    trataBackSpaceMascaraValorRT(fld, e);

    if (whichCode == 13) return true;  // Enter
    key = String.fromCharCode(whichCode);  // Get key value from key code
    if (strCheck.indexOf(key) == -1) return false;  // Not a valid key
    len = fld.value.length;
    for(i = 0; i < len; i++)
        if ((fld.value.charAt(i) != '0') && (fld.value.charAt(i) != decSep)) break;
    aux = '';
    for(; i < len; i++)
    if (strCheck.indexOf(fld.value.charAt(i))!=-1) aux += fld.value.charAt(i);
    aux += key;
    len = aux.length;
    if (len == 0) fld.value = '';
    if (len == 1) fld.value = '0'+ decSep + '0' + aux;
    if (len == 2) fld.value = '0'+ decSep + aux;
    if (len > 2) {
        aux2 = '';
        for (j = 0, i = len - 3; i >= 0; i--) {
            if (j == 3) {
                aux2 += milSep;
                j = 0;
            }
            aux2 += aux.charAt(i);
            j++;
        }
        fld.value = '';
        len2 = aux2.length;
        for (i = len2 - 1; i >= 0; i--)    fld.value += aux2.charAt(i);
        fld.value += decSep + aux.substr(len - 2, len);
    }
    return false;
}

function trataBackSpaceMascaraValorRT4CasasDecimais(campo, event)
{   
   NumDig = campo.value;
   TamDig = NumDig.length;
   TamDig--;
   Contador = 0;
   if ((TamDig >= 0) && (event.keyCode == 8))
    {
      numer = "";
      for (i = TamDig; (i >= 0); i--){
          if ((parseInt(NumDig.substr(i,1))>=0) && (parseInt(NumDig.substr(i, 1))<=9))
            {
             Contador++;
             /*alert(NumDig.substr(i, 1) + " Contador " + Contador+ " numer "+ numer+ " TamDig " +TamDig + " i " + i );*/
             if ((Contador == 6) && ((TamDig -i) < 7))
              {numer = ","+numer;
               Contador = 0;
               }
             else if ((Contador == 5) && ((numer.length) > 6))  
              {numer = "."+numer;
               Contador = 0;
              }
              
             numer = NumDig.substr(i, 1)+numer;
            
            }
        }
            if (numer == "00000" || numer == "00001" || numer == "00002" || numer == "00003" || numer == "00004" || numer == "00005" || numer == "00006" || numer == "00007" || numer == "00008" || numer == "00009") 
                numer="";       
            if ((numer.length) == 5 )
                numer= "0," + numer;

        campo.value = numer;
      };
}

function mascaraValorRT4CasasDecimais(fld, milSep, decSep, e) {
    var sep = 0;
    var key = '';
    var i = j = 0;
    var len = len2 = 0;
    var strCheck = '0123456789';
    var aux = aux2 = '';
    var whichCode = (window.Event) ? e.which : e.keyCode;


    trataBackSpaceMascaraValorRT4CasasDecimais(fld, e);

    if (whichCode == 13) return true;  // Enter
    key = String.fromCharCode(whichCode);  // Get key value from key code
    if (strCheck.indexOf(key) == -1) return false;  // Not a valid key
    len = fld.value.length;
    for(i = 0; i < len; i++)
        if ((fld.value.charAt(i) != '0') && (fld.value.charAt(i) != decSep)) break;
    aux = '';
    for(; i < len; i++)
    if (strCheck.indexOf(fld.value.charAt(i))!=-1) aux += fld.value.charAt(i);
    aux += key;
    len = aux.length;
    if (len == 0) fld.value = '';
    if (len == 1) fld.value = '0'+ decSep + '000' + aux;
    if (len == 2) fld.value = '0'+ decSep + '00' + aux;
    if (len == 3) fld.value = '0'+ decSep + '0' + aux;
    if (len == 4) fld.value = '0'+ decSep + aux;
    if (len > 4) {
        aux2 = '';
        for (j = 0, i = len - 5; i >= 0; i--) {
            if (j == 3) {
                aux2 += milSep;
                j = 0;
            }
            aux2 += aux.charAt(i);
            j++;
        }
        fld.value = '';
        len2 = aux2.length;
        for (i = len2 - 1; i >= 0; i--)    fld.value += aux2.charAt(i);
        fld.value += decSep + aux.substr(len - 4, len);
    }
    return false;
}

function arredondar(valor, casas)
{
	var numberField = valor;
	var rnum = numberField.value;
	var rlength = casas; // The number of decimal places to round to
	
	if (rnum > 8191 && rnum < 10485) //Isso devido a um BUG do Javascript
	{
		rnum = rnum-5000;
		var newnumber = Math.round(rnum * Math.pow(10, rlength)) / Math.pow(10,rlength);
		newnumber = newnumber + 5000;
	}
	else 
	{
		var newnumber = Math.round(rnum * Math.pow(10, rlength)) / Math.pow(10, rlength);
	}
	
	return newnumber;
}

function ExisteBloqueadorPopup()
{
    var mine = window.open('','','width=1,height=1,left=-10,top=-10,scrollbars=no');
    var popUpsBlocked;
    
    if(mine != null)
    {
        if(mine)
        {
            popUpsBlocked = false
        }
        else
        {
            popUpsBlocked = true
        }
        
        mine.close();
    }
    else
    {
        popUpsBlocked = true
    }
    
    if(popUpsBlocked)
    {
        alert('Foi detectado que você está usando bloqueador de popup. Por favor, desabilite o bloqueador, pois algumas funcionalidades do sistema SSDP dependem de popups.');
    }
}

function InserirTelefone(obj)
{
    var nomeLinha = obj.id.replace('imbAdd','linha');
    var nomeTabela = obj.id.replace('imbAdd','tabelaPrincipal');
    var objLinha = document.getElementById(nomeLinha);
    var objTabela = document.getElementById(nomeTabela);
    var tabela = null;
    
    //Clona a tabela
    tabela = objTabela.cloneNode(true);
    
    //Limpa o nome dela
    tabela.setAttribute('id','');
    
    //Limpa a caixa de telefone
    tabela.childNodes(0).childNodes(0).childNodes(0).childNodes(0).value = '';
    
    //Limpa a caixa de ramal
    tabela.childNodes(0).childNodes(0).childNodes(2).childNodes(0).value = '';
    
    //IdTelefone
    tabela.childNodes(0).childNodes(0).childNodes(3).childNodes(0).value = '0';
    
    objLinha.childNodes(1).appendChild(tabela);
    
    return false;
}

function RemoverTelefone(obj)
{
    var nomeLinha = obj.id.replace('imbRem','linha');
    var objLinha = document.getElementById(nomeLinha);
    var qtdTabelas = objLinha.childNodes(1).childNodes.length;
    
    if(qtdTabelas > 1)
    {
        objLinha.childNodes(1).removeChild(objLinha.childNodes(1).childNodes(parseInt(qtdTabelas) - 1));
    }
    
    return false;
}

function ColetarTelefones()
{
    var hddTelefones = null;
    var tabela = null;
    var qtdTabelas = 0;
    var idTipoTelefone = 0;
    var idTelefone = 0;
    var todosTelefones = '';
    
    hddTelefones = document.getElementById('ctl00_ContentPlaceHolder1_hddTels');
    tabela = document.getElementById('ctl00_ContentPlaceHolder1_tblTelefones');
    
    //Pega o valor dos hiddens de tipo de telefone:
    //alert(tabela.rows[i].childNodes(0).getElementsByTagName('input')[0].value);
    
    //Retorna qtas tabelas existem de telefone dentro da linha
    //tabela.rows[i].childNodes(1).getElementsByTagName('table').length
    
    for(i = 0; i < tabela.rows.length; i++)
    {
        idTipoTelefone = tabela.rows[i].childNodes(0).getElementsByTagName('input')[0].value;
        qtdTabelas = tabela.rows[i].childNodes(1).getElementsByTagName('table').length;
        
        for(j = 0; j < qtdTabelas; j++)
        {
            telefone = tabela.rows[i].childNodes(1).childNodes(j).childNodes(0).childNodes(0).getElementsByTagName('input')[0].value;
            ramal = tabela.rows[i].childNodes(1).childNodes(j).childNodes(0).childNodes(0).getElementsByTagName('input')[1].value;
            idTelefone = tabela.rows[i].childNodes(1).childNodes(j).childNodes(0).childNodes(0).getElementsByTagName('input')[2].value;
            
            todosTelefones += idTipoTelefone + ';' + idTelefone + ';' + telefone + ';' + ramal + '|';
        }
    }
    
    hddTelefones.value = todosTelefones;
    
    return true;
}

function ValidarDataDigitacao(pObj)
{
    if(pObj.value != "")
    {
        if(!Data_Valida(pObj))
        {
            alert("Data inválida!");
            event.keyCode = 0;
            pObj.value = '';
            pObj.focus();
        }
    }
}

function Data_Valida(obj)
{
    var data = obj.value;
    var barra1 = data.indexOf('/');
    var barra2 = data.lastIndexOf('/');
    var ano = data.substring(barra2+1, data.length);
    var dia = data.substring(0,barra1);
    var mes = data.substring(barra1+1,barra2);
    var anoMod  = ano%4;
    var mesMod  = mes%2;
    var retorno = true;

    //verifica as barras
    if ((barra1==-1) || (barra1==barra2))
    {
        retorno=false; 
    }
    
    // verifica se os campos dia, ano , mes são numéricos e se possuem a quantidade de caracteres suficientes
    if  ((isNaN(ano)) || (isNaN(dia)) || (isNaN(mes))  || (ano<1900)  || (ano>2200) || (mes < 1)|| (mes > 12) ||(dia > 31)|| (dia < 1) )
    { 
        retorno=false; 
    }
    
    // ferifica o mes de fevereiro
    if ((((anoMod != 0) && (dia > 28)) || ((anoMod==0) && (dia > 29))) && (mes == 2))
    { 
        retorno=false; 
    }
    
    if (mesMod == 1)
    { 
        if  ((mes >= 9) &&  (dia >30))
        {		
            retorno=false; 
        }
    }
    else
    { 
        if  ((mes < 7 ) &&  (dia >30))
        {		
            retorno=false; 
        } 
    }
    
    if ((retorno==false))
    {
        return false; 
    }
    else
    { 
        return (true); 
    }
}

function Arredondar(valor, casas)
{
	//var numberField = valor;
	var rnum = valor;
	var rlength = casas; // The number of decimal places to round to
	
	if (rnum > 8191 && rnum < 10485) //Isso devido a um BUG do Javascript
	{
		rnum = rnum-5000;
		var newnumber = Math.round(rnum * Math.pow(10, rlength)) / Math.pow(10,rlength);
		newnumber = newnumber + 5000;
	}
	else 
	{
		var newnumber = Math.round(rnum * Math.pow(10, rlength)) / Math.pow(10, rlength);
	}
	
	return newnumber;
}

function PesquisarFornecedor()
{
    altura   = 400;
    largura  = 600;
    topo     = (screen.height/2)-(altura/2);
	esquerda = (screen.width/2) - (largura/2);
	
    var ret = window.open('PesquisarFornecedor.aspx?controle1=ctl00_ContentPlaceHolder1_hddIdPessoaFornecedor&controle2=ctl00_ContentPlaceHolder1_hddRazao', "popup",'width=' + largura + ',height=' + altura + ',toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=' + scroll + ',resizable=no,top=' + topo + ',left=' + esquerda);
    
    return false;
}

function MostrarHorariosTurma() {
var objdiv = document.getElementById("divHorariosTurma");

var visibilidade = objdiv.getAttribute("style").display;

if (visibilidade == "none")
{
    objdiv.getAttribute("style").display = "block";
} 
else
{
    objdiv.getAttribute("style").display = "none";
}


return false;
}

function CalcularDesconto()
{
var Resultado = 0;
var ValorConta = parseFloat(document.getElementById("ctl00_ContentPlaceHolder1_txtValor").value);
var Desconto = parseFloat(document.getElementById("ctl00_ContentPlaceHolder1_txtDesconto").value);
var ValorcomDesconto = parseFloat(document.getElementById("ctl00_ContentPlaceHolder1_txtValorcomDesconto").value);

Resultado = ValorConta - ((ValorConta * Desconto)/100);


document.getElementById("ctl00_ContentPlaceHolder1_txtValorcomDesconto").value = Resultado;
alert(Resultado);
//ValorcomDesconto = Resultado;
return false;
}

function ExibirAguarde() {
    /*var divAguarde = document.getElementById('divAguarde');
    var containerLoader = document.getElementById('containerLoader');

    try {
        if (!exibirAguarde) {
            return;
        }
    }
    catch (ex) { }

    if (divAguarde != null) {
        divAguarde.style.display = 'inline';
    }

    if (containerLoader != null) {
        containerLoader.style.display = 'inline';
    }*/

    return true;
}

function OcultarAguarde() {
    var divAguarde = document.getElementById('divAguarde');
    var containerLoader = document.getElementById('containerLoader');

    if (containerLoader != null) {
        containerLoader.style.display = 'none';
    }

    if (divAguarde != null) {
        divAguarde.style.display = 'none';
    }
}

var carregouCookie = false;
var gravandoDados = false;

function SalvarInteressado(container1, container2, container3)
{
    var intervalo1 = window.setInterval(function() {
        GravarDadosInteressado(document.getElementById(container1));
        GravarDadosInteressado(document.getElementById(container2));
        GravarDadosInteressado(document.getElementById(container3));
    }, 2000);
}

function LimparInteressado(container) {
    var interessado = null;

    var lista = document.getElementById(container).getElementsByTagName("*");

    for (i = 0; i < lista.length; i++) {
        if (lista[i].id != '') {
            delCookie(lista[i].id);
        }
    }
    
    return true;
}

function GravarDadosInteressado(container)
{
    var numDias = 10;
    var controles = null;
    var controlesTextArea = null;
    var controlesCombo = null;
    var valor = null;
    
    gravandoDados = true;
    
    controles = container.getElementsByTagName('input');
    controlesTextArea = container.getElementsByTagName('textarea');
    controlesCombo = container.getElementsByTagName('select');
    
    for (var i = 0; i < controles.length; i++) {
        if (controles[i].type == "text") {
            valor = replaceAll(controles[i].value, '(', '');
            valor = replaceAll(valor, ')', '');
            valor = replaceAll(valor, '-', '');
            valor = replaceAll(valor, '_', '');
            
            if (valor != '') {
                setCookie(controles[i].id, valor, numDias);
            }
        }
        else if (controles[i].type == "checkbox") {
            setCookie(controles[i].id, controles[i].checked, numDias);
        }
    }
    
    //Grava os textarea
    for (var i = 0; i < controlesTextArea.length; i++) {
        if (controlesTextArea[i].type == "textarea") {
            valor = controlesTextArea[i].value;
            
            if (valor != '') {
                setCookie(controlesTextArea[i].id, valor, numDias);
            }
        }
    }
    
    //Grava a posicao dos combos
    for (var i = 0; i < controlesCombo.length; i++) {
        valor = controlesCombo[i].selectedIndex;
        
        if (valor > 0) {
            setCookie(controlesCombo[i].id, valor, numDias);
        }
    }
    
    gravandoDados = false;
}

function TratarNomeControleInteressado(nomeControle) {
    var ret = (nomeControle.split(/_/g).length - 1);

    ret = nomeControle.split(/_/g)[ret - 1] + '-' + nomeControle.split(/_/g)[5];

    return ret;
}

function RetornarDadosCookie(container)
{
    var txtConversa;
    var txtNome;
    var txtTelefone1;
    var txtTelefone2;
    var txtEmail;
    var ddlGrauInteresse;
    var ddlTipoContato;
    
    var controles = null;
    var controlesTextArea = null;
    var controlesCombo = null;
    var valor = null;
    
    controles = container.getElementsByTagName('input');
    controlesTextArea = container.getElementsByTagName('textarea');
    controlesCombo = container.getElementsByTagName('select');
    
    for (var i = 0; i < controles.length; i++) {
        if (controles[i].type == "text") {
            //Pula a caixa de busca de interessados
            if (controles[i] == 'search') {
                continue;
            }
            
            //Obtem o valor do cookie e atribui nas caixas de texto
            if (controles[i].id.indexOf('Telefone') > 0) {
                document.getElementById(controles[i].id).value = ' ' + replaceAll(getCookie(controles[i].id), ' ', '');
            }
            else {
                document.getElementById(controles[i].id).value = getCookie(controles[i].id);
            }
        }
        else if (controles[i].type == "checkbox") {
            if (getCookie(controles[i].id) == 'true') {
                document.getElementById(controles[i].id).checked = true;
            }
        }
    }
    
    //Carrega o textarea
    for (var i = 0; i < controlesTextArea.length; i++) {
        if (controlesTextArea[i].type == "textarea") {
            document.getElementById(controlesTextArea[i].id).value = getCookie(controlesTextArea[i].id);
        }
    }

    //Carrega os combos
    for (var i = 0; i < controlesCombo.length; i++) {
        document.getElementById(controlesCombo[i].id).selectedIndex = getCookie(controlesCombo[i].id);
    }
    
    carregouCookie = false;
}

function VerificarInteressadosNaoSalvos(interessado1, interessado2, interessado3)
{
    var intervalo1 = window.setInterval(function() {
        LimparLabelAvisoNaoSalvo();
        VerifInter(interessado1);
        VerifInter(interessado2);
    }, 2000);
}

function LimparLabelAvisoNaoSalvo()
{
    var lbl = document.getElementById('ctl00_ContentPlaceHolder1_lblInteressadoNaoSalvo');
    
    if (lbl != null)
    {
        lbl.innerHTML = '';
    }
}

function VerifInter(pcontainer) {
    var lbl = null;
    var temInteressado = false;

    container = document.getElementById(pcontainer);
    controles = container.getElementsByTagName('input');
    
    for (var i = 0; i < controles.length; i++) {
        if (controles[i].type == "text") {
            valor = replaceAll(controles[i].value, '(', '');
            valor = replaceAll(valor, ')', '');
            valor = replaceAll(valor, '-', '');
            valor = replaceAll(valor, '_', '');
            valor = replaceAll(valor, ' ', '');
            
            if (valor != '') {
                temInteressado = true;
                
                break;
            }
        }
    }
    
    lbl = document.getElementById('lblInteressadoNaoSalvo');

    var tamanho = container.id.split(/_/g).length;
    
    var controleInteressado = container.id.split(/_/g)[tamanho - 2];

    if (temInteressado) {
        lbl.innerHTML = '<font face=tahoma size=3 color=red>Interessado ' + controleInteressado.substring(controleInteressado.length - 1) + ' não salvo<br />';
    }
}

function setCookie(c_name,value,expiredays)
{
    var exdate=new Date();exdate.setDate(exdate.getDate()+expiredays);
    document.cookie=c_name + "=" + escape(value) + ((expiredays == null) ? "" : ";expires="+exdate.toGMTString());
}

function getCookie(c_name)
{
    if (document.cookie.length>0)
    {
        c_start=document.cookie.indexOf(c_name + "=");
        
        if (c_start!=-1)
        { 
            c_start=c_start + c_name.length+1; 
            c_end=document.cookie.indexOf(";",c_start);
            
            if (c_end==-1)
            {
                c_end=document.cookie.length;
            }
            
            return unescape(document.cookie.substring(c_start,c_end));
        }
    }
    
    return "";
}

function delCookie(name)
{
    path = '';
    domain = '';
    
    if (getCookie( name ) ) document.cookie = name + "=" + ( ( path ) ? ";path=" + path : "") + ( ( domain ) ? ";domain=" + domain : "" ) + ";expires=Thu, 01-Jan-1970 00:00:01 GMT";
}




function ImprimirReciboPedidoCompra(idPedido, dataHora)
{
    AbrirPopup2('PedidoCompraReciboLiberacao.aspx?IdPedido=' + idPedido.toString() + '&DataHora=' + dataHora, 800, 600, 1);
}

function ImprimirReciboPedidoCompraImpressora()
{
    var botao = document.getElementById('btnImprimirRecibo');
    
    if(botao != null)
    {
        botao.style.display = 'none';
    
        window.print();
    
        botao.style.display = 'inline';
    }
}

function ValidarPedido(ehFranqueadora)
{
    var ddlFranquias = document.getElementById('ctl00_ContentPlaceHolder1_ddlFranquias');
    var ddlParcelas = document.getElementById('ctl00_ContentPlaceHolder1_ddlParcelas');
    
    if(ehFranqueadora)
    {
        if(ddlFranquias[ddlFranquias.selectedIndex].value == 0)
        {
            alert('Selecione uma franquia');
            ddlFranquias.focus();
            
            return false;
        }
    }
    
    if(ddlParcelas[ddlParcelas.selectedIndex].value == 0)
    {
        alert('Selecione uma opçao de parcelamento');
        ddlParcelas.focus();
        
        return false;
    }
    
    return true;
}


// Largura da Tela visivel
function Largura() {
    try {
        if (BrowserDetect.browser == 'Explorer') {
            if (BrowserDetect.version != 7) { return document.documentElement.clientWidth; }
            else { return screen.Width; }
        }
        else { return window.innerWidth + window.pageXOffset - 18; }
    }
    catch (e) {
        return 1024;
    }
}

// Altura da Tela visivel
function Altura() {
    try {
        if (BrowserDetect.browser == 'Explorer') {
            if (BrowserDetect.version != 7) {
                if (document.documentElement.scrollHeight > document.documentElement.clientHeight) { return document.documentElement.scrollHeight; }
                else { return document.documentElement.clientHeight; }
            }
            else { return screen.Height; }
        }
        else { return window.innerHeight + window.pageYOffset; }
    }
    catch (e) {
        return 768;
    }
}


// Detectando o Browser do Cliente
var BrowserDetect = {
    init: function() {
        this.browser = this.searchString(this.dataBrowser) || "An unknown browser";
        this.version = this.searchVersion(navigator.userAgent) || this.searchVersion(navigator.appVersion) || "an unknown version";
        this.OS = this.searchString(this.dataOS) || "an unknown OS";
    },
    searchString: function(data) {
        for (var i = 0; i < data.length; i++) {
            var dataString = data[i].string;
            var dataProp = data[i].prop;
            this.versionSearchString = data[i].versionSearch || data[i].identity;
            if (dataString) {
                if (dataString.indexOf(data[i].subString) != -1)
                    return data[i].identity;
            }
            else if (dataProp)
                return data[i].identity;
        }
    },
    searchVersion: function(dataString) {
        var index = dataString.indexOf(this.versionSearchString);
        if (index == -1) return;
        return parseFloat(dataString.substring(index + this.versionSearchString.length + 1));
    },
    dataBrowser: [
		  { string: navigator.userAgent, subString: "Chrome", identity: "Chrome" },
		  { string: navigator.userAgent, subString: "OmniWeb", versionSearch: "OmniWeb/", identity: "OmniWeb" },
		  { string: navigator.vendor, subString: "Apple", identity: "Safari" },
		  { prop: window.opera, identity: "Opera" },
		  { string: navigator.vendor, subString: "iCab", identity: "iCab" },
		  { string: navigator.vendor, subString: "KDE", identity: "Konqueror" },
		  { string: navigator.userAgent, subString: "Firefox", identity: "Firefox" },
		  { string: navigator.vendor, subString: "Camino", identity: "Camino" },
		  { string: navigator.userAgent, subString: "Netscape", identity: "Netscape" },
		  { string: navigator.userAgent, subString: "MSIE", identity: "Explorer", versionSearch: "MSIE" },
		  { string: navigator.userAgent, subString: "Gecko", identity: "Mozilla", versionSearch: "rv" },
		  { string: navigator.userAgent, subString: "Mozilla", identity: "Netscape", versionSearch: "Mozilla" }
  ],
    dataOS: [
		  { string: navigator.platform, subString: "Win", identity: "Windows" },
		  { string: navigator.platform, subString: "Mac", identity: "Mac" },
		  { string: navigator.platform, subString: "Linux", identity: "Linux" }
	 ]
};
BrowserDetect.init();


//Exibe Alert e depois redireciona.
function Sucesso() {
alert('Dados gravados com sucesso!');
window.location.href = "Cursos.aspx";
}

///////////////////////////////
//Formata valor teste Fabiano//
///////////////////////////////
addEvent = function(o, e, f, s) {
    var r = o[r = "_" + (e = "on" + e)] = o[r] || (o[e] ? [[o[e], o]] : []), a, c, d;
    r[r.length] = [f, s || o], o[e] = function(e) {
        try {
            (e = e || event).preventDefault || (e.preventDefault = function() { e.returnValue = false; });
            e.stopPropagation || (e.stopPropagation = function() { e.cancelBubble = true; });
            e.target || (e.target = e.srcElement || null);
            e.key = (e.which + 1 || e.keyCode + 1) - 1 || 0;
        } catch (f) { }
        for (d = 1, f = r.length; f; r[--f] && (a = r[f][0], o = r[f][1], a.call ? c = a.call(o, e) : (o._ = a, c = o._(e), o._ = null), d &= c !== false));
        return e = null, !!d;
    }
};

removeEvent = function(o, e, f, s) {
    for (var i = (e = o["_on" + e] || []).length; i; )
        if (e[--i] && e[i][0] == f && (s || o) == e[i][1])
        return delete e[i];
    return false;
};

function formataMoeda(o, n, dig, dec) {
    o.c = !isNaN(n) ? Math.abs(n) : 2;
    o.dec = typeof dec != "string" ? "," : dec, o.dig = typeof dig != "string" ? "." : dig;
    addEvent(o, "keypress", function(e) {
        if (e.key > 47 && e.key < 58) {
            var o, s, l = (s = ((o = this).value.replace(/^0+/g, "") + String.fromCharCode(e.key)).replace(/\D/g, "")).length, n;
            if (o.maxLength + 1 && l >= o.maxLength) return false;
            l <= (n = o.c) && (s = new Array(n - l + 2).join("0") + s);
            for (var i = (l = (s = s.split("")).length) - n; (i -= 3) > 0; s[i - 1] += o.dig);
            n && n < l && (s[l - ++n] += o.dec);
            o.value = s.join("");
        }
        e.key > 30 && e.preventDefault();
    });
}

////////////////////////////
//Mudar cor textbox JQUERY//
////////////////////////////
function AlterarCorCamposJQuery() {
    $(document).ready(function() {
        //$('input[type="text"]').addClass("textbox");
        $('input[type="text"]').focus(function() {
            $(this).removeClass("textbox").addClass("textboxFocus");
        });

        $('textarea').focus(function() {
            $(this).removeClass("textbox").addClass("textboxFocus");
        });

        $('select').focus(function() {
            $(this).removeClass("textbox").addClass("textboxFocus");
        });

        $('input[type="text"]').blur(function() {
            $(this).removeClass("textboxFocus").addClass("textbox");
            /*if ($.trim(this.value) == '') {
                this.value = (this.defaultValue ? this.defaultValue : '');
            }*/
        });
        $('textarea').blur(function() {
            $(this).removeClass("textboxFocus").addClass("textbox");
        });
        $('select').blur(function() {
            $(this).removeClass("textboxFocus").addClass("textbox");
        });
    });
}

function replaceAll(str, from, to) {
    var idx = str.indexOf(from);

    while (idx > -1) {
        str = str.replace(from, to);
        idx = str.indexOf(from);
    }

    return str;
}

function SelecionarEstilo(classe) {
    var elemento = document.getElementById("bg");
    var resolucao = "_" + screen.width + "_" + screen.height;
    if (elemento.className != "") {
        elemento.className = classe + resolucao;
    }
    else {
        elemento.className = "Login01" + resolucao;
    }
    GravarCookieEstilo('Estilo', classe + resolucao, '90');
}

function GravarCookieEstilo(strCookie, strValor, lngDias) {
    var dtmData = new Date();
    if (lngDias) {
        dtmData.setTime(dtmData.getTime() + (lngDias * 24 * 60 * 60 * 1000));
        var strExpires = "; expires=" + dtmData.toGMTString();
    }
    else {
        var strExpires = "";
    }
    document.cookie = strCookie + "=" + strValor + strExpires + "; path=/";
}

// Função para ler o cookie.
function LerCookie(strCookie) {
    var strNomeIgual = strCookie;  //+ "=";
    var arrCookies = document.cookie.split(';');

    for (var i = 0; i < arrCookies.length; i++) {
        var strValorCookie = arrCookies[i];
        while (strValorCookie.charAt(0) == ' ') {
            strValorCookie = strValorCookie.substring(1, strValorCookie.length);
        }
        if (strValorCookie.indexOf(strNomeIgual) == 0) {
            //return strValorCookie.substring(strNomeIgual.length, strValorCookie.length);
            var teste = strValorCookie.substring(7, strValorCookie.length);
            document.getElementById("bg").className = strValorCookie.substring(7, strValorCookie.length);
        }
    }
    return null;
}

function MaxlengthJS(objText) {
    var txt = null;
    var valor = null;
    var maximo = 0;
    var tamanho = 0;

    txt = $('#' + objText.id);

    valor = replaceAll(txt.val(), ',', '');
    valor = replaceAll(valor, '.', '');

    maximo = parseInt(txt.attr('tamanhomaximo'));
    tamanho = parseInt(valor.length);

    if (tamanho >= maximo) {
        window.event.keyCode = 0;

        return false;
    }

    return true;
}

function CalcularValorReajusteProdutoPrecoVenda(rdbPorcentagem, rdbValor, txtValor, lblValorFinal, hddValor) {
    var txt = null;
    var lbl = null;
    var rdbP = null;
    var rdbV = null;
    var valor = 0;
    var hdd = null;
    var valorAtual = 0;
    var valorDigitado = 0;

    txt = document.getElementById(txtValor);
    lbl = document.getElementById(lblValorFinal);
    rdbP = document.getElementById(rdbPorcentagem);
    rdbV = document.getElementById(rdbValor);
    hdd = document.getElementById(hddValor);
    valorAtual = parseFloat(hdd.value.replace('.', '').replace(',', '.'));
    valorDigitado = parseFloat(txt.value.replace('.', '').replace(',', '.'));

    //Calcula o valor ou a porcentagem
    if (rdbP.checked) {
        valor = valorAtual + (valorAtual * (valorDigitado / 100));
    }
    else if (rdbV.checked) {
        valor = parseFloat(valorAtual) + parseFloat(valorDigitado);
    }

    //Formata e exibe o valor
    if (!isNaN(valor)) {
        valor = valor.toString().replace('.', ',');

        if (valor.indexOf('.') < 0 && valor.indexOf(',') < 0) {
            valor += ',00';
        }
        else {
            valor = valor.toString().replace('.', ',');
        }
        
        lbl.innerHTML = 'R$ ' + valor;
    }
    else {
        lbl.innerHTML = '0,00';
    }
}

function AtualizarValorProdutoCotacaoSession(idProduto, idPessoaFornecedor, txtValor) {
    var txt = document.getElementById(txtValor);
    var valor = 0;

    valor = txt.value.toString().replace('.', '').replace(',', '.');

    valor = parseFloat(valor);

    ExibirAguarde();
    
    JQueryAjaxSetup();

    $.get("CompraCotacaoAtualizarValorProdutoSession.ashx", { idProduto: idProduto, idPessoaFornecedor: idPessoaFornecedor, valor: valor },
      function(data) {
          if (data == 'ok') {

          }
          else {
              alert(data);
          }

          OcultarAguarde();
      });

}


function JQueryAjaxSetup() {
    $.ajaxSetup({ contentType: "application/x-www-form-urlencoded;charset=iso-8859-1",
        cache: false
    });
}

/*
Exemplo: accordion('.accordion li h3');
<div class="accordion">
	<li>
	    <h3>Titulo 1</h3>
		<div>
			Conteudo
		</div>
	</li>
	<li>
	    <h3>Titulo 2</h3>
		<div>
			Conteudo
		</div>
	</li>
</div>
*/
function accordion(elemento) {
    $(elemento).click(function() {
        /*
        testando pra ver se o proximo o
        elemento do accordion tem a classe aberto
        */
        if ($(this).next().is('.aberto')) {
            return false;
        } else {
            /*
            caso o elemento nao possua a classe aberto
            eu removo a propriedade class de todos os elementos 
            que formam o accordion, e defindo ele apenas pro elemento
            que vai ser aberto
            */
            $(elemento).next().hide('slow').removeAttr('class');
            $(this).next().toggle('slow').attr('class', 'aberto');
        }
        return false;
    }).next().hide()
}

function ReajustePrecoDiferencaValor(txtValor, hddValor, lblValorFinal, lblPorcentagemFinal, chkSel) {
    var txt = document.getElementById(txtValor);
    var hdd = document.getElementById(hddValor);
    var lblV = document.getElementById(lblValorFinal);
    var lblP = document.getElementById(lblPorcentagemFinal);
    var chk = document.getElementById(chkSel);
    var valor = 0;
    var valorP = 0;
    var valorOriginal = 0;

    valor = moeda.desformatar(txt.value);
    valorOriginal = moeda.desformatar(hdd.value);

    //Calcula a diferenca de valor
    valor = parseFloat(valor) - parseFloat(valorOriginal);

    //Calcula a diferenca de porcentagem
    valorP = moeda.arredondar(    100 - (100 - ((valor * 100) / valorOriginal)) );

    lblV.innerHTML = 'R$ ' + moeda.arredondar(valor);
    lblP.innerHTML = valorP + ' %';
    chk.checked = 1;
}





/**
* moeda
* 
* @abstract Classe que formata de desformata valores monetários em float e formata valores 
* de float em moeda.
* 
* @author anselmo
* 
* @example 
* 		moeda.formatar(1000) 
*      	>> retornar 1.000,00
* 		moeda.desformatar(1.000,00) 
* 			>> retornar 1000
* 
* @version 1.0
**/
var moeda = {

    /**
    * retiraFormatacao
    * 
    * Remove a formatação de uma string de moeda e retorna um float
    * 
    * @param {Object} num
    */
    desformatar: function(num) {
        num = num.replace(".", "");

        num = num.replace(",", ".");

        return parseFloat(num);
    },

    /**
    * formatar
    * 
    * Deixar um valor float no formato monetário
    * 
    * @param {Object} num
    */
    formatar: function(num) {
        x = 0;

        if (num < 0) {
            num = Math.abs(num);
            x = 1;
        }

        if (isNaN(num)) num = "0";
        cents = Math.floor((num * 100 + 0.5) % 100);

        num = Math.floor((num * 100 + 0.5) / 100).toString();

        if (cents < 10) cents = "0" + cents;
        for (var i = 0; i < Math.floor((num.length - (1 + i)) / 3); i++)
            num = num.substring(0, num.length - (4 * i + 3)) + '.'
	               + num.substring(num.length - (4 * i + 3));

        ret = num + ',' + cents;

        if (x == 1) ret = ' - ' + ret; return ret;
    },

    /**
    * arredondar
    * 
    * @abstract Arredonda um valor quebrado para duas casas decimais.
    * 
    * @param {Object} num
    */
    arredondar: function(num) {
        var ret = 0;
        var posSeparador = 0;
        var parte1 = 0;
        var parte2 = 0;

        ret = Math.round(num * Math.pow(10, 2)) / Math.pow(10, 2);

        if (ret.toString().indexOf(',') < 0 &&
            ret.toString().indexOf('.') < 0) {
            return ret + ',00';
        }

        //Verifica a qtde de casas depois do separador decimal
        posSeparador = ret.toString().indexOf('.');

        parte1 = ret.toString().substring(0, posSeparador);
        parte2 = ret.toString().substring(posSeparador);

        //Coloca o zero no final, caso necessario
        if (parte2.length <= 2) {
            parte2 = parte2 + '0';
        }

        ret = parte1 + ',' + parte2.replace('.', '');

        return ret;
    }
}

function DivInformacao(msg) {
    var div = document.getElementById('divAlerta');
    var divTxt = document.getElementById('divAlertaTexto');

    divTxt.innerHTML = msg;
    $(div).addClass('divAlertaInformacao');
    $('#imgIcone').attr('src', 'imagens/paginas/information.png');
    $('#imgIcone').css('margin-right', '10px');
    //$(div).css('display', 'block');
    $(div).slideDown('slow');

    window.setTimeout(DivInformacaoEsconde, 3000);
}

function DivErro(msg) {
    var div = document.getElementById('divAlerta');
    var divTxt = document.getElementById('divAlertaTexto');

    divTxt.innerHTML = msg;
    $(div).addClass('divAlertaErro');
    $('#imgIcone').attr('src', 'imagens/paginas/exclamation.png');
    $('#imgIcone').css('margin-right', '10px');
    $(div).css('display', 'block');
}

function DivInformacaoEsconde() {
    var div = document.getElementById('divAlerta');
    var divTxt = document.getElementById('divAlertaTexto');

    divTxt.innerHTML = '';
    //$(div).css('display', 'none');
    $(div).hide('slow');
}

function debug(msg) {
    document.getElementById('divAlerta').innerHTML += new Date().getHours().toString() + ':' + new Date().getMinutes().toString() + ':' + new Date().getSeconds().toString() + ' - ' + msg + '<br />';
}

function debugLimpar() {
    document.getElementById('divAlerta').innerHTML = '';
}

function EditarAcesso(menu, hddIdItemTree) {
    //window.location.href = 'PerfilSistema.aspx?iditem=' + menu;

    document.getElementById(hddIdItemTree).value = menu.toString().split('&')[0];

    __doPostBack('editarItem', null);
}

function AvisoPreMatricula(frase, idPessoaAluno) {
    alert(frase);
    ExibirAguarde();
    window.location.href = 'PessoaAluno.aspx?id=' + idPessoaAluno;

    topo = (screen.height / 2) - (650 / 2);
    esquerda = (screen.width / 2) - (800 / 2);

    window.moveTo(esquerda, topo);
    window.resizeTo(800, 650);

    ExibirAguarde();
}

function CriarTabs() {
    var listaFls = $('fieldset[rel="tab"]');
    var indiceTab = 0;
    var exibiuErro = false;
    var ativouPrimeiroTab = false;
    
    //Caso tenha elementos na pagina que podem ser tabpanels
    if (listaFls.length >= 1) {
        //Exibe somente o primeiro Fieldset
        $(listaFls[0]).css('display', 'block');

        for (i = 0; i < listaFls.length; i++) {
            var lnk = $("<a>" + $(listaFls[i]).children('[class="fieldsetLegend"]').text().trim() + "</a>").attr('href', '#');

            lnk.attr('numFls', i);

            lnk.click(function() {
                for (i = 0; i < listaFls.length; i++) {
                    $(listaFls[i]).hide();
                }

                indiceTab = $(this).attr('numFls');
                ativouPrimeiroTab = true;

                $(listaFls[indiceTab]).show('fade');

                $('#tabs a').removeClass('divTabAtivo');

                $(this).addClass('divTabAtivo');

                setCookie('indiceTab', indiceTab, 1);
            });

            var espaco = "<span>&nbsp;&nbsp;</span>"
            //<div id="tabs"></div>
            if ($('#tabs').length == 0 && !exibiuErro) {
                alert('Faltou criar um DIV da seguinte forma: <div id=tabs></div> no local onde você deseja que apareça a TAB');
                exibiuErro = true;
            }
            
            $('#tabs').append(lnk);
            $('#tabs').append(espaco);
        }

        if (!ativouPrimeiroTab && isPostBack) {
            $('#tabs a:first').addClass('divTabAtivo');
            ativouPrimeiroTab = true;
        }
    }

    if (!isPostBack) {
        setCookie('indiceTab', 0, 1);
    }
    else {
        for (i = 0; i < listaFls.length; i++) {
            $(listaFls[i]).hide();
        }

        indiceTab = getCookie('indiceTab');

        $(listaFls[indiceTab]).show();
    }
}

function EditarMenu(url) {
    window.location.href = 'LojaVirtualDepartamentos.aspx?iditem=' + url;
}





function LimparExibiuListaCepUnico() {
    $("#ctl00_ContentPlaceHolder1_hddExibiuListaCepUnico").val('');
}

function BuscarCEP(cep, urlProvedor) {
    var endereco = null;
    var qtdEnderecos = 0;
    var contador = 0;

    if ($("[id$=hddExibiuListaCepUnico]").val() == "1") {
        return;
    }

    cep = replaceAll(cep, '-', '');
    cep = replaceAll(cep, ' ', '');
    
    urlProvedor = 'Handlers/Logradouro.ashx';
    
    if (cep.length == 0) {
        $('[id$=hddProblemaNoCep]').val('');

        $('[id$=ddlCidade]').children().remove().end().append('<option selected value="0">Selecione</option>');

        $('[id$=txtEndereco]').attr('disabled', 'disabled');
        $('[id$=txtBairro]').attr('disabled', 'disabled');
        $('[id$=txtCidade]').attr('disabled', 'disabled');
        $('[id$=ddlEstado]').attr('disabled', 'disabled');
        $('[id$=ddlCidade]').attr('disabled', 'disabled');
        $('[id$=txtNumeroEndereco]').attr('disabled', 'disabled');
        $('[id$=txtComplementoEndereco]').attr('disabled', 'disabled');
        $('[id$=txtReferencia]').attr('disabled', 'disabled');
        $('[id$=txtEndereco]').attr('value', '');
        $('[id$=txtBairro]').attr('value', '');
        $('[id$=txtComplementoEndereco]').attr('value', '');
        $('[id$=txtReferencia]').attr('value', '');
        $('[id$=txtNumeroEndereco]').attr('value', '');
        $('[id$=ddlEstado]').find("option[index='0']").attr("selected", "selected");
        $('[id$=ddlCidade]').find("option[index='0']").attr("selected", "selected");
        return;
    }

    JQueryAjaxSetup();
    
    $.get(urlProvedor, { ceps: cep, tipo: 1 },
      function (data) {
          if (data.length > 4 &&
              data.substring(0, 4) == "erro") {
              alert(data);

              return;
          }
          
          qtdEnderecos = $(data).find("Logradouro").length;

          if (qtdEnderecos == 0) {
              if ($('[id$=hddExibiuAvisoCep]').val() == "1") {
                  return;
              }

              if (confirm('CEP não encontrado. Deseja usá-lo mesmo assim?\n\nClique em OK para SIM')) {
                  $('[id$=hddExibiuAvisoCep]').val('1');

                  $('[id$=txtEndereco]').attr('disabled', false);
                  $('[id$=txtBairro]').attr('disabled', false);
                  $('[id$=txtCidade]').attr('disabled', false);
                  $('[id$=ddlEstado]').attr('disabled', false);
                  $('[id$=ddlCidade]').attr('disabled', false);
                  $('[id$=txtNumeroEndereco]').attr('disabled', false);
                  $('[id$=txtComplementoEndereco]').attr('disabled', false);
                  $('[id$=txtReferencia]').attr('disabled', false);
                  $('[id$=ddlEstado]').find("option[index='0']").attr("selected", "selected");
                  $('[id$=ddlCidade]').children().remove().end().append('<option selected value="0">Selecione</option>');
                  $('[id$=txtEndereco]').focus();
                  $('[id$=hddProblemaNoCep]').val('1');
              }
              else {
                  $('[id$=hddExibiuAvisoCep]').val('1');

                  $('[id$=txtCEP]').val('');
                  $('[id$=txtCEP]').focus();

                  $('[id$=hddProblemaNoCep]').val('');

                  $('[id$=ddlCidade]').children().remove().end().append('<option selected value="0">Selecione</option>');

                  $('[id$=txtEndereco]').attr('disabled', false);
                  $('[id$=txtBairro]').attr('disabled', false);
                  $('[id$=txtCidade]').attr('disabled', false);
                  $('[id$=ddlEstado]').attr('disabled', false);
                  $('[id$=ddlCidade]').attr('disabled', false);
                  $('[id$=txtNumeroEndereco]').attr('disabled', false);
                  $('[id$=txtComplementoEndereco]').attr('disabled', false);
                  $('[id$=txtReferencia]').attr('disabled', false);
                  $('[id$=txtEndereco]').attr('value', '');
                  $('[id$=txtBairro]').attr('value', '');
                  $('[id$=txtComplementoEndereco]').attr('value', '');
                  $('[id$=txtReferencia]').attr('value', '');
                  $('[id$=txtNumeroEndereco]').attr('value', '');
                  $('[id$=ddlEstado]').find("option[index='0']").attr("selected", "selected");
                  $('[id$=ddlCidade]').find("option[index='0']").attr("selected", "selected");
              }

              return;
          }
          else if (qtdEnderecos == 1) {
              $('[id$=hddProblemaNoCep]').val('');
              $('[id$=hddExibiuAvisoCep]').val('');

              $('[id$=txtEndereco]').attr('disabled', false);
              $('[id$=txtBairro]').attr('disabled', false);
              $('[id$=txtCidade]').attr('disabled', false);
              $('[id$=ddlEstado]').attr('disabled', false);
              $('[id$=ddlCidade]').attr('disabled', false);
              $('[id$=txtNumeroEndereco]').attr('disabled', false);
              $('[id$=txtComplementoEndereco]').attr('disabled', false);
              $('[id$=txtReferencia]').attr('disabled', false);
              $('[id$=txtNumeroEndereco]').focus();
              $('[id$=txtEndereco]').attr('value', $(data).find("Logradouro").attr('Endereco'));
              $('[id$=txtBairro]').attr('value', $(data).find("Logradouro").attr('Bairro'));

              $("[id$=ddlEstado] option").each(function () { this.selected = $(this).text() == $(data).find('Logradouro').attr('Estado'); });
              $('[id$=ddlEstado]').change();

              $('[id$=hddIdCidade]').val($(data).find('Logradouro').attr('IdLogradouroCidade'));
          }
          else if (qtdEnderecos > 1) {
              $("#divCepUnico").modal();

              //Cria a tabela de acordo com a qtd de enderecos retornados
              tbody = $('#tabelaCeps');

              $(data).find("Logradouro").each(function () {
                  contador++;

                  var trow = $("<tr>");
                  var cor = (contador % 2 == 0 ? "tabelaCepsLinhaEven" : "tabelaCepsLinhaOdd");
                  var endereco = $(this).attr("Endereco");
                  var bairro = $(this).attr("Bairro");
                  var cidade = $(this).attr("Cidade");
                  var estado = $(this).attr("Estado");
                  var idLogradouroCidade = $(this).attr("IdLogradouroCidade");

                  //Endereco
                  $("<td>").addClass(cor).text(endereco).appendTo(trow);

                  //Bairro
                  $("<td>").addClass(cor).text(bairro).appendTo(trow);

                  //Cidade
                  $("<td>").addClass(cor).text(cidade).appendTo(trow);

                  //Estado
                  $("<td>").addClass(cor).text(estado).appendTo(trow);

                  //Selecionar
                  $("<td>").addClass(cor).append('<img style="cursor:hand;cursor:pointer;" src="imagens/accept.png" title="Usar este endereço" />').click(function () {
                      SetarEnderecoModal(endereco,
                                         bairro,
                                         cidade,
                                         estado,
                                         idLogradouroCidade);

                      $.modal.close();
                      $("[id$=hddExibiuListaCepUnico]").val('1');

                  }).appendTo(trow);

                  trow.appendTo(tbody);
              });
          }

          $(data).find("Logradouro").each(function () {
              //var link = $(this).find("link").attr("href");
              //alert('aa');
          });
      });
  }

  function SetarEnderecoModal(endereco, bairro, cidade, estado, idLogradouroCidade) {
      $('[id$=hddProblemaNoCep]').val('');
      $('[id$=hddExibiuAvisoCep]').val('');

      $('[id$=txtEndereco]').attr('disabled', false);
      $('[id$=txtBairro]').attr('disabled', false);
      $('[id$=ddlEstado]').attr('disabled', false);
      $('[id$=ddlCidade]').attr('disabled', false);
      $('[id$=txtNumeroEndereco]').attr('disabled', false);
      $('[id$=txtComplementoEndereco]').attr('disabled', false);
      $('[id$=txtReferencia]').attr('disabled', false);

      /*$('#').removeAttr('disabled');
      $('#').removeAttr('disabled');
      $('#').removeAttr('disabled');
      $('#').removeAttr('disabled');
      $('#').removeAttr('disabled');*/

      $('[id$=txtNumeroEndereco]').focus();

      $('[id$=txtEndereco]').attr('value', endereco);
      $('[id$=txtBairro]').attr('value', bairro);

      $("[id$=ddlEstado] option").each(function () { this.selected = $(this).text() == estado; });
      $('[id$=ddlEstado]').change();

      $('[id$=hddIdCidade]').val(idLogradouroCidade);
  }

  function PopularComboCidade(idEstado, urlProvedor) {
      var endereco = null;
      var qtdEnderecos = 0;
      var option = null;

      JQueryAjaxSetup();
      
      urlProvedor = 'Handlers/Logradouro.ashx';

      $('#imgLoadCidades').show();

      $.get(urlProvedor, { idEstado: idEstado, tipo: 4 },
          function (data) {
              $('[id$=ddlCidade]').children().remove().end().append('<option selected value="0">Selecione</option>');
              
              if ($(data).find("Logradouro").length > 0) {
                  $(data).find("Logradouro").each(function () {
                      $('[id$=ddlCidade]').append("<option value='" + $(this).attr('idlogradourocidade') + "'>" + $(this).attr('nome') + "</option>");
                  });

                  if ($('[id$=hddIdCidade]').val() > 0) {
                      $('[id$=ddlCidade]').find("option[value='" + $('[id$=hddIdCidade]').val() + "']").attr("selected", "selected");
                  }

                  $('#imgLoadCidades').hide();
              }
          }
      );
}

function GravarCidadeSelecionadaCadastro(idCidade) {
    $('[id$=hddIdCidade]').val(idCidade);
}

function ExibirPopupPagamento(chave, espera) {
    if (espera) {
        setTimeout(function () {
            if (confirm('Pedido ainda não pago, deseja efetuar o pagamento?\n\nClique em OK para SIM')) {
                window.open('PedidoPagamentoPagSeguro.aspx?chave=' + chave);

                /*$('#ifPagamento').attr('src', 'PedidoPagamentoPagSeguro.aspx?chave=' + chave);
                $('#ifPagamento').attr('width', '900px');
                $('#ifPagamento').attr('height', '450px');
                $("#divPagto").modal();

                setTimeout(function () {
                    $('#divPagtoAguarde').hide();
                }, 2000);*/
            }

        }, 1500);
    }
    else {
        if (confirm('Pedido ainda não pago, deseja efetuar o pagamento?\n\nClique em OK para SIM')) {
            /*$('#ifPagamento').attr('src', 'PedidoPagamentoPagSeguro.aspx?chave=' + chave);
            $('#ifPagamento').attr('width', '900px');
            $('#ifPagamento').attr('height', '450px');
            $("#divPagto").modal();

            setTimeout(function () {
                $('#divPagtoAguarde').hide();
            }, 2000);*/

            window.open('PedidoPagamentoPagSeguro.aspx?chave=' + chave);
        }
    }

    return false;
}

function ValidarCPFCNPJjQuery(field, rules, i, options) {
    var valor = null;
    var res = false;
    
    valor = replaceAll(replaceAll(replaceAll(replaceAll(field.val(), '.', ''), '-', ''), '/', ''), ' ', '');

    if (valor.length == 10 || valor.length == 11) {
        res = valida_cpf(valor);
    }
    else if (valor.length == 13 || valor.length == 14) {
        res = valida_cnpj(valor);
    }

    if (!res) {
        return options.allrules.validarCPFCNPJ.alertText;
    }
}

function valida_cnpj(cnpj)
      {
      var numeros, digitos, soma, i, resultado, pos, tamanho, digitos_iguais;
      digitos_iguais = 1;
      if (cnpj.length < 14 && cnpj.length < 15)
            return false;
      for (i = 0; i < cnpj.length - 1; i++)
            if (cnpj.charAt(i) != cnpj.charAt(i + 1))
                  {
                  digitos_iguais = 0;
                  break;
                  }
      if (!digitos_iguais)
            {
            tamanho = cnpj.length - 2
            numeros = cnpj.substring(0,tamanho);
            digitos = cnpj.substring(tamanho);
            soma = 0;
            pos = tamanho - 7;
            for (i = tamanho; i >= 1; i--)
                  {
                  soma += numeros.charAt(tamanho - i) * pos--;
                  if (pos < 2)
                        pos = 9;
                  }
            resultado = soma % 11 < 2 ? 0 : 11 - soma % 11;
            if (resultado != digitos.charAt(0))
                  return false;
            tamanho = tamanho + 1;
            numeros = cnpj.substring(0,tamanho);
            soma = 0;
            pos = tamanho - 7;
            for (i = tamanho; i >= 1; i--)
                  {
                  soma += numeros.charAt(tamanho - i) * pos--;
                  if (pos < 2)
                        pos = 9;
                  }
            resultado = soma % 11 < 2 ? 0 : 11 - soma % 11;
            if (resultado != digitos.charAt(1))
                  return false;
            return true;
            }
      else
            return false;
      } 


function valida_cpf(cpf) {
    var numeros, digitos, soma, i, resultado, digitos_iguais;
    digitos_iguais = 1;
    if (cpf.length < 11)
        return false;
    for (i = 0; i < cpf.length - 1; i++)
        if (cpf.charAt(i) != cpf.charAt(i + 1)) {
            digitos_iguais = 0;
            break;
        }
    if (!digitos_iguais) {
        numeros = cpf.substring(0, 9);
        digitos = cpf.substring(9);
        soma = 0;
        for (i = 10; i > 1; i--)
            soma += numeros.charAt(10 - i) * i;
        resultado = soma % 11 < 2 ? 0 : 11 - soma % 11;
        if (resultado != digitos.charAt(0))
            return false;
        numeros = cpf.substring(0, 10);
        soma = 0;
        for (i = 11; i > 1; i--)
            soma += numeros.charAt(11 - i) * i;
        resultado = soma % 11 < 2 ? 0 : 11 - soma % 11;
        if (resultado != digitos.charAt(1))
            return false;
        return true;
    }
    else
        return false;
}

function CompartilharFacebook(url) {
    AbrirPopup2(url, 600, 400, '0');
}

function CompartilharTwitter(url) {
    AbrirPopup2(url, 600, 250, '0');
}

function ValidarBusca() {
    var texto = null;

    texto = replaceAll($('#ctl00_WUC_Pesquisa_Produto1_txtPesquisa').val(), ' ', '');
    texto = replaceAll(texto, 'Produto', '');

    if (texto.length < 2) {

        alert('Digite pelo menos 2 letras');

        $('#ctl00_WUC_Pesquisa_Produto1_txtPesquisa').focus();

        return false;
    }

    return true;
}
