var form = document.forms[0];
var send = true;
var alerted = false;

//Verifica se o ano é valido
// Ano valido é maior que 1900 e menor que o ano atual
function checkYear(inputYear,msg) {

	year = Number(document.getElementById(inputYear).value);		
	var result = false;
	var currentYear = new Date().getYear();
		
	if (year < 1900 || year > currentYear) result = false; else result = true	
	isValid(result,inputYear,msg);
	return result;

}

function setNextInput() {
	arrInput = document.getElementsByTagName("input");
	for (var i = 0; i < arrInput.length; i++) {	
		
		arrInput[i].num = i;
		arrInput[i].onkeyup = function() {
			var len = this.value.length;
			if (len >= this.maxLength) {
				var t = this.num + 1;
				if (arrInput[t].disabled == true) {
					return false;
				}
				arrInput[t].focus();
			}
		}
	}
}

//verifica se tem pelo menos um checkbox marcado.

// MELHORADO POR MARCO ANTONIO LIMA PIMENTEL
function VericaChkBOX(nomeForm,msg) {
	var aux = 0;
	var objetoForm = document.getElementById(nomeForm);

	for (i = 0; i < objetoForm.length; i++) {
		if (objetoForm.elements[i].type == "checkbox") {
			if (objetoForm.elements[i].checked) {
				aux = 1;
			}
		}
	}
	if (aux == 0) {
		if (send) {
			alerted = true;
			alert(msg);
		}
		return false;
	} else {
		return true;
	}
}
function VerifyCheck() {
	var aux = 0;
	for (i = 0; i < document.forms[0].length; i++) {
		if (document.forms[0].elements[i].type == 'checkbox') {
			if (document.forms[0].elements[i].checked) {
				aux = 1;
			}
		}
	}
	if (aux == 0) {
		return false;
	} else {
		return true;
	}
}
// Exibe erros
function isValid(result, input, msg) {
   if (result == false && msg != "" && alerted == false) {
      alert(msg);
	  alerted = true;
	
      document.getElementById(input).focus();
   }
}
// Exibe erros

// Função para campos em upperCase
function upperCase() {
	this.value = this.value.toUpperCase();
}

// Seta todos os input texts em caixa alta
function setInputsToUpperCase() {

	var len = document.getElementsByTagName("input").length;
	for (i = 0; i < len; i++) {
		var element = document.getElementsByTagName("input")[i];
		element.style.textTransform = "uppercase";
		element.onkeyup = upperCase;
	}
	
	var len = document.getElementsByTagName("textarea").length;
	for (j = 0; j < len; j++) {
		var element = document.getElementsByTagName("textarea")[j];
		element.style.textTransform = "uppercase";
		element.onkeyup = upperCase;
	}
}

//Executa uma função quando o usuario digitar a tecla "Enter" em um Input Text especifico
function setKeyEnter(id,method) {
	element = document.getElementById(id);
	element.onkeypress = function() {
		if (event.keyCode == 13) {
			method();
		}
	}
}

//Executa função de validação quando o usuario digitar "Enter" em qualquer input Text da pagina
function setInputsValidate(method) {
	var arrInput = document.getElementsByTagName("input")
	
	for (var i = 0; i < arrInput.length; i++) {
		arrInput[i].onkeyup = onUp;
	}
	
	function onUp() {
		if (event.keyCode == 13) {
			method();
		}
	}
}

// Valida se o password do campo A é igual a do campo B
function passwordConfirm(inputA,inputB,msg) {
	var result = false;

	if (document.getElementById(inputA).value == document.getElementById(inputB).value) {
		result = true;
	} else {
		result = false;
	}

	isValid(result, inputA, msg);
	
	return result;
}

// Formata o campo como numerico passando o input
function setKeyInt(input) {
	alert(input);
	document.getElementById(input).onkeypress = function() {
		
		if (enterInt(event.keyCode)) {
			return true;
		} else {
			return false;
		}
	}
}
// Formata o campo como telefone passando o input
function setKeyFone(input) {

	document.getElementById(input).onkeypress = function() {
		formataTelefone(document.getElementById(input))
	}
}


// Validação para não vazio
/*function noNull(input, msg) {
   var result = false;
   
   if (document.forms[0].elements[input].value == "") result = false; else result = true;

   isValid(result, input, msg);
   return result;
}*/
// Validação para não vazio

// Validação para entrada de decimais
function enterFloat(key) {

   if ((key > 47 && key < 58) || key == 8 || key == 116 || (key > 95 && key < 106) || (key > 33 && key < 41) || key == 45 || key == 12 || key == 9  || key == 190)
      return true;
   else
      return false;
}
// Validação para entrada de decimais



// Validação para decimais
function isFloat(key) {
   if ((key > 47 && key < 58) || key == 8 || key == 116 || (key > 95 && key < 106) || (key > 33 && key < 41) || key == 45 || key == 12 || key == 9 || key == 188 || key == 46)
      return true;
   else
      return false;
}

function isMonthYear(key) {
   if ((key > 47 && key < 58) || key == 8 || key == 116 || (key > 95 && key < 106) || (key > 33 && key < 41) || key == 45 || key == 12 || key == 9 || key == 46 || key == 111 || key == 193 || key == 191)
      return true;
   else
      return false;
}
// Validação para decimais

// Inserir Inteiro
function enterInt(key) {

   if ((key > 47 && key < 58) || key == 8 || key == 116 || (key > 95 && key < 106) || (key > 33 && key < 41) || key == 45 || key == 12 || key == 9)
      return true;
   else
      return false;
}
// Inserir Inteiro

// Inserir Data
function enterDate(key, input) {
   var result = false;
   if ((key > 47 && key < 58) || key == 8 || key == 116 || (key > 95 && key < 106) || (key > 33 && key < 41) || key == 45 || key == 12 || key == 9) 
      result = true;
   if (key != 8) {
      if (input.value.length == 2) input.value = input.value + "/";
      if (input.value.length == 5) input.value = input.value + "/";
   }
   return result;
} 
// Inserir Data


// **************************************************************************************************
var dtCh= "/";
var minYear=1900;
var maxYear=2100;

function isInteger(s){
	var i;
    for (i = 0; i < s.length; i++){
        // Check that current character is number.
        var c = s.charAt(i);
        if (((c < "0") || (c > "9"))) return false;
    }
    // All characters are numbers.
    return true;
}

function stripCharsInBag(s, bag){
	var i;
    var returnString = "";
    // Search through string's characters one by one.
    // If character is not in bag, append to returnString.
    for (i = 0; i < s.length; i++){
        var c = s.charAt(i);
        if (bag.indexOf(c) == -1) returnString += c;
    }
    return returnString;
}

function daysInFebruary (year){
	// February has 29 days in any year evenly divisible by four,
    // EXCEPT for centurial years which are not also divisible by 400.
    return (((year % 4 == 0) && ( (!(year % 100 == 0)) || (year % 400 == 0))) ? 29 : 28 );
}
function DaysArray(n) {
	for (var i = 1; i <= n; i++) {
		this[i] = 31
		if (i == 4 || i == 6 || i == 9 || i == 11) {this[i] = 30}
		if (i == 2) {this[i] = 29}
   }
   return this
}

function isDate(dtStr, input, msg){
	var daysInMonth = DaysArray(12);
	var pos1 = dtStr.indexOf(dtCh);
	var pos2 = dtStr.indexOf(dtCh, pos1+1);
	var strDay = dtStr.substring(0, pos1);
	var strMonth = dtStr.substring(pos1 + 1, pos2);
	var strYear = dtStr.substring(pos2 + 1);
	var result = true;
	strYr = strYear;
	if (strDay.charAt(0) == "0" && strDay.length > 1) strDay = strDay.substring(1);
	if (strMonth.charAt(0)== "0" && strMonth.length > 1) strMonth = strMonth.substring(1);
	for (var i = 1; i <= 3; i++) {
		if (strYr.charAt(0) == "0" && strYr.length > 1) strYr = strYr.substring(1);
	}
	month = parseInt(strMonth);
	day = parseInt(strDay);
	year = parseInt(strYr);
	if (pos1 == -1 || pos2 == -1){
		result = false;
	}
	if (strMonth.length < 1 || month < 1 || month > 12){
		result = false;
	}
	if (strDay.length < 1 || day < 1 || day > 31 || (month == 2 && day > daysInFebruary(year)) || day > daysInMonth[month]){
		result = false;
	}
	if (strYear.length != 4 || year == 0 || year<minYear || year > maxYear){
		result = false;
	}
	if (dtStr.indexOf(dtCh,pos2+1)!= -1 || isInteger(stripCharsInBag(dtStr, dtCh)) == false){
		result = false;
	}

   isValid(result, input, msg);
   return result;
}


// Validacao de CNPJ
function isCNPJ(input, msg){
	var result = true;
	var r = new RegExp('[./-]', 'g');
	var cnpj = document.forms[0].elements[input].value.replace(r, ''); 
	var i;
	var c = cnpj.substr(0,12);
	var dv = cnpj.substr(12,2);
	var d1 = 0;
	for (i = 0; i <12; i++){
		d1 += c.charAt(11-i)*(2+(i % 8));
	}
	
	if (d1 == 0) result =  false;
	
	d1 = 11 - (d1 % 11);
	if (d1 > 9) d1 = 0;
	if (dv.charAt(0) != d1) result =  false; 
	d1 *= 2;
	
	for (i = 0; i < 12; i++){
		d1 += c.charAt(11-i)*(2+((i+1) % 8));
	}
	
	d1 = 11 - (d1 % 11);
	if (d1 > 9) d1 = 0;
	if (dv.charAt(1) != d1) result =  false;
	
	isValid(result, input, msg);
	return result;
}

// Validacao de CPF
function isCPF(input, msg){
	var result = true;
	var r = new RegExp('[./-]', 'g');
	var cpf = document.getElementById(input).value.replace(r, ''); 
	var i;
	var c = cpf.substr(0,9);
	var dv = cpf.substr(9,2);
	var d1 = 0;
	for (i = 0; i < 9; i++) {
		d1 += c.charAt(i)*(10-i);
	}
	if (d1 == 0) result =  false;
    d1 = 11 - (d1 % 11);
    
    if (d1 > 9) d1 = 0;         
	if (dv.charAt(0) != d1) result = false;
	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) result =  false;
	
	isValid(result, input, msg);
	return result;
}

//Formata o CPF 999.999.999-99
function formataCPF(input) {
    //if ((event.keyCode < 48) || (event.keyCode > 57)) {
  //      event.returnValue = false;
  // } else {
        if ((input.value.length == 3) || (input.value.length == 7)) {
            input.value = input.value + ".";
        } else {
            if (input.value.length == 11) {input.value = input.value + "-";}
        }
  //  }
}

function Integer() {
    if (event.keyCode < 48 || event.keyCode > 57) {
        event.returnValue = false;
    }
}

//Formata o CNPJ 99.999.999/9999-99 
function formataCNPJ(input) {
   // if (event.keyCode < 48 || event.keyCode > 57) {
    //    event.returnValue = false;
   // } else {
        if (input.value.length == 2 || input.value.length == 6) {
            input.value = input.value + ".";
        } else {
            if (input.value.length == 10) {
            	input.value = input.value + "/";
			} else {
            	if (input.value.length == 15) { input.value = input.value + "-"; }
            }	
        }
   // }
}

//Formata Telefone 9999-9999
function formataTelefone(input) {
	
	if (event.keyCode == 8) {
		return true;
	}
	
    if (event.keyCode < 48 || event.keyCode > 57) {
        event.returnValue = false;
    } else if (input.value.length == 4) {
	input.value = input.value + "-";
    }
	
}

//Formata CEP 99999-999
function formataCEP(input) {
    if (event.keyCode < 48 || event.keyCode > 57) {
        event.returnValue = false;
    } else if (input.value.length == 5) {
	input.value = input.value + "-";
    }
}


//Formata o Data com barra dd/mm/yyyy
function formataData(input) {
    if (event.keyCode < 48 || event.keyCode > 57) {
        event.returnValue = false;
	} else {
		if ((input.value.length == 2) || (input.value.length == 5)) {
            input.value = input.value + "/";
        }
    }
}

function formataTelefoneEx(input) {
	
	if (event.keyCode == 8) {
		return true;
	}
	
    if (event.keyCode < 48 || event.keyCode > 57) {
        event.returnValue = false;
    } 
	
	if (input.value.length == 0) {
		input.value = input.value + "(";    
	}
	
	if (input.value.length == 3) {
		input.value = input.value + ") ";
    }
	
	if (input.value.length == 9) {
		input.value = input.value + "-";
    }

	
}
function exibirCalendario(campo) {
	field = campo;
	calendario.goToToday();
    if (DIVCalendario.style) {DIVCalendario = DIVCalendario.style;}
	DIVCalendario.left = event.clientX;
//	DIVCalendario.top = event.clientY + document.body.scrollTop - 70;
	DIVCalendario.top = event.clientY + document.body.scrollTop - 10;
    	DIVCalendario.visibility = 'visible';
}

function ocultarCalendario() {
    if (DIVCalendario.style) {DIVCalendario = DIVCalendario.style;}
	DIVCalendario.visibility = 'hidden';
}


// **************************************************************************************************

//Valida a data
function checkDate(dtStr){
	var daysInMonth = DaysArray(12)
	var pos1 = dtStr.indexOf(dtCh)
	var pos2 = dtStr.indexOf(dtCh, pos1+1)
	var strDay = dtStr.substring(0, pos1)
	var strMonth = dtStr.substring(pos1 + 1, pos2)
	var strYear = dtStr.substring(pos2 + 1)
	var result = true
	strYr = strYear
	if (strDay.charAt(0) == "0" && strDay.length > 1) strDay = strDay.substring(1)
	if (strMonth.charAt(0)== "0" && strMonth.length > 1) strMonth = strMonth.substring(1)
	for (var i = 1; i <= 3; i++) {
		if (strYr.charAt(0) == "0" && strYr.length > 1) strYr = strYr.substring(1)
	}
	month = parseInt(strMonth)
	day = parseInt(strDay)
	year = parseInt(strYr)
	if (pos1 == -1 || pos2 == -1){
		result = false;
	}
	if (strMonth.length < 1 || month < 1 || month > 12){
		result = false;
	}
	if (strDay.length < 1 || day < 1 || day > 31 || (month == 2 && day > daysInFebruary(year)) || day > daysInMonth[month]){
		result = false;
	}
	if (strYear.length != 4 || year == 0 || year<minYear || year > maxYear){
		result = false;
	}
	if (dtStr.indexOf(dtCh,pos2+1)!= -1 || isInteger(stripCharsInBag(dtStr, dtCh)) == false){
		result = false;
	}
	 return result;
}



// **************************************************************************************************
// **************************************************************************************************
// **************************************************************************************************


// Validação para tamanho minimo
function minLength(input, size, msg) {
   var result = false;
   
   if (document.forms[0].elements[input].value.length < size) result = false; else result = true;

   isValid(result, input, msg);
   return result;
}
// Validação para tamanho minimo




// Validação para não vazio
function noNull(input, msg) {

	var result = false;

   if (Trim(document.getElementById(input).value) == "") result = false; else result = true;

   isValid(result, input, msg);

   return result;
}
// Validação para não vazio


// Validação para Radio Button

// frmName = id do form
// radioId = id do Radio
// msg = mensagem
function radioNoNull(frmName,radioId,msg) {
	var form = document.getElementById(frmName);
	var radios = [];
	var result = false;
	
	for (var i = 0; i < form.elements.length; i++) {
		if (form.elements[i].id == radioId) {				
			radios.push(form.elements[i]);
		}			
	}
	var ok = false;
	for (var i = 0; i < radios.length; i++) {
		ok = radios[i].checked;
		if (ok) {
			result = true;
			break;
		}
	}
	isValid(result, radioId, msg);
	
	return result;
}
// Validação de Radio Button


// Validação de e-mail - OK
function isEmail(input, msg) {
  var result = true;
  if (document.getElementById(input).value.indexOf('@', 0) < 1 || document.getElementById(input).value.indexOf('.',0) < 1) result = false;

  isValid(result, input, msg);
  return result;
}
// Validação de e-mail


// **************************************************************************************************


// Funções Trim para Javascript
// JavaScript Document
function Trim(TRIM_VALUE){
if(TRIM_VALUE.length < 1){
return"";
}
TRIM_VALUE = RTrim(TRIM_VALUE);
TRIM_VALUE = LTrim(TRIM_VALUE);
if(TRIM_VALUE==""){
return "";
}
else{
return TRIM_VALUE;
}
} //End Function

function RTrim(VALUE){
var w_space = String.fromCharCode(32);
var v_length = VALUE.length;
var strTemp = "";
if(v_length < 0){
return"";
}
var iTemp = v_length -1;

while(iTemp > -1){
if(VALUE.charAt(iTemp) == w_space){
}
else{
strTemp = VALUE.substring(0,iTemp +1);
break;
}
iTemp = iTemp-1;

} //End While
return strTemp;

} //End Function

function LTrim(VALUE){
var w_space = String.fromCharCode(32);
if(v_length < 1){
return"";
}
var v_length = VALUE.length;
var strTemp = "";

var iTemp = 0;

while(iTemp < v_length){
if(VALUE.charAt(iTemp) == w_space){
}
else{
strTemp = VALUE.substring(iTemp,v_length);
break;
}
iTemp = iTemp + 1;
} //End While
return strTemp;
} //End Function

function abrir_janela(pagina,titulo,topo,esquerda,largura,altura){
/* exemplo **************************************************
window.open('pagina.html','nomepagina','0','0','50','50');
************************************************************/
window.open(pagina,titulo,"status=no,toolbar=no,menubar=no,top="+topo+",left="+esquerda+",width="+largura+" height="+altura+",scrollbars=no,maximized=no,resizable=no,fullscreen=no"); 

}

function selecionarchk(){
var oElem = document.formpadrao.elements;
	for ( var i=0;i<oElem.length;i++){
		if (oElem[i].type.toUpperCase() == "CHECKBOX") {
			if(oElem[i].checked){
				oElem[i].checked = false;				
			}else{
				oElem[i].checked = true;				
			}
		}
	}
}

function check_marcados(formulario,hidden,vacao){

var oElem = document.getElementById(formulario).elements;
var objcheked = '';
   for ( var i=0;i<oElem.length;i++){
	  if (oElem[i].type.toUpperCase() == "CHECKBOX") {

		if(oElem[i].checked){
		  objcheked=objcheked+oElem[i].value+',';
		}
	  }
   }

objcheked = objcheked.substr(0,objcheked.length -1);
document.getElementById(hidden).value = objcheked;

// verifica se o usuario esta clicando no botao excluir sem ter selecionado algum registro.
if(objcheked == ''){
alert('Selecione ao menos 1 (um) reguistro para exluir.');
} 
// só entra aqui caso seja necessario submeter o form
if(vacao != '' && objcheked != ''){
	var msg
		msg='Deseja realmente Excluir este(s) registro(s)?';
		if(confirm(msg)){
			document.getElementById(formulario).acao.value = vacao;		
			document.getElementById(formulario).submit();		
		}
	}

}


function excluir_chk_sel(){
var msg
	msg='Deseja realmente Excluir este(s) registro(s)?';
	if(confirm(msg)){
		document.formpadrao.acao.value ='EXCLUIR';		
		document.formpadrao.submit();		
	}
}


function irPopup(URL, nomeJanela, scrollbars, largura,altura) {
	if (altura == null) {
		altura = '320';
	}
	
	janela = null;
	var window_width = largura;
	var window_height = altura;
	var window_top = (screen.height-window_height)/2;
	var window_left = (screen.width-window_width)/2;
	popup = window.open(URL,nomeJanela,'width=' + window_width + ',height=' + window_height + ',,top=' + window_top + ',left=' + window_left + 'toolbar=0,location=0,directories=0,status=1,menubar=0,scrollbars=' + scrollbars + ',resizable=0,leftmargin=0,border=0,topmargin=0,marginheight=0,marginwid=0').focus();
}


function abrirGaleria(){
	var url = "http://www.humberto13.can.br/popup/popup_fotos.php";
	irPopup(url,'fotos','0','600','532');
}
