/* For each form(element) a request will be done to the 'wmpformclientsideframework'-servlet.
     It will add the corresponding formState object to the WebmanagerFormStateRegistry. 
*/
var WebmanagerFormStateRegistry = {};

$(document).ready(function(event) {

	$('a', '#messagePopup').each( function () {
		$(this).click( function(event) {
			$('#lockAll, #messagePopup').hide()
		});
	});

	$('input').each( function () {
		// Trim all input values to avoid Chrome bug
		$(this).val(trim($(this).val()));
	});

	//
	// Check preconditions upon loading the form
	//
	$('.wmpform').find(':input').each(function() {
	  var formId = $(this).parents('form:first').attr("id");

	  if (formId != 'undefined' && formId != '') {
	    var formState = WebmanagerFormStateRegistry[formId];

	    if (typeof formState != 'undefined' && formState != '' ) {

	      attr = $(this).attr("name");
	      if (typeof attr != 'undefined' && attr != '') {
		var done = new Array();

		checkField(formState, $(this), done);
	      }
	    }
	  }
	});

	//
	// Set a change event on all inputs: we can determine clientside if other fields needs to be shown
	//
	$('.wmpform').find(':input').change(function() {
	  var formId = $(this).parents('form:first').attr("id");

	  if (formId != 'undefined' && formId != '') {
	    var formState = WebmanagerFormStateRegistry[formId];

	    if (typeof formState != 'undefined' && formState != '' ) {

	      attr = $(this).attr("name");
	      if (typeof attr != 'undefined' && attr != '') {
		var done = new Array();

		checkField(formState, $(this), done);
	      }
	    }
	  }
	});

});

// checks if the object is visible
function isVisible(obj) {
  var visible = !obj.hasClass('hide');

  obj.parents().each(function() {
   if ($(this).css("display") == 'none') {
      visible = false;
      return false;
    }
  });
  return visible;
}

// Check if an input has to be shown or not
function checkField(formState, obj, done) {
    // If the input is not visible, the value is unknown so other input can also disappear
    var fvalue = getValue(obj);
    done.push(obj.attr("id"));

    // Get the changes: input which needs to be shown or hide
    var changes = formState.setFragmentValue(obj.attr("name"),fvalue);

    for (var i = 0; i < changes.length; i++) {
      // Change object contains the identifier and a value if the input needs to be shown or hide
      var change = changes[i];
      var identifier = change.identifier.replace('.','_');
      
      if (change.value == 'show') {
        $('#ff_' + identifier).attr('style', 'display:block');
      } else {
        $('#ff_' + identifier).attr('style', 'display:none');
      }

      // We need to go recursive because hiding an input can have an effect on other inputs
      var showObj = $('input:[name=' + change.identifier + '],select:[name=' + change.identifier + '],textarea:[name=' + change.identifier + ']');

      if (showObj.length > 0) {
        if (showObj.attr("id") != '' && !done.contains(showObj.attr("id"))) {
           checkField(formState, showObj, done);
        }
      }
    }
}

function getValue(obj) {
  var value = obj.val();

  // for checkboxes we pass the array of values
  if (obj.attr("type") == 'radio') {
    value = $('input[name=' + obj.attr("name") + ']:checked').val();
  } else if (obj.attr("type") == 'checkbox') {
    var values = $('input:checkbox[name=' + obj.attr("name") + ']:checked');
    value = new Array();

    values.each(function() {
      value.push($(this).val());
    });
  } else if ($(obj).attr("title") != "" && value == $(obj).attr("title")) {
    value = "";
  }
  return value;
}

function addErrorMessage(formid, inputName, fr_error) {
  var fieldName = '';
  inputName = inputName.replace('.','_');
  if($('.wmFragmentName','#ff_' + inputName).length)
    fieldName = $('.wmFragmentName','#ff_' + inputName).html();
    
  $('.input,.alert,.gxCheckbox,.gxRadio','#ff_' + inputName).addClass('inputAlert');
  
  errorOb = eval('errorObj' + formid);
  if(errorOb.length){
    errorOb.append('<tr id="error_'+inputName+'"><td class="label" valign="top" style="text-align:right"><strong>! '+fieldName+' </strong></td><td valign="top"> '+fr_error+'</td><td class="alert"></td></tr>');
	$('tr',errorOb).attr('style', 'display:block');
  }
}
				
function validateForm(formId) {
  // prevent clientside validations when going back
  var goback = $('#go_back');
  if (typeof goback != undefined && goback.val() == 'true') {
    return true;
  }
  var myformId = formId;
  hasError = false;
  if (myformId != 'undefined' && myformId != '') {
    // get the formState
    var formState = WebmanagerFormStateRegistry[myformId];
    if (typeof formState != 'undefined' && formState != '' ) {
      // loop over the inputs to check the validations
      var doneFragments = new Array();
      var formObj = $('#' + formId);
      errorOb = eval('errorObj' + formId.replace('wmform_', ''));
      if(errorOb.length){
	  errorOb.html('');
      }
      $(':input', formObj).each(function() {
          // skip the hidden inputs, with some exceptions
          var inputName = $(this).attr("name");
          if (($(this).attr("type") != 'hidden' || $(this).attr("id").indexOf('dateholder_') == 0 ) && (inputName.indexOf('JSB') == -1) 
          	&& ($(this).attr("type") != 'submit') && !doneFragments.contains(inputName) && inputName != "")
          {
            $('.input','#ff_' + inputName).removeClass('inputAlert');
            $('.alert','#ff_' + inputName).removeClass('inputAlert');
			doneFragments.push(inputName);
            if (isVisible($(this))) {
                var value = getValue($(this));
                // get the validation errors
                var fr_error = '';
            	var arr = formState.validateAndReturnMessage(inputName,value);
                for(var item in arr) {
                  fr_error += arr[item];
                }
                if (fr_error != undefined && fr_error != "") {
                  hasError = true;
                  addErrorMessage(formId.replace('wmform_', ''), inputName, fr_error)
                } 
            } else {
                // make the value empty to prevent to be routed to the same step
                // issue: http://jira.gxdeveloperweb.com/jira/browse/GXWMF-626
                switch(this.type) {
                    case 'password':
                    case 'select-multiple':
                    case 'select-one':
                    case 'text':
                    case 'textarea':
                      $(this).val('');
                      break;
                    case 'checkbox':
                    case 'radio':
                      $('input[name=' + $(this).attr("name") + ']').removeAttr("checked");  
                      // add an empty input type="hidden": this because the browser doesn't send an empty radio
                      formObj.append('<input type="hidden" name="' + inputName + '" value="" />');
                }
              }
          }
      });
      // If there is an error: don't submit the form
      return !hasError;
    }
  }
}

/* voting functions */
function submitVotingform(){
	$('#votingform').ajaxSubmit({
		dataType:'html',
		beforeSubmit:function(formData, jqForm, options) {
			return true;
		},
		timeout:1000 * 60,
		error:function(event, XMLHttpRequest, ajaxOptions, thrownError) {
			window.console.log('#votingform submit error');
			/*addErrorMessage('form', 'Fout bij het verzenden van het formulier');*/
		},
		success:function(data) {
			window.console.log('#votingform submit success!');
			//$('#lockAll, #messagePopup').show(); 
		}
	});
}

function trim(str) {
	if (str != undefined) {
		return str.replace(/^\s+|\s+$/g,"");
	}
}
