var isNav4 = false, isNav5 = false, isIE4 = false;
if(navigator.appName == "Netscape") {
  if (navigator.appVersion < "5") {
    isNav4 = true;
  }  
  if (navigator.appVersion > "4") {
    isNav5 = true;
  }
} else {
  isIE4 = true;
}

function loadPage(form){ form.submit(); }

function expandContent(content){
  var obj = document.getElementById(content);
	if(obj.style.display=="none") obj.style.display = "inline";
	else obj.style.display = "none";
}	

function download(dir,file){
  url = "forcedownload.php?dir="+dir+"&file="+file; 
	document.getElementById("download_target").src = url;  
}

function overStyle(obj){
  obj.style.backgroundColor = '#f3f3f3';
}

function outStyle(obj){
  obj.style.backgroundColor = '';
}

function MM_openBrWindow(theURL,winName,features){
  window.open(theURL,winName,features);
	return;
}

function onlyNumbers(field){
  numeros = "0123456789";
	new_value = "";
	c = "";
	for(i=0; i<field.value.length; i++){
	  c = field.value.charAt(i);
	  if(numeros.indexOf(c)!=-1) new_value = new_value + c;
	}
	return new_value;
}

function onlyDoubles(campo){
  numeros = "0123456789.,-_";
	new_value = "";
	c = "";
	for(i=0; i<campo.value.length; i++){
	  c = campo.value.charAt(i);
	  if(numeros.indexOf(c)!=-1) new_value = new_value + c;
	}
	campo.value=new_value;
	return;
}

function verificaValor(objeto,teclapres){
  if(isNav4) return true;
  var vr = stringFilter(objeto.value,"1234567890");
  var tam = vr.length;
	
  if(tam==0) objeto.value="0,00";
  else if(objeto.value.indexOf(',')==-1) objeto.value = objeto.value + ',00';
	else if(objeto.value.indexOf(',')!=-1){
	  var tmp = objeto.value.substr(objeto.value.indexOf(',')+1);
		if(tmp.length<2) objeto.value = objeto.value + "0";
	}
  return;
	
}

function formataValor(objeto){
  valor = onlyNumbers(objeto);	
	if(valor.length==3) valor = valor.substr(0,1)+","+valor.substr(1,2);
	else if(valor.length==4) valor = valor.substr(0,2)+","+valor.substr(2,2);
	else if(valor.length==5) valor = valor.substr(0,3)+","+valor.substr(3,2);
	else if(valor.length==6) valor = valor.substr(0,1)+"."+valor.substr(1,3)+","+valor.substr(4,2);
	else if(valor.length==7) valor = valor.substr(0,2)+"."+valor.substr(2,3)+","+valor.substr(5,2);
	else if(valor.length>=8) valor = valor.substr(0,3)+"."+valor.substr(3,3)+","+valor.substr(6,2);
	objeto.value = valor;
  return;
}


function isValidString(str){
  validCharacters = "abcdefghijklmnopqrstuvxzywABCDEFGHIJKLMNOPQRSTUVXYZWáÁéÉíÍóÓúÚãÃõÕâÂêÊîÎôÔûÛñÑ";
	valids = 0;
	for(i=0; i<str.length; i++) if(validCharacters.indexOf(str.charAt(i)) != -1) valids++;
	if(valids>=3) return true;
	else return false; 
	
}

function stringFilter(input,filteredValues) {
  var i;
  var returnString = "";
  for (i = 0; i < input.length; i++) {
    var c = input.charAt(i);
    if(filteredValues.indexOf(c) > -1) returnString += c;
  }
  return returnString;
}

function formataData(objeto,teclapres) {
  if(isNav4) return true;
  var tecla = teclapres.keyCode;
  if(tecla<46) return true;
  var vr = stringFilter(objeto.value,"1234567890");
  var tam = vr.length + 1;
  if( tam < 4 ) return true;
  if( tam > 3 && tam < 5 )
    objeto.value = vr.substr( 0, tam - 2  ) + '/' + vr.substr( tam - 2, tam );
  if( tam >= 5 && tam <= 10 )
    objeto.value = vr.substr( 0, 2 ) + '/' + vr.substr( 2, 2 ) + '/' + vr.substr( 4, 4 );
}

function isDate (day,month,year) {
	var today = new Date();
	ActualYear = today.getFullYear();
  nDay = parseFloat(day);
	nMonth = parseFloat(month);
	nYear = parseFloat(year);
	if((nDay>31) || (nDay<1)) {
	   alert("Data inválida. Por favor verifique.");
	   return false;
	}   
	if((nMonth>12) || (nMonth<1)) {
	   alert("Data inválida. Por favor verifique.");
	   return false;
	}   
	if(((nMonth==4)||(nMonth==6)||(nMonth==9)||(nMonth==11)) && (nDay>30)){
	   alert("Data inválida. Por favor verifique.\nPossivelmente este mês contêm apenas 30 dias.");
	   return false;
	}
	if(nMonth==2){
	   if(nDay>29){
	      alert("Data inválida. Por favor verifique.");
	      return false;
	   }
	   if(nDay==29){	   	   
          if(!(((nYear % 4 == 0) && (nYear % 100 != 0)) || (nYear % 400 == 0))){ 
	         alert("Data inválida. Por favor verifique.\nProvavelmente este não é um ano bisexto");
	         return false;
	      }
	   }
	}   
	if((nYear > ActualYear+1) || (nYear<ActualYear-100)) {
	   alert("Data inválida. Por favor verifique.");
	   return false;
	}
	return true;
}

function formataHora(objeto,teclapres) {
  if(isNav4) return true;
  var tecla = teclapres.keyCode;
  if(tecla<46) return true;
  var vr = stringFilter(objeto.value,"1234567890");
  var tam = vr.length + 1;
  if( tam < 2 ) return true;
  if( tam > 1 && tam < 3)
    objeto.value = vr.substr( tam-2, 1 ) + ':' + vr.substr( tam-1, 1 );
  if( tam > 4 && tam < 6)
    objeto.value = vr.substr( tam-5, 2 ) + ':' + vr.substr( tam-3, 2 );
  if( tam > 5)
    objeto.value = vr.substr( tam-6, 2 ) + ':' + vr.substr( tam-4, 2 );
	
}

function checkEmail(email){
  var str = email;
  var filter=/^([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i;
  if(filter.test(str)) return true;
  else return false;
}

function formataFone(objeto) { 
  valor = onlyNumbers(objeto.value);

	if(valor.length >= 1) valor = '(' + valor;
  if(valor.length >= 4) valor = valor.substr(0, 3) + ')' + valor.substr(3);
  if(valor.length >= 9) valor = valor.substr(0, 8) + '-' + valor.substr(8);
	if(valor.length > 13) valor = valor.substr(0, 13);
	
	objeto.value = valor;
	return;
}

function formataCNPJ(object, teclapres){
	var tecla = teclapres.keyCode;
	var vr = new String(object.value);
	vr = vr.replace(".", "");
	vr = vr.replace("/", "");
	vr = vr.replace("-", "");
	tam = vr.length + 1;
	
	if (tecla != 14){
		if(tam == 3) object.value = vr.substr(0, 2) + '.';
		if(tam == 6) object.value = vr.substr(0, 2) + '.' + vr.substr(2, 5) + '.';
		if(tam == 10) object .value = vr.substr(0, 2) + '.' + vr.substr(2, 3) + '.' + vr.substr(6, 3) + '/';
		if(tam == 15) object.value = vr.substr(0, 2) + '.' + vr.substr(2, 3) + '.' + vr.substr(6, 3) + '/' + vr.substr(9, 4) + '-' + vr.substr(13, 2);
	}
	
	return;
}

function isValidValue(object){
	valor = onlyNumbersTrue(object.value);
	object.value = valor;
	return;
}
	
function formataCep(objeto){
 valor = onlyNumbersNew(objeto.value);
 if(valor.length >= 6) valor = valor.substr(0, 5) + '-' + valor.substr(5,valor.length);
	
 objeto.value = valor;
 return; 
}

function trim(str){
  newStr = "";
	for(i=0; i<str.length; i++) if(str.charAt(i)!=" ") newStr+=str.charAt(i);
	return newStr; 
}

function validaCNPJ(CNPJ) {
        erro = new String;
        if (CNPJ.length < 18) erro += "É necessario preencher corretamente o número do CNPJ. \n"; 
        if ((CNPJ.charAt(2) != ".") || (CNPJ.charAt(6) != ".") || (CNPJ.charAt(10) != "/") || (CNPJ.charAt(15) != "-")){
        if (erro.length == 0) erro += "É necessário preencher corretamente o número do CNPJ. \n";
        }
        //substituir os caracteres que não são números
       if(document.layers && parseInt(navigator.appVersion) == 4){
               x = CNPJ.substring(0,2);
               x += CNPJ. substring (3,6);
               x += CNPJ. substring (7,10);
               x += CNPJ. substring (11,15);
               x += CNPJ. substring (16,18);
               CNPJ = x; 
       } else {
               CNPJ = CNPJ. replace (".","");
               CNPJ = CNPJ. replace (".","");
               CNPJ = CNPJ. replace ("-","");
               CNPJ = CNPJ. replace ("/","");
       }
       var nonNumbers = /\D/;
       if (nonNumbers.test(CNPJ)) erro += "A verificação de CNPJ suporta apenas números.\n"; 
       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 +="Dígito verificador do CNPJ com problema.";
       }
       if (erro.length > 0){
               alert(erro);
               return false;
       }
       return true;
}

function validateUser(form,nPermissoes){

  if((form.name.value=="")||(form.name.value.length<3)){
    alert("Você precisa informar um nome válido.");
    form.name.focus();
    return false;
  }
  
  if((form.username.value=="")||(form.username.value.length<3)){
    alert("Você precisa informar um usuário válido.");
    form.username.focus();
    return false;
  }
  
  if((form.userpass.value=="")||(form.userpass.value.length<3)){
    alert("Você precisa informar uma senha válida (entre 3 e 20 caracteres).");
    form.userpass.focus();
    return false;
  }
  
  if(form.repeat.value!=form.userpass.value){
    alert("A repetição da senha deve ser exatamente igual.");
    form.repeat.focus();
    return false;
  }
  
  var submeter = false;
  for(i=0; i<nPermissoes; i++){
    campo = eval("form.elements['modules["+i+"]']");
    if(campo.checked) submeter = true;
  }
  
  if(!submeter){ alert("Você precisa selecionar pelo menos uma permissão."); return false; }
  
  return true;	
}

function updateThis(key,target){
  var form = document.list;
	form.action=target;
	form.key.value = key;
	form.update.value = true;
	loadPage(form);
}

function deleteThis(key,target){
  var form = document.list;
	form.action=target;
	form.key.value = key;	
	form.remove.value = true;
	loadPage(form);
}


function validatePage() { 
  var form = document.getElementById("page");
	if((form.title.value=="")||(form.title.value.lenght<5)){
	  alert("Você precisa informar um título válido");
		form.title.focus();
		return false;
	}
	if((form.content.value=="")||(form.content.value.lenght<5)){
	  alert("Você precisa informar um conteudo válido");
		form.content.focus();
		return false;
	}
	return true;   
}

function validateTestimonial(){
  var form = document.getElementById("testimonial");
	if((form.title.value=="")||(form.title.value.lenght<5)){
	  alert("Você precisa informar um título válido");
		form.title.focus();
		return false;
	}
	if((form.content.value=="")||(form.content.value.lenght<5)){
	  alert("Você precisa informar um conteudo válido");
		form.content.focus();
		return false;
	}
	return true;
}

function validateMusic(){
  var form = document.getElementById("music");
	if((form.title.value=="")||(form.title.value.lenght<5)){
	  alert("Você precisa informar um título válido");
		form.title.focus();
		return false;
	}
	return true;
}	

function validateDisc(){
  var form = document.getElementById("music");
	if((form.title.value=="")||(form.title.value.lenght<5)){
	  alert("Você precisa informar um título válido");
		form.title.focus();
		return false;
	}
	return true;
}

function validatePhoto(){
  var form = document.getElementById("photo");
	if((form.photo.value=="")){
	  alert("Você precisa selecionar um arquivo");
		form.photo.focus();
		return false;
	}
	return true;
}	

function validateContact(){
  var form = document.getElementById("contact");	
	if((form.name.value=="")||(form.name.value.lenght<5)){
	  alert("Você precisa informar um nome válido.");
		form.name.focus();
		return;
	}
	if((form.email.value=="")||(form.name.value.lenght<5)){
	  alert("Você precisa informar um email válido.");
		form.name.focus();
		return;
	}	
	if((form.subject.value=="")||(form.subject.value.lenght<5)){
	  alert("Você precisa informar um assunto válido.");
		form.subject.focus();
		return;
	}	
	if((form.content.value=="")||(form.content.value.lenght<5)){
	  alert("Você precisa informar uma mensagem válida.");
		form.content.focus();
		return;
	}	
	form.submit();
}
	
