// width to resize large images to
var maxWidth=200;
// height to resize large images to
var maxHeight=200;
// valid file types
var fileTypes=["gif","jpg","jpeg"];
// the id of the preview image tag
var outImage="previewField";
// what to display when the image is not valid
var defaultPic="spacer.gif";
// what to display when the image is not valid
var img="";
// 
var globalPic;

function preview(what, ind){
    outImage='';
    outImage="previewField";
   	outImage=outImage+ind;
    var source=what.value;
	var ext=source.substring(source.lastIndexOf(".")+1,source.length).toLowerCase();
	img = what;

	for (var i=0; i<fileTypes.length; i++) if (fileTypes[i]==ext) break;
	     globalPic=new Image();
     if (i<fileTypes.length) 
		 globalPic.src=source;
     else {
	     globalPic.src=defaultPic;
         alert("IMAGEM INVÁLIDA \nPor favor carregue uma imagem com umas das extensões:\n\n"+fileTypes.join(", "));
	 }

     setTimeout("applyChanges()",200);
}

  function mascara_hora(campo, event){
	  var keyCode = event.keyCode ? event.keyCode : event.which ? event.which : event.charCode;
	  if(campo.value.length == 2 && keyCode != 8) 
	  	return campo.value = campo.value+':';
  } 
   
function applyChanges(){
	 var field=document.getElementById(outImage);
	 var x=parseInt(globalPic.width);
	 var y=parseInt(globalPic.height);

	 if (x>maxWidth) {
	 	 y*=maxWidth/x;
         x=maxWidth;
	 }
	 if (y>maxHeight) {
         x*=maxHeight/y;
         y=maxHeight;
	 }

	 field.style.display = (x<1 || y<1)?"none":"";
	 field.src=globalPic.src;
	 field.width=x;
	 field.height=y;
}

/** 
 * Função que formata um campo do formulário de 
 * acordo com a máscara informada... 
 *
 * Parâmetros: 
 *  => objForm (o Objeto Form);
 *  => strField (string contendo o nome do textbox); 
 *  => sMask (mascara que define o formato que o dado será apresentado, 
 *            usando o algarismo "9" para definir números e o símbolo "!" para 
 *            qualquer caracter... 
 *  => evtKeyPress (evento);
 *
 * Uso..: <input type="textbox" name="xxx" 
 * onkeypress="return txtBoxFormat(document.rcfDownload, 'str_cep', '99999-999', event);"> 
 * 
 * Observação: As máscaras podem ser representadas como os exemplos abaixo: 
 * CEP -> 99.999-999  
 * CPF -> 999.999.999-99 
 * RG -> 99.999.999-9
 * CNPJ -> 99.999.999/9999-99 
 * Data -> 99/99/9999 
 * Tel Resid -> (99) 999-9999 
 * Tel Cel -> (99) 9999-9999 
 * Processo -> 99.999999999/999-99 
 * Inscrição Estadual -> 999.999.999-9999
 * C/C -> 999999-! 
 * E por aí vai... 
 **/
function format(field, sMask, evtKeyPress) {

   var i;
   var nCount;
   var sValue;
   var fldLen;
   var mskLen;
   var bolMask;
   var sCod;
   var nTecla;

   if(document.all) { // Internet Explorer
      nTecla = evtKeyPress.keyCode; 
   }
   else 
   if(document.layers) { // Nestcape
      nTecla = evtKeyPress.which;
   }

   sValue = field.value;

   // Limpa todos os caracteres de formatação que
   // já estiverem no campo.
   sValue = sValue.toString().replace( "-", "" );
   sValue = sValue.toString().replace( "-", "" );
   sValue = sValue.toString().replace( ".", "" );
   sValue = sValue.toString().replace( ".", "" );
   sValue = sValue.toString().replace( "/", "" );
   sValue = sValue.toString().replace( "/", "" );
   sValue = sValue.toString().replace( "(", "" );
   sValue = sValue.toString().replace( "(", "" );
   sValue = sValue.toString().replace( ")", "" );
   sValue = sValue.toString().replace( ")", "" );
   sValue = sValue.toString().replace( " ", "" );
   sValue = sValue.toString().replace( " ", "" );
   sValue = sValue.toString().replace( ":", "" );
  
   fldLen = sValue.length;
   mskLen = sMask.length;

   i = 0;
   nCount = 0;
   sCod = "";
   mskLen = fldLen;

   while (i <= mskLen) 
   {
       bolMask = ((sMask.charAt(i) == "-") || (sMask.charAt(i) == ".") || (sMask.charAt(i) == "/"))
       bolMask = bolMask || ((sMask.charAt(i) == "(") || (sMask.charAt(i) == ")") || (sMask.charAt(i) == " "))

       if (bolMask) 
	   {  sCod += sMask.charAt(i);
          mskLen++; 
	   }
       else {
         sCod += sValue.charAt(nCount);
         nCount++;
       }
       i++;
   }

   field.value = sCod;
   if (nTecla != 9 && nTecla != 8 && nTecla != 46)  {
       if (sMask.charAt(i-1) == "9")  // apenas números...
	   {   return ((nTecla > 47) && (nTecla < 58)); // números de 0 a 9
	   } 
       else { // qualquer caracter...
         return true;
       } 
   }
   else {
       return true;
   }
}

function trocaLinkPgto(div) {
    document.getElementById(div).innerHTML="CASO N&Atilde;O TENHA CONCLU&Iacute;DO O PAGAMENTO,<br /> CLIQUE AQUI PARA ABRIR NOVA CONEX&Atilde;O COM A OPERADORA DO CART&Atilde;O";
}


/**
 *  Função Usada para habilitar os campos que estão checados
 **/
function habilitarTodosCampos() {
	var listElementos  = document.forms[0].elements;
    var totalElementos = document.forms[0].elements.length
   
    for (i=0; i<totalElementos; i++) {
         elemento = listElementos[i];
         if (elemento.type == "text" || elemento.type == "select-one" || elemento.type == "textarea")
         {   if (elemento.value != "" && elemento.value != "0")
         	 {   elemento.disabled=false;
         	 }	
         }
    }
}

function ChecarTodosCampos() {
	var listElementos  = document.forms[0].elements;
    var totalElementos = document.forms[0].elements.length
   
    for (i=0; i<totalElementos; i++) {
         elemento = listElementos[i];
         if (elemento.type == "checkbox"){ 
		 	 if (elemento.checked==false){
				 elemento.checked=true;
         	 }
			 else{
				 elemento.checked=false;
			 }
         }
    }
}


function Abre_Pop(theURL) { //v2.0
  window.open(theURL,'janela','width=330 height=300 scrollbars=yes');
}
function Abre_Pop_News(theURL,id) { //v2.0
  window.open(theURL+"?id="+id,'janela','width=330 height=300 scrollbars=yes');
}

/**
 *  Função usada para abrir Help dos formulários.
 *  Parametro usado(url) caminho do help.
 **/
function popup(url, w, h) {
    var lado = (screen.width - w) / 2;
    var topo = (screen.height - h) / 2;
    janela = window.open(url, '', 'height='+h+', width='+w+', top='+topo+', left='+lado+', scrollbars=yes');		
	janela.focus();
}

/**
 *
 */
function acender(linha) {
	if ( navigator.appName == "Netscape" ) linha.bgColor = "#e5e5e5"
    else linha.style.backgroundColor = "#e5e5e5";
}

/**
 *
 */
function apagar(linha) {
	if ( navigator.appName == "Netscape" ) linha.bgColor = "#f5f5f5"
    else linha.style.backgroundColor = "#f5f5f5";
}

/**
 *
 */
function mostrarLinhas(obj) {
	if(document.getElementById(obj).style.display == "") {
		document.getElementById(obj).style.display = "none";
	}
	else {
		document.getElementById(obj).style.display = "";
	}
}

/**
 * 
 */
function deletar(on_off) {
    if (on_off == false) {
	    if (!confirm('Caro(a) Usuário, todas as informações deste Registro serão excluídas do Banco de Dados.\n\n\ Confirma a exclusão deste Registro ?')) {
		     return false;
    	}
    }
	else {
	    if (!confirm('Caro(a) Usuário, todas as informações deste Registro serão excluídas do Banco de Dados.\n Caso queira desativar temporariamente utilize a Ação ON/OFF.\n\n\ Confirma a exclusão deste Registro ?')) {
	        return false;
		}
    }
}

/**
 * 
 */
function soNumero(event){
	var keyCode = event.keyCode ? event.keyCode : event.which ? event.which : event.charCode;
	var caract = new RegExp(/^[0-9]+$/i);
	var caract = caract.test(String.fromCharCode(keyCode));
	parseInt(keyCode);
    if (keyCode != 9 && keyCode != 8 && keyCode != 46 && keyCode != 13 && keyCode != 12){
		if(!caract){
			keyCode=0;
			return false;
		}
	}
}

/**
 * 
 */
function mostra_oculta(obj) {
	if(document.getElementById(obj).style.display == "") {
	   document.getElementById(obj).style.display = "none";
	}
	else {
	   document.getElementById(obj).style.display = "";
	}
}

/**
 * 
 */
function desableEnable(id) {
   var subcateg = document.getElementById("mailling"+id);
   var editasub = document.getElementById("acessoTotal"+id);
   if (subcateg.checked == true) {
	   editasub.disabled = false;
   }
   else {
	   editasub.checked  = false;
	   editasub.disabled = true;
   }
}

/**
 * 
 */
function habilitaCampo(master, id_slave) {
   slave = document.getElementById(id_slave);
   if (master.checked == true) {
	   slave.disabled = false;
   }
   else {
	   slave[0].selected=true;
	   slave.disabled = true;
	   if (master.name == "deposito") {
		   mostraTipoDeposito(slave);
	   }
   }
}

/**
 * 
 */
function mostraTipoDeposito(campo) {
	if (campo.value == "INT") {
	    document.getElementById("dep_nac").style.display = "none";
	    document.getElementById("dep_int").style.display = "";
	}
	else
	if (campo.value == "NAC") {
	    document.getElementById("dep_nac").style.display = "";
	    document.getElementById("dep_int").style.display = "none";
	}
	else {
	    document.getElementById("dep_nac").style.display = "none";
	    document.getElementById("dep_int").style.display = "none";
	}
}

//-----------------------------------------------------
//Funcao: MascaraMoeda
//Sinopse: Mascara de preenchimento de moeda
//Parametro:
//   objTextBox : Objeto (TextBox)
//   SeparadorMilesimo : Caracter separador de milésimos
//   SeparadorDecimal : Caracter separador de decimais
//   e : Evento
//Retorno: Booleano
//Autor: Gabriel Fróes
//Data Criação: 15/02/2005
//-----------------------------------------------------
function MascaraMoeda(objTextBox, SeparadorMilesimo, SeparadorDecimal, 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 || whichCode == 8) return true;
    key = String.fromCharCode(whichCode); // Valor para o código da Chave
    if (strCheck.indexOf(key) == -1) return false; // Chave inválida

    len = objTextBox.value.length;
    for(i = 0; i < len; i++)
        if ((objTextBox.value.charAt(i) != '0') && (objTextBox.value.charAt(i) != SeparadorDecimal)) break;
    aux = '';
    for(; i < len; i++)
        if (strCheck.indexOf(objTextBox.value.charAt(i))!=-1) aux += objTextBox.value.charAt(i);
    aux += key;

    len = aux.length;
    if (len == 0) objTextBox.value = '';
    if (len == 1) objTextBox.value = '0'+ SeparadorDecimal + '0' + aux;
    if (len == 2) objTextBox.value = '0'+ SeparadorDecimal + aux;
    if (len > 2) {
        aux2 = '';
        for (j = 0, i = len - 3; i >= 0; i--) {
            if (j == 3) {
                aux2 += SeparadorMilesimo;
                j = 0;
            }
            aux2 += aux.charAt(i);
            j++;
        }
        objTextBox.value = '';
        len2 = aux2.length;
        for (i = len2 - 1; i >= 0; i--)
        objTextBox.value += aux2.charAt(i);
        objTextBox.value += SeparadorDecimal + aux.substr(len - 2, len);
    }
    return false;
}

function dataDiff(dtFim, dtIni) {
	if (!isNull(dtIni)) {  
		if (isDate(dtIni) != false) {
			if (!isNull(dtFim)) {
				if (isDate(dtFim) != false) {
					if (calculaTotalDias(dtIni, dtFim) >= 0) {
						alert("A Data Final deve ser posterior a Data Inícial");
						dtFim.className = 'tfvHighlight';
						dtFim.focus();
						document.forms[0].btnSubmit.disabled=true;
						return false;
					}
				}
			}
		}
	}
	document.forms[0].btnSubmit.disabled=false;
	dtFim.className = 'tfvNormal';
}

function isNull(campo){
	if (campo.value == "" || campo.value.length < 10) 
		return true;
	else
		return false;
}

function isDate(campo){
	var expReg = /^(([0-2]\d|[3][0-1])\/([0]\d|[1][0-2])\/[1-2][0-9]\d{2})$/;
	var msgErro = 'Formato inválido de data.';

	if ((campo.value.match(expReg)) && (campo.value!='')){
	    barras = campo.value.split("/");
	    var dia = barras[0];
	    var mes = barras[1];
	    var ano = barras[2];

        resultado = ((!isNaN(dia) && (dia > 0) && (dia < 32)) && (!isNaN(mes) && (mes > 0) && (mes < 13)) && (!isNaN(ano) && (ano > 2005) && (ano < 2008)));

        if (!resultado) {
            return false;
	    }
	    else {

			if (mes==4 || mes==6 || mes==9 || mes==11 && dia > 30) {
				return false;
			} 
			else {
				if (ano%4!=0 && mes==2 && dia>28) {
					return false;
				} 
				else {
					if (ano%4==0 && mes==2 && dia>29) {
						return false;
					} 
				}
			}
	    }
	}
	else {
		return false;
	}
}

function calculaTotalDias(dt1, dt2){

    dat1 = dt1.value.split("/");
	dia1 = dat1[0];
	mes1 = dat1[1]-1;
	ano1 = dat1[2];
	var data1 = new Date(ano1, mes1, dia1);

    dat2 = dt2.value.split("/");
	dia2 = dat2[0];
	mes2 = dat2[1]-1;
	ano2 = dat2[2];
	var data2 = new Date(ano2, mes2, dia2);

	var diferenca = data1.getTime() - data2.getTime();
	var diferenca = Math.floor(diferenca / (1000 * 60 * 60 * 24));

	return diferenca;
}
function mascMoeda(cur,len) { 

        n='__0123456789';
        d=cur.value;
        l=d.length;
        r='';

        if (l > 0)
        {   z = d.substr(0,l-1);
            s = '';
            a = 2;

            for (i=0; i < l; i++)
            {
                 c = d.charAt(i);
                 if (n.indexOf(c) > a)
                 {   a=1;
                     s+=c;
                 };
            };

            l = s.length;
            t = len-1;

            if (l > t)
            {   l = t;
                s = s.substr(0,t);
            };
  		    if (l > 2)
            {   r = s.substr(0,l-2)+','+s.substr(l-2,2);
            }
            else
            {   if (l == 2)
                {   r='0, '+s;
                }
                else
                {  if (l == 1)
                   {   r = '0,0'+s;
                   };
                };
            };

            if (r == '')
            {   r = '0,00';
            }
            else
            {   l = r.length;
                if (l > 6)
                {   j  = l%3;
                    w  = r.substr(0,j);
                    wa = r.substr(j,l-j-6);
                    wb = r.substr(l-6,6);
                    if (j > 0)
                    {   w += '.';
                    };
                    k = (l-j)/3-2;

                    for (i=0; i < k; i++)
					{    w += wa.substr(i*3,3)+'.';
                    };

                    r = w+wb;
                };
             };
         };

         if (r.length <= len)
         {   cur.value=r;
         }
         else
         {   cur.value=z;
         };

         return 'ok';
}
function mascaraTel(campo) { // (21) 3333-3333
	c = campo;
	t = c.value.length;
	if (t==1) {
		c.value = "("+c.value;
	}
	if (t==3) {
		c.value += ") ";
	}
	if (t==9) {
		c.value += "-";
	}
}