//
// logic which is executed when the form is submitted:
//  - each fragment is check for clientside validations
//
$(document).ready(function(event) {
    $(".wmpform").bind("IAF_ClientsideFrameworkLoaded",function() {
        if($("#errorholder").length > 0) {
          $(".wmpform").unbind("submit");
          $(".wmpform").submit(function(event) {


              var hasError = false;
              var formId = $(this).attr("id");

              // This js only supports the non ajax variant
              $('#clientsideRouting').val("false");

              if (formId != 'undefined' && formId != '') {
                  // get the formState
                  var formState = WebmanagerFormStateRegistry[formId];

                  if (typeof formState != 'undefined' && formState != '' ) {
                	  if($('#wmradio_collectieve_korting_N').attr('checked')==true) {
                		  $('.collectiviteit-text').html('');
                	  }

                      // loop over the inputs to check the validations
                      var doneFragments = new Array();
                      var formObj = $(this);

                      var objHolder = $('#errorholder');
                      var objButton = $('.button-submit');

                      var fr_total = "";

                      $(':input', $(this)).each(function() {
                          // skip the hidden inputs
                          // stillvalidate for date fields and area code. The real value is hidden.
                          var inputName = $(this).attr("name");

                          if (inputName != 'undefined') {
							  if (typeof(inputName) != 'undefined' && inputName != "" && ($(this).attr("type") != 'hidden' || $(this).hasClass('stillvalidate')) && !doneFragments.contains(inputName)) {
								  var removeClass = true;
								  doneFragments.push(inputName);
								  if (FormValidation.isVisible($(this))) {
									  var obj = $('#error_' + inputName.replace(/\./g, '_'));
									  var objDiv = $('#' + inputName.replace(/\./g, '_'));

									  // Skip the clientside validation if there is no div to show the error message
									  if (obj.length > 0) {

										  obj.hide();
										  var value = FormValidation.getValue($(this));

										  // get the validation errors
										  var arr = formState.validateAndReturnMessage(inputName,value);
										  // build a list of fragment errors
										  for(var item in arr) {
											  hasError = true;
											  removeClass = false;
											  if (objDiv.find('span.label span.name').length > 0) {
												  fr_total += '<li>' + objDiv.find('span.label span.name').html() + '</li>';
											  } else if (objDiv.find('label span.name').length > 0) {
												  fr_total += '<li>' + objDiv.find('label span.name').html() + '</li>';
											  }
										  }
										  objDiv.addClass('error');
										  objDiv.addClass('odditem');
									  }
									  if (removeClass) {
										  objDiv.removeClass('error');
										  objDiv.removeClass('odditem');
									  }
								  } 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 (fr_total != '') {
                      fr_total = '<h2>Let op! Wilt u de volgende velden alstublieft invullen?</h2><ul>' + fr_total + '</ul>';
                      objHolder.html(fr_total);
                      objHolder.show();
                  }

                  // If there is an error: don't submit the form
                  if (hasError) {
                      objButton.addClass('button-submit-error');
                      event.preventDefault();
                  } else {
                      objButton.removeClass('button-submit-error');
                  }
                }
              }
          });
        }

	    // Replace default error handling
	    $('div').unbind('IAF_ShowError');
        $('div[id^="error_"]').bind('IAF_ShowError',function(e, errorDivId, errors) {
				e.stopPropagation();
				var objDiv =  $('#' + errorDivId.replace('error_', ''));
				var errorholder = $('#errorholder');
				if (errorholder.length > 0) {
					// ZenZ presentation specific
					var content = $('#errorholder').html();
					if (content != null && content.indexOf('<li>') == -1) {
						//content = '<h2>Let op! Wilt u de volgende velden alstublieft invullen?</h2><ul><li>' + objDiv.find('label span.name').html() + '</li></ul>';
						content = '<h2>Let op! Wilt u de volgende velden alstublieft invullen?</h2><ul><li>';
						if (objDiv.find('span.label span.name').length > 0) {
							content += objDiv.find('span.label span.name').html();
						} else if (objDiv.find('label span.name').length > 0) {
							content += objDiv.find('label span.name').html();
						}
						content += '</li></ul>';
					} else {

						if (objDiv.find('label span.name').length > 0 && content != null && content.indexOf('<li>' + objDiv.find('label span.name').html() + '</li>') == -1) {
							content = content.replace('</ul>', '<li>' + objDiv.find('label span.name').html() + '</li></ul>');
						}else if(objDiv.find('span.label span.name').length > 0 && content != null && content.indexOf('<li>' + objDiv.find('span.label span.name').html() + '</li>') == -1){

							 content = content.replace('</ul>', '<li>' + objDiv.find('span.label span.name').html() + '</li></ul>');
						}
					}
					$('#errorholder').html(content).show();
					objDiv.addClass('error');
					$('.button-submit').addClass('button-submit-error');
				} else {
				   // IAF default for regular presentations
				   $('#' + errorDivId).html('<ul><li>' + FormsUtil.join(errors,'</li><li>') + '</li></ul>').show();
				}
	    });

	    // Replace default error handling
	    $('div').unbind('IAF_HideError');
	   	$('div').bind('IAF_HideError',function(e, errorDivId) {
	    	e.stopPropagation();
	    	var objDiv =  $('#' + errorDivId.replace('error_', ''));
	    	var content = $('#errorholder').html();
	   		if (content != null && content != '') {
	   			if (objDiv.find('span.label span.name').length > 0) {
	   				content = content.replace('<li>' + objDiv.find('span.label span.name').html() + '</li>', '');
                } else if (objDiv.find('label span.name').length > 0) {
                	content = content.replace('<li>' + objDiv.find('label span.name').html() + '</li>', '');
                }
	   		}
	    	if (content != null && content.indexOf('<li>') == -1) {
	   			$('#errorholder').empty().hide();
	   		} else {
		    	$('#errorholder').html(content).show();
	   		}
	        objDiv.removeClass('error');
	        $('.button-submit').removeClass('button-submit-error');
	    });

	   	/* FIXME: remove errors on hiding fragments
	   	$('div').bind('IAF_ShowFormFragment',function(e, errorDivId) {
	   		if (FormValidation.isVisible($(this))) {
	   		}
	    });

	   	$('div').bind('IAF_HideFormFragment',function(e, errorDivId) {
	    });
		*/
    });
});

Array.prototype.contains = function (element) {
    for (var i = 0; i < this.length; i++) {
        if (this[i] == element) {
            return true;
        }
    }
    return false;
}

