var letra = new Array('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z');

function addFavorito(title, url){
    if (window.sidebar) window.sidebar.addPanel(title, url,"");
    else if(window.opera && window.print){
        var mbm = document.createElement('a');
        mbm.setAttribute('rel','sidebar');
        mbm.setAttribute('href',url);
        mbm.setAttribute('title',title);
        mbm.click();
    }
    else if(document.all){window.external.AddFavorite(url, title);}
}

var msgErro = function(x, a, c){
	alert("Ocorreu algum erro durante esse processo.\r\n\r\n Entre em contato conosco ");
};

var init = function()
{
	inputUtil();
	
	//criar validacoes
	$.each($('.form'), function()
	{
		$(this).validate();
	});
	
	//criar trava
	$.each($('textarea[TravaQtd]'), function()
	{
		var o = $(this);
		var qtd = parseInt(o.attr('TravaQtd'));
		var lbl = $("#" + o.attr('TravaLabel'));
		o.keypress(function(e){
			if(this.value.length >= qtd)
			{
				this.value = this.value.substring(0, (qtd - 1));
				return;
			}
			lbl.text(qtd - this.value.length);
		});
		
		o.keydown(function(e){
			lbl.text(qtd - this.value.length);
		});
	});
			
	//criar WatermarkInput
	$.each($('input[Watermark]'), function()
	{
		var Watermark = $(this).attr('Watermark');
		var cor = "#666666";
		if($(this).css('color'))
		{
			cor = $(this).css('color');
		}
		$(this).Watermark(Watermark, cor);
		
	});
	
	//criar maskaras
	$.each($('input[Mask]'), function()
	{
		var Mask = $(this).attr('Mask');
		$(this).mask(Mask);
	});

	//seta focus no campo
	$.each($('*[@FocusInit]'), function()
	{
		var Focus = $(this).attr('FocusInit');
		if(Focus)
		{
			$(this).focus();
		}
	});
};

//funções nos inputs
var inputUtil = function(){
	$('input, select, textarea').each(function(){
		var o = $(this);
		var meta = o.metadata();
		
		//mascara
		if(meta.mask)
		{
			o.mask(meta.mask);
		}
		
		//focus
		if(meta.focus)
		{
			o.focus();
		}
		
		//watermark
		if(meta.watermark)
		{
			var cor = (o.css('color') ? o.css('color') : "#666666");			
			o.Watermark(meta.watermark, cor);
		}
	});
}

var conf = function(msg){
	if(!msg){
		return confirm('Deseja realmente remover este registro ?');
	}
	else{
		return confirm(msg);
	}
};

var confURL = function(url, msg){
	if(!msg){
		msg = false;
	}
	if(conf(msg))
	{
		window.location.href = url;
	}
};

var LinhaCor = function()
{
	$.each($(".Grid"), function(){
				var conta = 1;
				$.each($("tbody tr", this), function(){
					if(conta == 0)
					{
						$(this).addClass("Alter");
						conta = 1;
					}
					else
					{
						conta = 0;
					}
				});
			});
};

function getKeyCode(e)
{
	var whichCode;
    if (window.event) whichCode = window.event.keyCode;
    else if (e) whichCode = (e.which) ? e.which : e.keyCode;
    return whichCode;
}

function formatarValor(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 = getKeyCode(e);
	if (whichCode == 13) return true;  // Enter
	if (whichCode == 8 ) fld.value = '';
	else{
		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 TravarTexto(o, qtd, lbl)
{
    if(o.value.length <= qtd)
    {
        document.getElementById(lbl).innerHTML = (qtd - o.value.length);
    }
    else
    {
        o.value = o.value.substr(0, qtd);
    }
}

function PermiteNumeros(e)
{
	var key = getKeyCode(e);
	if(key != 35 && key != 36 && key != 37 && key != 38 && key != 39 && key != 40 && key != 46 && key != 9 && key != 13 && key != 8 && key != 0)
	{
    	if(key < 48 || key > 57)
    	{
	   		(navigator.appName == 'Netscape')? e.preventDefault() : e.keyCode=0;
    	}
	} 
}
function formatarData(field, e)
{
	return mask(field, "??/??/????", 1, e);
}

function formatarHora(field, e)
{
	return mask(field, "??:??", 1, e);
}

function formatarCEP(field, e)
{
	return mask(field, "?????-???", 1, e);
}

function formatarCPF(field, e)
{
	return mask(field, "???.???.???-??", 1, e);
}

function formatarCNPJ(field, e)
{
	return mask(field, "??.???.???/????-??", 1, e);
}

function formatarTelefone(field, e)
{
	return mask(field, "(??) ????-????", 1, e);
}

function validarData(campo)
{
	var erro = false;
	var value = ((typeof campo.value == "undefined") ? campo : campo.value);
	
	//valida formato da data
	var expReg = /^(([0-2]\d|[3][0-1])\/([0]\d|[1][0-2])\/[1-2][0-9]\d{2})$/;
	if (!(value.match(expReg))){erro = true;}
		    	    					
	//valida se a data eh valida
	var dia = value.substring(0,2);
	var	mes = value.substring(3,5);
	var	ano = value.substring(6,10);
	if (mes > 12){erro = true;} 
	if (mes==01||mes==03||mes==05||mes==07||mes=='08'||mes==10||mes==12){if (dia > 31){erro = true;}}
	else if(mes== 04 || mes==06 || mes==10 || mes==11){if (dia > 30){erro = true;}}
	else if (mes==02){if (dia > 28) {erro = true;}}

	return !erro;
}

function validarEmail(campo)
{
	var value = ((typeof campo.value == "undefined") ? campo : campo.value);
	return (/^[^\s,;]+@([^\s.,;]+\.)+[\w-]{2,}$/i.test(value));
}

function validarCPF(campo)
{
	var value = ((typeof campo.value == "undefined") ? campo : campo.value);
	var s = value;
	var i; 
	var erro = false;
	    
    s = s.replace(".", "");
    s = s.replace(".", "");
    s = s.replace("-", "");
            
	var c = s.substr(0,9);
    var dv = s.substr(9,2);
    var d1 = 0;
    for (i = 0; i < 9; i++){
        d1 += c.charAt(i)*(10-i);
    }
    if (d1 == 0){     
        erro = true;
    }
    d1 = 11 - (d1 % 11);
    if (d1 > 9) d1 = 0;
    if (dv.charAt(0) != d1){
        erro = true;
    }
    d1 *= 2;
    for (i = 0; i < 9; i++){
        d1 += c.charAt(i)*(11-i);
    }
    d1 = 11 - (d1 % 11);
    if (d1 > 9) d1 = 0;
    if (dv.charAt(1) != d1){
        erro = true;
    }
            
    if(s == '11111111111'
    || s == '22222222222'
    || s == '33333333333'
    || s == '44444444444'
    || s == '55555555555'
    || s == '66666666666'
    || s == '77777777777'
    || s == '88888888888'
    || s == '99999999999'){
        erro = true;
    }
            
    return !erro;
}

function validarCNPJ(campo)
{
	var value = ((typeof campo.value == "undefined") ? campo : campo.value);
	var CNPJ = value;
	var erro = false;
			
	CNPJ = CNPJ. replace (".","");
    CNPJ = CNPJ. replace (".","");
    CNPJ = CNPJ. replace ("-","");
    CNPJ = CNPJ. replace ("/","");
				
    if (CNPJ.length < 14) erro = true;
            
    var nonNumbers = /\D/;
    if (nonNumbers.test(CNPJ)) erro = true;
    var a = [];
    var b = new Number;
    var c = [6,5,4,3,2,9,8,7,6,5,4,3,2];
    for (i=0; i<12; i++){
        a[i] = CNPJ.charAt(i);
        b += a[i] * c[i+1];
    }
    if ((x = b % 11) < 2) { a[12] = 0 } else { a[12] = 11-x }
    b = 0;
    for (y=0; y<13; y++) {
        b += (a[y] * c[y]);
    }
    if ((x = b % 11) < 2) { a[13] = 0; } else { a[13] = 11-x; }
    if ((CNPJ.charAt(12) != a[12]) || (CNPJ.charAt(13) != a[13])){
        erro = true;
    }            
    return !erro;
}

function selecionaAction(pagina, form)
{
	if(!form)
	{
		form = ".form";
	}
	$(form).attr("action", pagina);
	$(form).submit();
}

function cep_default()
{
	var url = ((typeof(URL) == "string") ? URL : "../");
	var c = $("#txtCEP").val().replace(/[^\d]*/gi, "");
	if(c.length >= 8)
	{
		$("#txtEndereco").val('Carregando...');
		$.get(url + "library/loadcep.php", {cep: c}, function(dados){
			if($("resultado", dados).text() == "1")
			{
				$("#txtEndereco").val($("tipo_logradouro", dados).text() + ' ' + $("logradouro", dados).text());
				$("#txtBairro, #ddlBairro").val($("bairro", dados).text());
				$("#txtCidade, #ddlCidade").val($("cidade", dados).text());
				$("#txtEstado, #ddlEstado").val($("estado", dados).text());
				$("#txtPais, #ddlPais").val("Brasil");
			}
			else
			{
				$("#txtEndereco").val('');
			}
		});
	}
}
function mask(campo, formato, conteudo, event) {

 valor = campo.value;

 var i, j;
 var caracs = [ '.', '/', '-', ':', '(', ')', ',' ];
 var auxPonto = formato;
 var auxBarra = formato;
 var auxHifen = formato;
 var auxDblPonto = formato;
 var auxAbrePar = formato;
 var auxFechaPar = formato;
 var auxVirgula = formato;
 var tamanho = formato.length;
 var posPonto = new Array(tamanho);
 var posBarra = new Array(tamanho);
 var posHifen = new Array(tamanho);
 var posDblPonto = new Array(tamanho);
 var posAbrePar = new Array(tamanho);
 var posFechaPar = new Array(tamanho);
 var posVirgula = new Array(tamanho);
 var keyPress = event;

 campo.maxLength = tamanho;

 if (event.keyCode != 17) {
  switch (conteudo) {
  case 1: // Verifica se soh podem ser entrados valores numericos
   if (!(event.keyCode >= 48) && (event.keyCode)) if(navigator.appName != 'Netscape') event.keyCode = 0;
   break;
  case 2: // Somente Letras
   if (!((event.keyCode >= 97) && event.keyCode) || (event.keyCode >= 65 && event.keyCode)) if(navigator.appName != 'Netscape') event.keyCode = 0;
   break;
  case 3: // Letras e numeros
   if (!((event.keyCode >= 48) && event.keyCode) || (event.keyCode >= 97 && event.keyCode) || (event.keyCode >= 65 && event.keyCode)) if(navigator.appName != 'Netscape') event.keyCode = 0;
   break;
  }
 }

 // ----------------------------- PEGA A FORMATACAO DA MASCARA
 // ------------------
 for (i = 0; i < tamanho; i++) {

  posPonto[i] = auxPonto.indexOf('.');
  posBarra[i] = auxBarra.indexOf('/');
  posHifen[i] = auxHifen.indexOf('-');
  posDblPonto[i] = auxDblPonto.indexOf(':');
  posAbrePar[i] = auxAbrePar.indexOf('(');
  posFechaPar[i] = auxFechaPar.indexOf(')');
  posVirgula[i] = auxVirgula.indexOf(',');

  auxPonto = auxPonto.substring(posPonto[i] + 1, tamanho);
  auxBarra = auxBarra.substring(posBarra[i] + 1, tamanho);
  auxHifen = auxHifen.substring(posHifen[i] + 1, tamanho);
  auxDblPonto = auxDblPonto.substring(posDblPonto[i] + 1, tamanho);
  auxAbrePar = auxAbrePar.substring(posAbrePar[i] + 1, tamanho);
  auxFechaPar = auxFechaPar.substring(posFechaPar[i] + 1, tamanho);
  auxVirgula = auxVirgula.substring(posVirgula[i] + 1, tamanho);

  if (i > 0) {
   posPonto[i] = posPonto[i] + posPonto[i - 1];
   posBarra[i] = posBarra[i] + posBarra[i - 1];
   posHifen[i] = posHifen[i] + posHifen[i - 1];
   posDblPonto[i] = posDblPonto[i] + posDblPonto[i - 1];
   posAbrePar[i] = posAbrePar[i] + posAbrePar[i - 1];
   posFechaPar[i] = posFechaPar[i] + posFechaPar[i - 1];
   posVirgula[i] = posVirgula[i] + posVirgula[i - 1];
   posPonto[i] = posPonto[i] + 1;
   posBarra[i] = posBarra[i] + 1;
   posHifen[i] = posHifen[i] + 1;
   posDblPonto[i] = posDblPonto[i] + 1;
   posAbrePar[i] = posAbrePar[i] + 1;
   posFechaPar[i] = posFechaPar[i] + 1;
   posVirgula[i] = posVirgula[i] + 1;
  }
 }

 // Retirando a máscara
 for (i = 0; i < campo.value.length; i++) {
  valor = valor.replace('-', '');
  valor = valor.replace('(', '');
  valor = valor.replace(')', '');
  valor = valor.replace(':', '');
  valor = valor.replace('/', '');
  valor = valor.replace('.', '');
  valor = valor.replace(',', '');
 }

 // Faz a validação se for apenas número
 // utilizado para fazer a validação de Ctrl+V
 if (conteudo == 1) {
  if (isNaN(valor)) {
   if (isNaN(valor.charAt(valor.length - 2)))
    valor = "";
   else
    valor = valor.substring(0, valor.length - 1);
  }
 }

 indicePonto = 0;
 indiceBarra = 0;
 indiceHifen = 0;
 indiceDblPonto = 0;
 indiceVirgula = 0;
 indiceAbrePar = 0;
 indiceFechaPar = 0;

 // Varre o campo aplicando a máscara
 for (i = 0; i < valor.length; i++) {
  if (i == posPonto[indicePonto]) {
   if (valor.charAt(i) != '.') {
    if (i == 0) {
     valor = '.' + valor;
    } else if (i == valor.length) {
     valor = valor + '.';
    } else {
     valor = valor.substring(0, i) + '.' + valor.substring(i);
    }
    indicePonto++;
   }
  }
  if (i == posBarra[indiceBarra]) {
   if (valor.charAt(i) != '/') {
    if (i == 0) {
     valor = '/' + valor;
    } else if (i == valor.length) {
     valor = valor + '/';
    } else {
     valor = valor.substring(0, i) + '/' + valor.substring(i);
    }
    indiceBarra++;
   }
  }

  if (i == posHifen[indiceHifen]) {
   if (valor.charAt(i) != '-') {
    if (i == 0) {
     valor = '-' + valor;
    } else if (i == valor.length) {
     valor = valor + '-';
    } else {
     valor = valor.substring(0, i) + '-' + valor.substring(i);
    }
    indiceHifen++;
   }
  }

  if (i == posDblPonto[indiceDblPonto]) {
   if (valor.charAt(i) != ':') {
    if (i == 0) {
     valor = ':' + valor;
    } else if (i == valor.length) {
     valor = valor + ':';
    } else {
     valor = valor.substring(0, i) + ':' + valor.substring(i);
    }
    indiceDblPonto++;
   }
  }

  if (i == posAbrePar[indiceAbrePar]) {
   if (valor.charAt(i) != '(') {
    if (i == 0) {
     valor = '(' + valor;
    } else if (i == valor.length) {
     valor = valor + '(';
    } else {
     valor = valor.substring(0, i) + '(' + valor.substring(i);
    }
    indiceAbrePar++;
   }
  }

  if (i == posFechaPar[indiceFechaPar]) {
   if (valor.charAt(i) != ')') {
    if (i == 0) {
     valor = ')' + valor;
    } else if (i == valor.length) {
     valor = valor + ')';
    } else {
     valor = valor.substring(0, i) + ')' + valor.substring(i);
    }
    indiceFechaPar++;
   }
  }

  if (i == posVirgula[indiceVirgula]) {
   if (valor.charAt(i) != ',') {
    if (i == 0) {
     valor = ',' + valor;
    } else if (i == valor.length) {
     valor = valor + ',';
    } else {
     valor = valor.substring(0, i) + ',' + valor.substring(i);
    }
    indiceVirgula++;
   }
  }
 }

 if (campo.value.length > tamanho) {
  campo.value = campo.value.substring(0, tamanho);
 }

 campo.value = valor;
}