//GLOBALS
var w3c = (document.getElementById) ? 1:0
var ns4 = (document.layers) ? 1:0  //browser detect for NS4 & W3C standards
var hasCookies = false;
// tests whether the user accepts cookies, and sets a flag.
if(document.cookie == '') {
 document.cookie = 'hasCookies=yes';
 if (document.cookie.indexOf('hasCookies=yes') != -1) hasCookies = true;
}
else hasCookies = true;

function popUp( loc, w, h, menubar ) {
   if( w == null ) { w = 700; }
   if( h == null ) { h = 500; }
   if( menubar == null || menubar == false ) {
      menubar = "";
   } else {
      menubar = "menubar,";
   }
   //if( NS ) { w += 50; }
   // Need the var or else IE4 blows up not recognizing editorWin
   var editorWin = window.open(loc,'editWin', menubar + 'resizable,scrollbars,left=0,top=0,width=' + w + ',height=' + h);
   //editorWin.focus(); //causing intermittent errors
}

function openPopup(url) {
   window.open(url, "popup", "location=0,status=0,scrollbars=1, resizable=1, width=800, height=500, left=0, top=0");
}
function openPopup2(url) {
   window.open(url, "", "location=1,status=1,scrollbars=1, resizable=1, width=800, height=500, locationbar = 1, directories = 1, resizable = 1, statusbar = 1, toolbar = 1, left=0, top=0");
}

function autonum(nome) {
   var num = nome.value.length;
   var newNum = '';
   for (var i=0; i<num; i++) {
      if ((!(isNaN(nome.value.substr(i,1))) && (nome.value.substr(i,1) != ' ')) || nome.value.substr(i,1) == ',') {
         newNum = newNum + nome.value.substr(i,1);
      }
   }
   nome.value = newNum;
}

// sets a cookie in the browser.
function setCookie(name, value, hours, path) {
 if (hasCookies) {
   if(hours) {
      if ( (typeof(hours) == 'string') && Date.parse(hours) ) var numHours = hours;
      else if (typeof(hours) == 'number') var numHours = (new Date((new Date()).getTime() + hours*3600000)).toGMTString();
   }
   document.cookie = name + '=' + escape(value) + ((numHours)?(';expires=' + numHours):'') + ((path)?';path=' + path:'');
 }
}

// reads a cookie from the browser
function readCookie(name) {
 if (document.cookie == '') return '';
 else {
   var firstChar, lastChar;
   var theBigCookie = document.cookie;
   firstChar = theBigCookie.indexOf(name);
   if (firstChar != -1) {
       firstChar += name.length + 1;
       lastChar = theBigCookie.indexOf(';', firstChar);
       if (lastChar == -1) lastChar = theBigCookie.length;
       return unescape(theBigCookie.substring(firstChar, lastChar));
   }
   else return '';
 }
}
  
//funcao para redimensionar janela
function resizeWindow(p_width, p_height) {
   self.resizeTo(p_width, p_height);
   if(window.navigator.userAgent.indexOf("SV1") != -1){
      window.resizeBy(0, 30);
   }
}

//funcao para calcular valor!
function checkNumber() {
   var keyCode = 0;
   
   if (document.all) {
      keyCode = window.event.keyCode;
      event.cancelBubble = true
   } else {
      keyCode = event.which;
   }
   var isNum = (keyCode >= 48 && keyCode <= 57);
   if(document.all)
      event.returnValue = isNum
   else
      return isNum
}

function formatNumber(field,dec) {
   var numCaract = 0;
   var newNum = '';
   var jn = /[^[0-9]]*/gi;

   var num = field.value.replace(jn,'').replace(/^0/,'');
   if(num.length <= dec)
      for(var cont = 0; num.length <= dec; cont++)
         num = '0' + num;
   for(cont = num.length - 1; cont >= 0; cont--) {
      newNum = num.substr(cont,1) + newNum;
      if(dec > 0 && numCaract == dec - 1)
         newNum = ',' + newNum;
      else if(((numCaract - dec) % 3 == 2) && (numCaract < num.length-1))
         newNum = '.' + newNum;
      numCaract++;
   }
   if(newNum.substr(0,1) == ',')
      newNum = '0' + newNum;
   field.value = newNum;
}


function SaveCookie(name, value, expire)
{
   if (parseInt(value) || expire == 0) {
      if (expire == 0) value = 0;
      var eDate = new Date();
      eDate.setDate(eDate.getDate() + expire);
      document.cookie = name + "=" + value + "; expires=" +  eDate.toGMTString()+ "; path=/";
       window.location.reload();
   } else {
      alert('Tempo inválido.');
   }
}

function validacaoEmail(email, msg, alerta) {
   if (alerta == null) alerta = true;
   return validationEmail(email, msg, alerta);
}

function validationEmail(email, msg, alerta) {
   if (alerta == null) alerta = true;
   if (msg == null) msg = 'E-mail';
   if (email.value.indexOf ('@',0) == -1 || email.value.indexOf ('.',0) == -1 || email.value.indexOf ('@.',0) >= 1 || email.value.indexOf ('.@',0) >= 1 || email.value.indexOf ('..',0) >= 1) {
      if (alerta == true || alerta == 1) {  
         alert('Favor preencher o campo '+msg+'');
         email.focus();
      }
      return false;
   } else return true;
}

function validacaoLogin(em, se) {
   if (em == null || em == '') em = 'email';
   if (se == null || se == '') se = 'senha';
   doc1 = document.getElementById(em);
   doc2 = document.getElementById(se);
   if (doc1 == null || doc2 == null) return false;
   if (validationEmail(doc1) == false) {
      return false;
   }
   if (doc2.value.length == 0) {
      alert('Favor preencher o campo senha');
      doc2.focus();
      return false;
   }
   return true;
}

function validacaoForm1(op) {
   doc=document.form1;
   switch(op) {
      case '1':case 'ad':
         //adicionar
         return true;
      break;
      case '2':case 'ed':
         //editar
         return true;
      break;
      case '3':case 'ex':
         //excluir
         if (confirm('Confirmar exclusão?')) {
            return true;
         } else {
            return false;
         }
      break;
      case '4':case 'li':
         //liberar
         if (confirm('Confirmar liberação?')) {
            return true;
         } else {
            return false;
         }
      break;
      case '5':case 'bl':
         //bloquear
         if (confirm('Confirmar Bloqueio?')) {
            return true;
         } else {
            return false;
         }
      break;
      case '6':case 'bu':
         //buscar
      break;
      case '7': case 'em':
         //email
         if (confirm('Confirmar envio de e-mail?')) {
            return true;
         } else {
            return false;
         }
      break;
      case '8':case 'ge':
         //gerar planilha
         if (confirm('Confirmar geração de planilha?')) {
            return true;
         } else {
            return false;
         }
      break;
      case '9':case 'en':
         //enviar
          if (confirm('Confirmar envio?')) {
            return true;
         } else {
            return false;
         }  
      break;
      case '10':case 'ca':
         window.location='?';
         return false;
      break;
      case '11':case 'pr':
         if (confirm('Confirmar processamento?')) {
            return true;
         } else {
            return false;
         }
      break;
      case '12':case 'up_xml':
         if (confirm('Confirmar upload de XML?')) {
            return true;
         } else {
            return false;
         }
      break;
      case '13':case 'ge_xml':
         if (confirm('Confirmar geração de XML?')) {
            return true;
         } else {
            return false;
         }
      break;   
      case 'exremi':
         //excluir
         if (confirm('Confirmar exclusão de registros desta mídia?')) {
            return true;
         } else {
            return false;
         }
      break;
      case 've':
         //verificar
         if (confirm('Confirmar verificação?')) {
            return true;
         } else {
            return false;
         }
      break;
      case 'veFa':
         //verificar fabricante
         if (confirm('Verificar fabricante para todos os modelos deste fabricante?')) {
            return true;
         } else {
            return false;
         }
      break;
      case 'naVeFa':
         //Nao verificar fabricante
         if (confirm('Não verificar fabricante para todos os modelos deste fabricante?')) {
            return true;
         } else {
            return false;
         }
      break;
      case 'de':
         //Desativar
         if (confirm('Confirma desativação?')) {
            return true;
         } else {
            return false;
         }
      break;
   }
}

function validacaoTdLeftSpan() {
   //limpar className das tdLeftSpan
   for (var i=1; i<=15; i++) {
      var orig = 'idTdLeftSpan'+i;
      if (document.getElementById(orig) != null) document.getElementById(orig).className= '';
      else break;
   }
}

function validacaoInidiqueAmigo() {
   if (document.getElementById('nome1IA').value.length == 0) {
      alert('Favor preencher o campo nome');
      document.getElementById('nome1IA').focus();
      return false;
   }
   if (!validationEmail(document.getElementById('email1IA'))) {
      return false;
   }
   if (document.getElementById('nome2IA').value.length == 0) {
      alert('Favor preencher o campo nome do(a) amigo(a)');
      document.getElementById('nome2IA').focus();
      return false;
   }
   if (!validationEmail(document.getElementById('email2IA'), 'e-mail do(a) amigo(a)')) {
      return false;
   }
   refreshPage('../geral/indicar_amigo.php?acao=ad&nome1='+document.getElementById('nome1IA').value+'&email1='+document.getElementById('email1IA').value+'&nome2='+document.getElementById('nome2IA').value+'&email2='+document.getElementById('email2IA').value+'&url='+document.getElementById('urlIA').value, 'idDivDescription');
   return true;
}

function validacaoParticipanteCurso(idCurso) {
   if (document.getElementById('nomePC').value.length == 0) {
      alert('Favor preencher o campo nome');
      document.getElementById('nomePC').focus();
      return false;
   }
   if (!validationEmail(document.getElementById('emailPC'))) {
      return false;
   }
   if (document.getElementById('telefonePC').value.length == 0) {
      alert('Favor preencher o campo Telefone.');
      document.getElementById('telefonePC').focus();
      return false;
   }
   if (document.getElementById('curso1PC').checked == false && document.getElementById('curso2PC').checked == false) {
      alert('Favor preencher o campo Curso do que participou.');
      return false;
   }
   if (document.getElementById('curso1PC').checked == true) {
      var curso = document.getElementById('curso1PC').value;
   } else {
      var curso = document.getElementById('curso2PC').value;
   }
   refreshPage('../geral/participante_curso.php?acao=ad&idCurso='+idCurso+'&nome='+document.getElementById('nomePC').value+'&email='+document.getElementById('emailPC').value+'&telefone='+document.getElementById('telefonePC').value+'&curso='+curso, 'idDivDescription');
   return true;
}

function validacaoChecarEmail(em1, em2, dest) {
   if (em1.length > 0 && em2.length > 0) {
      if (em1.length == 0) {
         document.getElementById(dest).className = 'texto_nao_validado';
      } else {
         if (em1 == em2) {
            document.getElementById(dest).className = 'texto_validado';
         } else {
            document.getElementById(dest).className = 'texto_nao_validado';
         }
      }
   }
}

function validacaoChecarSenha(ps1, ps2, dest) {
   if (ps1.length > 0 && ps2.length > 0) {
      if (ps1.length == 0) {
         document.getElementById(dest).innerHTML = '';
         document.getElementById(dest).className = 'texto_nao_validado';
      } else {
         if (ps1.length >= 4 && ps1 == ps2) {
            document.getElementById(dest).className = 'texto_validado';
         } else {
            document.getElementById(dest).className = 'texto_nao_validado';
         }
      }
   }
}

function validacaoCadastroLimpar() {
   var doc = document.getElementById('idDivCheck');
   var docInputNumber = doc.getElementsByTagName('input').length;
   for (var i=0; i<docInputNumber;i++) {
      doc.getElementsByTagName('input')[i].checked = false;
   }
}

function validacaoCadastroNivel(chk, op) {
   var doc = document.getElementById('idDivCheck');
   var docInputCheckedNumber = 0;
   var docInputCheckedNivel0 = false;
   var docInputCheckedNivelArray = new Array(4);
   if (doc != null) {
      var docInputNumber = doc.getElementsByTagName('input').length;
      for (var i=0; i<docInputNumber;i++) {
         if (doc.getElementsByTagName('input')[i].checked == true) {
            docInputCheckedNivelArray[i] = true;
            docInputCheckedNumber++;
         }
      }
      if (docInputCheckedNumber > 0 || docInputCheckedNivelArray[0]) {
         //uma das opcoes esta selecionada.
         if (docInputCheckedNivelArray[0]!=true) {
            //selecionar nivel 0
            doc.getElementsByTagName('input')[0].checked = true;
            docInputCheckedNumber++;
         }
         if (docInputCheckedNivelArray[2] == true || docInputCheckedNivelArray[3] == true) {
            //selecionado nivel2 e/ou 3
            ElementFadeInOut('idDivCadastroEndereco', 1);
         } else {
            ElementFadeInOut('idDivCadastroEndereco', 0);
         }
         if (docInputCheckedNumber >= 1) {
            
            ElementFadeInOut('idDivCadastroNivel0', 1);
            ElementFadeInOut('idDivCadastroNivelBotao', 1);
         }
      } else {
         //nenhuma opcao selecionada
         ElementFadeInOut('idDivCadastroNivel0', 0);
         ElementFadeInOut('idDivCadastroEndereco', 0);
         ElementFadeInOut('idDivCadastroNivelBotao', 0);
      }
      if (chk == true) {
         //selecionado
         switch(op) {
            case '0':
               document.getElementById('idCheck0').checked = true;
               ElementFadeInOut('idDivCadastroNivel0', 1);
               ElementFadeInOut('idDivCadastroNivelPolitica', 1);
            break;
            case '1':
               document.getElementById('idCheck0').checked = true;   
               document.getElementById('idCheck1').checked = true;
               ElementFadeInOut('idDivCadastroNivel1', 1);
            break;
            case '2':
               document.getElementById('idCheck0').checked = true;
               document.getElementById('idCheck2').checked = true;
               ElementFadeInOut('idDivCadastroNivel2', 1);
               ElementFadeInOut('idDivCadastroEndereco', 1);
               ElementFadeInOut('idDivCadastroNivelTermo', 1);
            break;
            case '3':
               document.getElementById('idCheck0').checked = true;
               document.getElementById('idCheck3').checked = true;
               ElementFadeInOut('idDivCadastroNivel3', 1);
               ElementFadeInOut('idDivCadastroEndereco', 1);
            break;
         }
      } else {
         //nao selecionado
         switch(op) {
            case '0':
               if (docInputCheckedNumber > 1) {
                  //outros niveis selecionado! nao permitir desabilitar nivel 0
                  alert('Esta opção não pode ser desabilitada enquanto as outras opções estiverem selecionadas.');
               } else {
                  ElementFadeInOut('idDivCadastroNivel0', 0);
                  ElementFadeInOut('idDivCadastroNivelBotao', 0);
                  ElementFadeInOut('idDivCadastroNivelPolitica', 0);
               }
            break;
            case '1':
               ElementFadeInOut('idDivCadastroNivel1', 0);
            break;
            case '2':
               ElementFadeInOut('idDivCadastroNivel2', 0);
               ElementFadeInOut('idDivCadastroNivelTermo', 0);
            break;
            case '3':
               ElementFadeInOut('idDivCadastroNivel3', 0);
            break;
         }
      }
   }
}

function changeClassName(dest, className) {
   if (document.getElementById(dest) != null && className != null) {
      document.getElementById(dest).className = className;
   }
}

function redirectPage(url) {
   window.location = url;
}
   
function URLencode(sStr) {
   while (sStr.indexOf('\n') != -1) {
      sStr = sStr.replace('\n', ' ');
   }
   return escape(sStr).replace(/\+/g, '%2B').replace(/\"/g,'%22').replace(/\'/g, '%27').replace(/\//g,'%2F');
}

function filterRedirectPage(url) {
   
   return URLencode(url);
}

function executeRefreshPage(timeExec, url) {
   if (timeExec == '' || !timeExec) timeExec = '30000';
   window.setTimeout("refreshPage('./inicio.php?refr=1&"+url+"&timeExec="+timeExec+"', 'idDivResult');", timeExec);
   window.setTimeout("executeRefreshPage('"+timeExec+"', '"+url+"');", timeExec);
}

function positionScroll(h, start, changePositionScroll) {
   if (start == null) start = 0;
   if (changePositionScroll == null) changePositionScroll = true;
   h = parseInt(h);
   if (window.scrollY)
      scrSt = window.scrollY;
   else if (document.documentElement.scrollTop)
      scrSt = document.documentElement.scrollTop;
   else
      scrSt = document.body.scrollTop;
   if (scrSt < 175) {
      scrStNext = 0;
   } else {
      scrStNext = 175;
   }
   
   if (changePositionScroll) {
      window.scrollTo(0, scrStNext);
   } else {
      scrStNext = scrSt;
   }
   document.getElementById('idLoading').style.left = 0;
   document.getElementById('idLoading').style.top = scrStNext;
   document.getElementById('idLoading').style.margin = 5;
}

//posiciona div no de acordo com altura do scroll
function resizeScrollPosition(id) {
   var scrollTop;
   if (navigator.appName == "Microsoft Internet Explorer"){var position = document.body.scrollTop;}
   else {var position = window.pageYOffset;}
   scrollTop = position;
   document.getElementById(id).style.top = scrollTop+'px';
   
}

function changeFontSize(size, dest) {
   if (dest==null) dest = "texto";
   if (size==null||size==0) size = "10";
   if ($("#"+dest) != null) {
      $("#"+dest).animate({ 
        fontSize: size+"px"
      }, 1500 );
   }
}

function changeOpacity(dest, perc) {
   //perc = 0 ~ 1
   var perc2 = perc*100;
   if ($("#"+dest) != null) {
      $("#"+dest).animate({ 
        opacity: perc,
        Alpha:perc2,
        Alpha:('opacity='+perc2)
      }, 500 );
   }
}

//funcao para autotab
//ex. autoTab(this, 11, event)
var isNN = (navigator.appName.indexOf("Netscape")!=-1);
function autoTab(input,e) {
   var len = input.maxLength;
   var keyCode = (isNN) ? e.which : e.keyCode;
   var filter = (isNN) ? [0,8,9] : [0,8,9,16,17,18,37,38,39,40,46];
   if((input.value.length >= len) && !(containsElement(filter,keyCode))) {
      input.value = input.value.slice(0, len);
      input.form[(getIndex(input)+1) % input.form.length].focus();
   }
   
   function containsElement(arr, ele) {
      var found = false, index = 0;
      while(!found && index < arr.length)
         if(arr[index] == ele)
            found = true;
         else
            index++;
      return found;
   }
   
   function getIndex(input) {
      var index = -1, i = 0, found = false;
      while (i < input.form.length && index == -1)
         if (input.form[i] == input) index = i;
         else i++;
      return index;
   }
   return true;
}


function changePosition(orig, idDest) {
   if (orig && idDest) {
      position = returnPositionObject(orig);
      document.getElementById(idDest).style.top    = position[1] + "px";
      document.getElementById(idDest).style.left   = position[0] + "px";
      document.getElementById(idDest).style.display = "block";
      
      
      
   }
}


//acha e retorna posicao do objeto repassado
function returnPositionObject(obj) {
   var curleft = curtop = 0;
	if (obj.offsetParent) {
		curleft = obj.offsetLeft
		curtop = obj.offsetTop
		while (obj = obj.offsetParent) {
			curleft += obj.offsetLeft
			curtop += obj.offsetTop
		}
      curtop -= 2;
	}
	return [curleft,curtop];
}

//necessario crirar idDivDescription para realizar esta funcao
function mostraComentario(orig, url, dest) {
   if (dest == null) dest = "idDivDescription";
   if (orig != null && url != null) {
      var leftTop = returnPositionObject(orig);
      document.getElementById(dest).style.top = (leftTop[1]+20) + "px";
      document.getElementById(dest).style.left = leftTop[0] + "px";
      ElementShowHidden(dest, 1);
      refreshPage(url, dest);
   }
}

var sTime = null;
function escondeComentario(dest) {
   if (dest == null) dest = "idDivDescription";
   sTime = setTimeout("ElementShowHidden('"+dest+"', 0);", 1500);
}

function mousePositionX(e) {
   if (!document.all) {
      tempX = event.clientX + document.body.scrollLeft
   } else {
      tempX = e.pageX
   }  
  return tempX;
}

function mousePositionY(e) {
   if (!document.all) {
      tempY = event.clientY + document.body.scrollTop
   } else {
      tempY = e.pageY
   }  
   return tempY;
}

function returnWindowSizeX() {
   if (document.documentElement && document.documentElement.offsetWidth && document.documentElement.offsetWidth > 0) {
      width = document.documentElement.offsetWidth;
   } else {
      width = document.body.offsetWidth;
   }
   return width;
}

function returnWindowSizeY() {
   if (document.documentElement && document.documentElement.offsetHeight && document.documentElement.offsetHeight > 0) {
      width = document.documentElement.offsetHeight;
   } else {
      width = document.body.offsetHeight;
   }
   return width;
}

function formatCEP(dest){
   var newCep = '';
   if (dest.value.length >= 1) {
      for (var i=0; i<dest.value.length; i++) {
         if ((!isNaN(dest.value.substr(i,1)) && (dest.value.substr(i,1) != ' ')) || dest.value.substr(i,1) == '-') {
            newCep = newCep + dest.value.substr(i,1);
         }
      }
   }
   dest.value = newCep;
   var aux = dest.value.replace(/[^0-9]/, '');
   if(aux.length>5) {
      dest.value=dest.value.replace(/^([0-9]{5})([0-9]{0,3})$/, '$1-$2');
   }
}

function formatPalestranteHorario(dest){
   var aux = dest.value.replace(/[^0-9]/, '');
   if(aux.length>2) {
      dest.value=dest.value.replace(/^([0-9]{2})([0-9]{0,3})$/, '$1h$2');
   }
}

function limitTextLength(dest, v) {
   if (dest.value.length > v) {
      dest.value = dest.value.substring(0,150);
   }
}