/*
  Funções gerais da SXSS
*/

if(!navigator.javaEnabled()){
  document.write('JavaScript desabilitado!');
}

//Verifica se o JavaScript está funcionando corretamente
function teste(){  
  alert("Script SXSS.JS funcionando corretamente!");
}

//Atualiza a página
function refresh()    {  
  window.location.reload(true);
}

//Deixa o background do campo com erro em vermelho e lhe dá o foco
function error(obj)
{ 
  if(!elementExists(obj)){
     return false;
  }    
  document.getElementById(obj).style.background="#cc4444";
  document.getElementById(obj).focus();  
  return;
}

//Vai para a página de inserção do módulo solicitado/informado
function moduleNew(module){   
  location.href="?module="+module+"&action=edit";
  
  return true;
}

//Compara o valor de dois elementos da tela
function compare(obj1,obj2){  
  if(!elementExists(obj1)){
     return false;
  }
   
  if(!elementExists(obj2)){
    return false;
  }
  
  obja=document.getElementById(obj1).value;
  objb=document.getElementById(obj2).value;
 
  if(obja!=objb){
    initFocus(obj1);
    return false;
  }else{
    return true;
  }
}

//Redirecionamento forçado pelo JavaScript
function fail(){  
  location.href="index.php";
  
  return true;  
}

//Inicia dando foco no objeto solicitado/passado
function initFocus(id){  
  if(!elementExists(id)){
    return false;
  }
  document.getElementById(id).focus();  
  return true;;
}

//Dá foco em um elemento - Alias para initFocus()
function setFocus(id){  
  if(!elementExists(id)){
     return false;
  }
  initFocus(id);
  
  return true;
}

// Adiciona mensagem erro no span de um campo
function addMessage(id,msg){
  if(!elementExists(id+"_error")){
     return false;
  }
  setInner(id+"_error",msg);
  
  return;
 
}

// Gera efeito de erro em um campo
function addError(id,msg){   
  addMessage(id,msg);  
  error(id);
  return true;
}

// Remove erros
function clearError(id){
  addMessage(id,"");
  setInner(id+"_error","");  
  document.getElementById(id).style.background="#ffffff";
}

//Verifica se o valor de um objeto está vazio
function nonNull(id){  
  if(!elementExists(id)){
     return false;
  }
  obj=document.getElementById(id).value;
  if(obj){
    return true;    
  }else{
    initFocus(id);
    return false;
  }
}

//Verifica se um objeto tem valor nulo
function isNull(elementId){  
  if(!elementExists(elementId)){
     return false;
  }
  if(nonNull(elementId)){
    return false;
  }else{
    return true;
  }  
}

//Exibe uma mensagem no sxsspop 
function pop(msg){   
  if(!elementExists('sxsspop')){
     return false;
  }     
  setInner('sxsspop',msg);
  document.getElementById('sxsspop').style.display='inline';
  setTimeout("document.getElementById('sxsspop').style.display='none'",5000); 
}

//Redireciona para a url indicada 
function goTo(module,action,more){  
  if(!more || more==undefined)
    more="";
  if(!action || action==undefined)
    action="index";
  if(!module || module==undefined){
    alert("Módulo não especificado!");
    return false;
  }else{
    location.href="?module="+module+"&action="+action+more;
  }
}

//Atribui um valor para um campo
function setValue(elementId,elementValue){  
  if(!elementExists(elementId)){
     return false;
  } 
  document.getElementById(elementId).value = elementValue;  
  return;
}

//Retorna o valor de um elemento
function getValue(elementId){  
  if(!elementExists(elementId)){
     return false;
  }
  return document.getElementById(elementId).value;
}

//Atribui o InnerHTML a um elemento
function setInner(elementId,elementValue){   
   if(!elementExists(elementId)){
     return false;
   } 
   document.getElementById(elementId).innerHTML = elementValue;     
   return;
}

// Verifica se um elemento existe
function elementExists(elementId){
  if(document.getElementById(elementId)){
    return true;
  }else{
    alert("Objeto  \""+elementId+"\" não existe ou não foi declarado corretamente.");
    return false;
  }
}

// Verifica se um elemento existe, mas não retorna aviso
function checkExists(elementId){
  if(document.getElementById(elementId)){
    return true;
  }else{
    return false;
  }
}

// Limita um campo a um número de caracteres
function countTo(elementid,count){
  if(!elementExists(elementid)){
    return false;
  }
  var fieldValue = getValue(elementid); 
  if(fieldValue.length<count){
    return false;
  }else{
    return true;
  }
  
}

// Redireciona para a página de view, onde será o registro será apagado
function Delete(module,module_id,active){
   
   var confirm_del,confirm_del;
    
   confirm_del = confirm("Apagar registro?");
   if(confirm_del){
     confirm_del1 = confirm("Deseja realmente apagar este registro");
     if(confirm_del1){
       goTo(module,'view',"&delete=delete&id="+module_id+"&active="+active);
     }
   }
      
   return true;
}

// Valida campo de multicheck
function validCheck(elementName){
  
  var choices = document.getElementsByName(elementName);             
  var clicked = 0;
  
  for(i=0;i<choices.length;i++){
    if(choices[i].checked){
      clicked = 1;
    }
  }
       
  if(!clicked){
    return false
  }else{
    return true;
  }
}


// FormValidator Universal

/* This script and many more are available free online at
The JavaScript Source :: http://javascript.internet.com
Created by: Amit Wadhwa :: http://amitwadhwa.fcpages.com/javascript.com/formvalidator.html */

function checkThisForm(formname, submitbutton, errors) {
  //Verifica se o form tem botão de submit
  var formname = formname;
  if (errors == '') {        
    //eval(formname+'.'+submitbutton+'.disabled=true');
    document.getElementById(submitbutton).disabled =true;
    eval('document.'+formname+'.submit()');
  } else {
    alert(errors);
  }
}

function checkText(formname, textboxname, displaytext) {
  //Verifica valor de um campo texto
  var localerror = '';
  if(Trim(eval('document.'+formname+'.'+textboxname+'.value'))=='') {
    localerror =  '- '+displaytext+' é Obrigatório.\n';
  } else localerror = '';
  return localerror;
}

function checkNum(formname, textboxname, displaytext) {
  //Verifica se um campo é numérico
  var localerror = '';
  if(isNaN(eval('document.'+formname+'.'+textboxname+'.value'))) {
    localerror =  '- '+displaytext+' deve conter apenas números.\n';
  } else localerror = '';
  return localerror;
}

function checkSpaces(formname, textboxname, displaytext) {
  //Verifica se já espaços
  var valid = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_'; // define valid characters
  var localerror = '';
  if(!isValid(Trim(eval('document.'+formname+'.'+textboxname+'.value')), valid)) {
    localerror =  '- '+displaytext+' não deve contar espaços.\n';
  } else localerror = '';
  return localerror;
}

function checkSelect(formname, selectboxname, displaytext) {
  //Verifica se algo foi selecionado na lista
  var localerror = '';
  if(eval('document.'+formname+'.'+selectboxname+'.selectedIndex')==0) {
    localerror =  '- '+displaytext+' é Obrigatório.\n';
  } else localerror = '';
  return localerror;
}

function getRadio(formname, radioname, displaytext) {
  //Pega o valor de uma opção Radio
  for (var i=0; i < eval('document.'+formname+'.'+radioname+'.length'); i++) {
    if (eval('document.'+formname+'.'+radioname+'[i].checked')) {
      var rad_val = eval('document.'+formname+'.'+radioname+'[i].value');
      return rad_val;
    }
  }
}

function checkRadio(formname, radioname, displaytext) {
  //Verifica se alguma opção foi selecionada
  var localerror = '';
  var rad_val    = '';
  for (var i=0; i < eval('document.'+formname+'.'+radioname+'.length'); i++) { //check every radio button by that name
    if (eval('document.'+formname+'.'+radioname+'[i].checked'))  { //if it is checked
      rad_val += '-';
      }	else rad_val += '';
      }
    if (rad_val=='') {
      localerror =  '- '+displaytext+' é Obrigatório.\n';
    }
  return localerror;
}

function autoComplete (field, select, property) {
/*onKeyUp="autoComplete(this,this.form.selectboxname,'value',false)" - add this to textbox where you are typing*/
  //Autompleta um campo
  var found = false;
  for (var i = 0; i < select.options.length; i++) {
    if (select.options[i][property].toUpperCase().indexOf(field.value.toUpperCase()) == 0) {
      found=true; break;
    }
  }
  if (found) {
    select.selectedIndex = i;
  } else {
    select.selectedIndex = -1;
  }
  if (field.createTextRange) {
    if (!found) {
      field.value=field.value.substring(0,field.value.length-1);
      return;
    }
    var cursorKeys ="8;46;37;38;39;40;33;34;35;36;45;";
    if (cursorKeys.indexOf(event.keyCode+";") == -1) {
      var r1 = field.createTextRange();
      var oldValue = r1.text;
      var newValue = found ? select.options[i][property] : oldValue;
      if (newValue != field.value) {
        field.value = newValue;
        var rNew = field.createTextRange();
        rNew.moveStart('character', oldValue.length) ;
        rNew.select();
      }
    }
  }
}

function Trim(s) {
  //Remove espações em branco
  while ((s.substring(0,1) == ' ') || (s.substring(0,1) == '\n') || (s.substring(0,1) == '\r')) {
    s = s.substring(1,s.length);
  }
  while ((s.substring(s.length-1,s.length) == ' ') || (s.substring(s.length-1,s.length) == '\n') || (s.substring(s.length-1,s.length) == '\r')) {
    s = s.substring(0,s.length-1);
  }
  return s;
}

function isValid(string,allowed) {
    //Verifica se um campo é válido
    //  var valid = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'; // define valid characters
    for (var i=0; i< string.length; i++) {
      if (allowed.indexOf(string.charAt(i)) == -1) return false;
    }
    return true;
}

/*

Exemplo to use

<script type="text/javascript">

function check(formname, submitbutton) {
  var errors = '';
  errors += checkText(formname, 'textfield1', 'Name');
  errors += checkSelect(formname, 'Country', 'Country Of Residence');
  errors += checkText(formname, 'age', 'Age Of Person');
  errors += checkNum(formname, 'age', 'Age Of Person');
  errors += checkRadio(formname, 'Gender', 'Your gender');
  checkThisForm(formname, submitbutton, errors);
}
</script>

*/

//Fim do FormValidator Universal


//Valida e-mail digitado
function emailCheck (emailStr) {
	/* The following pattern is used to check if the entered e-mail address
	   fits the user@domain format.  It also is used to separate the username
	   from the domain. */
	var emailPat=/^(.+)@(.+)$/
	/* The following string represents the pattern for matching all special
	   characters.  We don't want to allow special characters in the address. 
	   These characters include ( ) < > @ , ; : \ " . [ ]    */
	var specialChars="\\(\\)<>@,;:\\\\\\\"\\.\\[\\]"
	/* The following string represents the range of characters allowed in a 
	   username or domainname.  It really states which chars aren't allowed. */
	var validChars="\[^\\s" + specialChars + "\]"
	/* The following pattern applies if the "user" is a quoted string (in
	   which case, there are no rules about which characters are allowed
	   and which aren't; anything goes).  E.g. "jiminy cricket"@disney.com
	   is a legal e-mail address. */
	var quotedUser="(\"[^\"]*\")"
	/* The following pattern applies for domains that are IP addresses,
	   rather than symbolic names.  E.g. joe@[123.124.233.4] is a legal
	   e-mail address. NOTE: The square brackets are required. */
	var ipDomainPat=/^\[(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})\]$/
	/* The following string represents an atom (basically a series of
	   non-special characters.) */
	var atom=validChars + '+'
	/* The following string represents one word in the typical username.
	   For example, in john.doe@somewhere.com, john and doe are words.
	   Basically, a word is either an atom or quoted string. */
	var word="(" + atom + "|" + quotedUser + ")"
	// The following pattern describes the structure of the user
	var userPat=new RegExp("^" + word + "(\\." + word + ")*$")
	/* The following pattern describes the structure of a normal symbolic
	   domain, as opposed to ipDomainPat, shown above. */
	var domainPat=new RegExp("^" + atom + "(\\." + atom +")*$")
	
	
	/* Finally, let's start trying to figure out if the supplied address is
	   valid. */
	
	/* Begin with the coarse pattern to simply break up user@domain into
	   different pieces that are easy to analyze. */
	var matchArray=emailStr.match(emailPat)
	if (matchArray==null) {
	  /* Too many/few @'s or something; basically, this address doesn't
	     even fit the general mould of a valid e-mail address. */
		//alert("Email address seems incorrect (check @ and .'s)")
		return false
	}
	var user=matchArray[1]
	var domain=matchArray[2]
	
	// See if "user" is valid 
	if (user.match(userPat)==null) {
	    // user is not valid
	    //alert("The username doesn't seem to be valid.")
	    return false
	}
	
	/* if the e-mail address is at an IP address (as opposed to a symbolic
	   host name) make sure the IP address is valid. */
	var IPArray=domain.match(ipDomainPat)
	if (IPArray!=null) {
	    // this is an IP address
		  for (var i=1;i<=4;i++) {
		    if (IPArray[i]>255) {
		        //alert("Destination IP address is invalid!")
			return false;
		    }
	    }
	    return true
	}
	
	// Domain is symbolic name
	var domainArray=domain.match(domainPat)
	if (domainArray==null) {
		//alert("The domain name doesn't seem to be valid.")
	    return false
	}
	
	/* domain name seems valid, but now make sure that it ends in a
	   three-letter word (like com, edu, gov) or a two-letter word,
	   representing country (uk, nl), and that there's a hostname preceding 
	   the domain or country. */
	
	/* Now we need to break up the domain to get a count of how many atoms
	   it consists of. */
	var atomPat=new RegExp(atom,"g")
	var domArr=domain.match(atomPat)
	var len=domArr.length
	if (domArr[domArr.length-1].length<2 || 
	    domArr[domArr.length-1].length>3) {
	   // the address must end in a two letter or three letter word.
	   //alert("The address must end in a three-letter domain, or two letter country.")
	   return false
	}
	
	// Make sure there's a host name preceding the domain.
	if (len<2) {
	   var errStr="This address is missing a hostname!"
	   //alert(errStr)
	   return false
	}
	
	// If we've gotten this far, everything's valid!
	return true;
}
