$(document).ready(function(){
  $("#jsError").hide();
  //Set all masks;
  $("input[tipo=DATE]").mask("99/99/9999");
  //$("input[tipo=INT]").numeric();
  $("input[tipo=ALPHA]").alphanumeric();
  $("input[tipo=ALPHA_S]").alphanumeric({allow:" "});
  $("input[tipo=CEP]").mask("99999-999");
  //Put the click function into the submit link;
  $("a[tipo=SUBMIT]").click(function(){
    var formId=$(this).attr('formId');
    $('form[id='+formId+']').submit();
  });
  $("input[type=text]").addClass("margemInput");
  $("input[type=password]").addClass("margemInput");

  //Submit function;
  $("form").submit(function(){
    var formId = $(this).attr('id');
    //Erase all errors;
    var errors = 0;
    $("div[erro=1]").remove();
    //Start the validations for all the inputs;
    $("form[id="+formId+"] :input").each(function(i){
      //Get the velues;
      var required  = $(this).attr('required');
      if($(this).attr('type') == 'radio'){
        radioVal = $("form[id="+formId+"] input[@name="+$(this).attr('name')+"]:checked").val();
        if( radioVal ){
          var value = $("form[id="+formId+"] input[@name="+$(this).attr('name')+"]:checked").val();
        }else{
          var value = '';
        }
      }else{
        var value = $(this).val();
      }
      var length    = ($(this).val()).length;
      var minLength = ($(this).attr('minlength') == null) ? 0 : $(this).attr('minlength');
      addError     = false;
      //Check if is required;
      if( required == 1 ){
        //Check if has value;
        if ( value == '' ) {
          addError = 'required';
        }
      }
      //Check if fits the minlength;
      if ( (minLength > 0) && (length > 0) ) {
        if ( minLength > length ) {
          addError = 'minlength';
        }
      }
      //Check if has error to show;
      if( addError != false ){
        errors++;
        if($(this).attr('type') == 'radio'){
          $(this).addClass('formRadioErro');
          addError = 'radioError';
        }else{
          $(this).addClass('formErro');
        }
        if( addError == 'required' ){
          $(this).after("<div class='obs_red' erro='1'>" + messageInterface["JS_REQUIRED_FIELD"] + "</div>");
        }else if( addError == 'minlength' ){
          var message = messageInterface["JS_MINIMUN_SIZE"].replace("@", minLength);
          $(this).after("<div class='obs_red' erro='1'>" + message + "</div>");
        }else if( addError == 'radioError' ){
          //Do nothing;
        }else{
          $(this).after("<div class='obs_red' erro='1'>" + messageInterface["JS_GENERIC_ERROR"] + "</div>");
        }
      }
    });
    if(formId == "newAccount"){
      //Check if the name is valid;
      var nameObject = $("form[id=newAccount] input[id=nome]");
      var minLength  = ($("form[id=newAccount] input[id=nome]").attr('minlength') == null) ? 0 : $("input[id=nome]").attr('minlength');
      var nameValue  = (nameObject.val()).trim();
      nameObject.val(nameValue);
      var validName  = true;
      var nameArray  = nameValue.split(" ");
      if( ( nameArray.length ) < 2  ){
        validName = false;
      }else{
        for(i = 0; i < nameArray.length; i++){
          if( (nameArray[i].length) <= 0 ){
            validName = false;
          }
        }
      }
      if( validName == false ){
        if( nameValue.length >= minLength ){
          errors++;
          nameObject.addClass('formErro');
          nameObject.after("<div class='obs_red' erro='1'>" + messageInterface["JS_INVALID_NAME"] + "</div>");
        }
      }
      //Validate the captcha;
      var captchaObject = $("form[id=newAccount] input[id=captcha]");
      var workflowCodeObject = $("form[id=newAccount] input[id=workflowCode]");
      var captchaLength      = (captchaObject.val()).length;
      var captchaMinLength   = (captchaObject.attr('minlength') == null) ? 6 : captchaObject.attr('minlength');
      if( captchaLength == captchaMinLength ){ 
        var validCaptcha = $.ajax({type: "POST", url: 'controller.php?action=' + constantList["REGISTER_FORM_HANDLER"] + '&formStep=' + constantList["DEFAULT_FORM_CAPTCHA_VALIDATE"], data: "captchaValue=" + captchaObject.val() + "&workflowCode=" + workflowCodeObject.val() + "&runAction=validateCaptcha", async: false }).responseText;
        if( validCaptcha == 0 ){
          //Just to clean the content before apend any thing new;
          $("td[id=newUserErrorListShell]").html('');
          $("td[id=newUserErrorListShell]").append("<div class='obs_red' erro='1' style='width: 180px;'>"+ messageInterface["CAPTCHA_VALIDATION_ERROR"] +"<br /></div>");
          return false;
        }
      }
    }
    //Check if is all ok;
    if (errors > 0) {
      return false;
    }else{
      $("this").submit();
    }
  });//Submit;
		 
  //Clean the error;
  $("input").keyup(function(){
    $("#errosjs").empty();
    $(this).removeClass('formErro');
  });

  $("input[id=selectionCpf]").click(function(){
    $("input[id=cpf_cnpj]").unmask();
    $("input[id=cpf_cnpj]").mask("999.999.999-99");
  });
  
  $("input[id=selectionCnpj]").click(function(){
    $("input[id=cpf_cnpj]").unmask();
    $("input[id=cpf_cnpj]").mask("99.999.999/9999-99");
  });
  
  $("select").change(function(){
    $("#errosjs").empty();
    $(this).removeClass('formErro');
  });
  
  //Put the click function in the captcha image;
  $("a[tipo=CAPTCHA_HELP]").click(function(){
    $("img[alt=CAPTCHA]").click();
  });

  //Image click function;
  $("img[alt=CAPTCHA]").click(function(){
    var worckflowCode = $("input[id=workflowCode]").val();
    $(this).attr('src', 'controller.php?action=' + constantList["REGISTER_FORM_HANDLER"] + '&formStep=' + constantList["DEFAULT_FORM_CAPTCHA_IMAGE"] + '&rndId=' + $.datemaker('now') + '&workflowCode=' + worckflowCode);
  });

  $(".idLabel").click(function(){
    var elementId=$(this).attr('elementId');
    var formId=$(this).attr('formId');
    if (formId) {
      $("form[id="+formId+"] input[id="+elementId+"]").click();
    } else {
      $("#"+elementId).click();
    }
  });  
  
  //enter submits the form
  //$("form").keydown(function(event){
  //  if (event.keyCode==13) {
  //    $(this).submit();
  //  }
  //});
});
