/**
 * Script to provide basic client side validation for support and feedback forms.
 * 
 * If included, any field marked 'required' will be validated here on the blur event.
 * To use simply wrap the form in a container with an id of 'supportForm' and include this file.
 * You can define custom functions for fields if necessary, an example of which is below for the 'email' field.
 * The default validation function simply checks the submitted value is not empty.
 */

 /**
  * CSS styles for the error messages
  */
var error_styles = [
	{key:'border-width',value:'1px'},
	{key:'border-style',value:'solid'},
	{key:'border-color',value:'#c6696d'},
	{key:'background-color',value:'#FBE3E4'},
	{key:'border-radius',value:'5px'},
	{key:'-moz-border-radius',value:'5px'},
	{key:'-webkit-border-radius',value:'5px'},
	{key:'padding',value:'.8em'},
	{key:'color',value:'#c6696d'},
	{key:'font-face',value:'arial,helvetica,verdana'},
	{key:'font-weight',value:'bold'}
];

/**
 * error messages to be displayed for individual elements.
 * To define a custom error message add a new property to the object
 * with a key that matches the TR element id. So if the id of the table row
 * containing the elment is 'First_Name' the property key will be first_name.
 * Do not remove the fallback message.
 */
var error_messages = {
	fallback:'Please enter a value in the field below',
	email:'Please enter a valid email address'
};


$(document).ready(function(){
  //Restore Cookie values
  if ($.cookie('ss_support_form')) {
    $($.cookie('ss_support_form').replace(/\+/g, "%20").split('&')).each(function () {
      $('#'+ unescape(this.substr(0, this.indexOf('=')).replace(/%20/g, "_")) +' .cookie').val(unescape(this.substr(this.indexOf('=')+1)));
    });
  }

  //Save Cookie values
  $('#supportForm :submit').click(function() {
    var cookie = $(".cookie").serialize();
    $.cookie('ss_support_form', cookie, { expires: 90 });
    return true;
  });

  $('#supportForm :reset').click(function() {
    
	$('#supportForm TR').each(function() {
      if ($(this).find('.required').get(0)) {
		$(this).find("TD").css('background-color', '#ccc');
	  }	  
    });
    return true;
  });

  //Set validation for required fields
  $('#supportForm TR').each(function() {
    if ($(this).find('.required').get(0)) {
      //ss_supportform_set_validation(this);
	  ss_init_validation(this);
    }
  });
});

/**
 * function to initialize form validation.
 * each form input element that has a classname of 'required'
 * is validated by a single function. That function can be a custom
 * function specifically for that element, or the default validation
 * function.
 * The default validation function is simply called 'ss_validate'. Any
 * custom function must use 'ss_validate_' as a prefix, followed by the 
 * name of the form element. So a form element named "Email" could be validated
 * by a custom function called 'ss_validate_email'. Validation functions must
 * accept the HTML Input Element as a parameter and return true|false.
 * @param HTML Table Row Element
 * @returns void
 */
function ss_init_validation(trElem) {
	var inputElem = $(trElem).find(':input').get(0);
	var name= $(inputElem).attr('name').replace(/\ /g, "_");
	name = name.toLowerCase();
	if (eval("typeof ss_validate_"+name+" == 'function'")) {
		var method = eval ("ss_validate_"+name+";");
	} else {
		var method = ss_validate;
	}
	ss_display_error(trElem,method(inputElem),false);
	$(inputElem).bind('blur',function() {
		ss_display_error(trElem,method(this),true);
	});
}

/**
 * function to validate an email address, form element must be named "Email".
 * this is a basic example of a custom validation function
 * @param HTMLinputElement
 * @returns bool
 */
function ss_validate_email(inputElem) {
	var filter=/^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9])+$/;
	return filter.test(inputElem.value);
}

/**
 * Default validation function.
 * If a required field does not have its own validation function
 * it will be validated via this function. Simply checks there is 
 * a value.
 * @param HTMLinputElement the element to validate
 * @returns bool true if valid, false if invalid
 */
function ss_validate(inputElem) {
	return inputElem.value!="";
}

/**
 * function to toggle the user interface display regarding the validity of
 * this form element.
 * Note: if you are changing css styles here you may also need to edit line 20
 * which handles form resets.
 * @param HTMLtrElement the table row element containing the form input element.
 * @param Bool is_valid
 * @returns void
 */
function ss_display_error(trElem, is_valid, show_error) {
	if (is_valid) {
		$(trElem).css('background-color','white');
		if (trElem.hasError) {
			$(trElem.errorRow).remove();
			trElem.hasError=false;
		}
	} else {
		$(trElem).css('background-color','#ccc');
		if (show_error && !trElem.hasError) {
			var col_span = trElem.children.length;
			var error_row = document.createElement("TR");
			var error_td = document.createElement("TD");
			var error_p = document.createElement("P");
			error_row.id = trElem.id+"_error";
			
			for (i=0;i<error_styles.length;i++) {
				$(error_p).css(error_styles[i].key,error_styles[i].value);
			}
			
			$(error_td).attr('colSpan',col_span);
			for (i in error_messages) {
				if (i == trElem.id.toLowerCase()) {
					$(error_p).html(error_messages[i]);
					break;
				}
				$(error_p).html(error_messages.fallback);
			}
			
			error_td.appendChild(error_p);
			error_row.appendChild(error_td);
			$(trElem).before(error_row);
			trElem.hasError = true;
			trElem.errorRow=error_row;
			
		}
	}
}

