validations = '';
tabSubmit = false;

$(document).ready(function(){
  defineForm();
  disableTabs();
});

function defineForm() {
  $("#formtabs > ul").tabs();

  $("#formtabs form").submit(formProcess);

  $("#formtabs input").blur(function() {
          $(this).validate.init(this);
  });
  
  $("#formtabs textarea").blur(function() {
            $(this).validate.init(this);
  });

  $("#formtabs a").click(function() { tabClick(this) });

  defineAutoComplete();
  preValidateFormParts();
  defineSubmitButton();
}

function preValidateFormParts() {

  $("#form input").each(function(){
    if ($(this).attr("type") == 'text') {
      myId = $(this).attr("name");
      myValue = $(this).attr("value");
      result = $('#' + myId + '_li').attr("class");
      
      if (myValue != '' && result == 'validated') {
        // check the field
        $(this).validate.init(this);
      }
    }
  });
  
  $("#form textarea").each(function(){
      	myId = $(this).attr("name");
      	myValue = $(this).attr("value");
      	result = $('#' + myId + '_li').attr("class");
  	
	if (myValue != '' && result == 'validated') {
	  // check the field
	  $(this).validate.init(this);
	}
  });
}

function defineSubmitButton() {
  disabled = false;
  $("#form input").each(function(){
    if ($(this).attr("type") == 'text') {
      myId = $(this).attr("name");
      result = $('#' + myId + '_li').attr("class");
	
      if (result == 'validated' || result == 'validated required-error') {
        disabled = true;
      }
    }
  });

  $("#form textarea").each(function(){
      myId = $(this).attr("name");
      result = $('#' + myId + '_li').attr("class");
	
      if (result == 'validated' || result == 'validated required-error') {
        disabled = true;
      }
  });

  if (disabled) {
    $('#submitButton').attr("disabled","disabled");
    $('#submitButton').attr("style","color: #697B91;");
  } else {
    $('#submitButton').attr("disabled","");
    $('#submitButton').attr("style","color: #fff;");
  }

}

function defineAutoComplete() {
  $("input[@class='autocomplete']").autocomplete($("#autocompleteurl").attr("value"), {
    delay:10,
    width: 260,
    selectFirst: false
  });

}

function enableTabs() {
  // disabled the right tabs
  i=0;
  $("#formtabs > ul > li").each(function() {
    $("#formtabs > ul").tabs("enable", i);
    i++;
  });
}

function disableTabs() {
  // disabled the right tabs
  found = false;
  i=0;
  $("#formtabs > ul > li").each(function() {
    if (found) {
      $("#formtabs > ul").tabs("disable", i);
    }
    if ($(this).attr("class").indexOf("selected") != -1) {
      found = true;
    }
    i++;
  });
}


function loadFragment(url,id) {
  if ($("#step-" + step) != null && $("#formtabs > ul").length > 0) {
    $(id).load(url,defineForm);
    disableTabs();
  } else {
    $("#form-container").load(url,defineForm);
  }
}


function tabClick(o) {

  value = o.id;
  value = value.replace('link-step-','');
  currentStep = value;

  // set all form id to bla
  $("#formtabs form").each(function(){
    $(this).attr("id","bla");
  });


  // set the form id of the selected tab to form
  $("#step-" + currentStep + " form").attr("id","form");
  defineSubmitButton();
}


function formProcess(event){
  event.preventDefault();

  if (!tabSubmit) {
    tabSubmit = true;

    enableTabs();

    document.getElementById('selectedformpart').value = '';
    if ($("#formtabs > ul").length > 0) {
      // this is the tabs variant: don't let the form disappear

      $('#form').ajaxSubmit(loadFormResults);
    } else {
      $('#form').ajaxSubmit(loadFormResults);
    }
  }
}



new function() {

       // $.fn.validate = validate() {};
    $.fn.validate = {
        init: function(o) {
          this.validateInput(o);
        },
        validateInput: function(o) {
          if (validations.indexOf('-' + o.id + '-') == -1) {
            validations += '-' + o.id + '-';

            errorMessage = '';
            mapValue = validatorMap.get(o.id);
            if (mapValue != null && mapValue != '') {

              for(var i = 0; i < mapValue.validators.length; i++) {
                regexp = mapValue.validators[i].regexp;
                if (regexp != '' && !o.value.match(regexp)) {
                  errorMessage = mapValue.validators[i].message;
                  break;
                }
              }
              if (errorMessage != '') {
                doError(o,errorMessage);
              } else {
                if (mapValue.serversideValidatorCount > 0) {
                  doValidate(o);
                } else {
                  doSuccess(o);
                }
              }
            }
          }
        }
     };

     function doSuccess(o) {
              $('#' + o.id + '_img').html('<img src="/static/project/richforms/img/accept.gif" border="0" style="float:left;" />');
              $('#' + o.id + '_li').removeClass("required-error");
              $('#' + o.id + '_msg').html("");
              $('#' + o.id + '_li').addClass("success");
              validations = validations.replace('-' + o.id + '-','');
              defineSubmitButton();
     }

     function doInfo(o,m) {
              $('#' + o.id + '_img').html('<img src="/static/project/richforms/img/info.gif" border="0" style="float:left;" />');
              $('#' + o.id + '_li').removeClass("required-error");
              $('#' + o.id + '_li').removeClass("success");
              $('#' + o.id + '_msg').html(m);
              $('#' + o.id + '_li').addClass("selected");
              validations = validations.replace('-' + o.id + '-','');
     }

     function doError(o,m) {
      // $('#myResponse').append('_' + m + '_');


              $('#' + o.id + '_img').html('<img src="/static/project/richforms/img/exclamation.gif" border="0" style="float:left;" />');
              $('#' + o.id + '_li').addClass("required-error");
              $('#' + o.id + '_msg').html(m);
              $('#' + o.id + '_li').removeClass("success");
              validations = validations.replace('-' + o.id + '-','');
     }

     function doValidate(o) {
      $('#' + o.id + '_img').html('<img src="/static/project/richforms/img/loading.gif" border="0" style="float:left;" />');
      // set the selected formpart and validate it
      document.getElementById('selectedformpart').value = o.id;

      $('#form').ajaxSubmit(function (data) {
        result = $(data).find('error').text();
        // trim the result
        result = result.replace(/^\s\s*/, '').replace(/\s\s*$/, '');
        if (result == '') {
          info = $(data).find('info').text();
          info = info.replace(/^\s\s*/, '').replace(/\s\s*$/, '');

          if (info != '') {
            doInfo(o,info);
          } else {
            doSuccess(o);
          }
        } else {
          doError(o,result);
        }

      });

    };


};

function loadFormResults(data) {
  tabSubmit=false;
  script = $(data).find('script').text();
  step = $(data).find('step').text();

  if ($("#step-" + step) != null && $("#formtabs > ul").length > 0) {
    $("#link-step-" + step).click();
  }


  if (script != '') {
    // execute the script
    eval(script);
  } else {
    formerror = $(data).find('formerror').text();
    if (formerror != '') {
      $('#formerror').html(formerror);
    }
  }

}