/**
 * forms.js version 1.1
 * author Dave Bradshaw
 * modified by Mike Speight 11 March 2009
 */

// Create closed namespace for jQuery code.
(function($) {
	
	//Create jQuery plugin methods
	$.fn.extend({
		
		//Bind error checking function to form submit
		addFormCheck	: function(errorSelector){
			
			return this.each(function(){
   
   				//Get current jQuery object
   				var $this = $(this)
				
				//Store error selector, so we can get it back on the event call in.
				$this.attr('errorSelector',errorSelector)		
   		
				//Add method to turn off error flag when field is selected
				$this.find(':input').focus(function(){
					$(this).removeClass('fieldError');
				})
		
				//Add function to form submit
				$this.submit(function(){
					
					try{
						//Display errors
						function showErrors(){
							
							var errStr = '';
							
							//Build error fields list
							for (err in $.kci.errorList)
								errStr += '<li>'+$.kci.errorList[err]+'</li>';
								
							//Show errors
							$('#'+$this.attr('errorSelector')).show().find('ul').html(errStr);
							
							//scroll up
							location.href='#content';
							
							//cancel form submit
							return false;	
						}
						
						function reset(){
							//hide error Messages
							$('span.fieldError').hide();
							$('#'+$this.attr('errorSelector')).hide();
							
							//reset error list
							$.kci.errorList = null;
							$.kci.errorList = new Array();
							
							//reset checkbox list
							$.kci.checkBoxList = null;
							$.kci.checkBoxList = new Array();
						}
						
						//Set up vars
						var retCode = true;
	   					var $this = $(this)
						
						//reset form
						reset();
						
						//Check fields
						$this.find('label').checkFields();
						$this.find('.requiredList').checkCheckBoxListFields();
						
						//Did we get any errors?
						if (0 != $.kci.errorList.length)
							retCode = showErrors();
						
						return retCode;
					}
					catch(err){
						console.error (err);
					}
				});
		  });
		},
		
		checkCheckBoxListFields		: function(){
			return this.each(function(){
				try{
						
					//Display error message and mark field
					function error(msgSelector){
						//add error to list
						$.kci.errorList[$.kci.errorList.length] = $this.prevAll('span.required').eq(0).html();
										
						//show field error message
						$this.prevAll(msgSelector).eq(0).show();		
										
						//mark field
						$('[accept='+accept+']').addClass('fieldError');
					}
					
					var $this = $(this);
					var $input = $('#'+$this.attr('for')); //Get input field from label
					var accept = $input.attr('accept'); //Get group name
					
					if (('checkbox' == $input.attr('type') || 'radio' == $input.attr('type')) && '' != accept){
						
						//record list being checked
						$.kci.checkBoxList[$.kci.checkBoxList.length] = accept;
						
						if(0 == $('[accept='+accept+']:checked').length)
							error('span.fieldError');
					}
				}
				catch(err){
					console.error (err);
				}
			});
		},
		
		checkFields		: function(){	
			return this.each(function(){
				try{
					
					
					//Check content format
					function acceptCheck(){
						
						var val,match;	
						
						//Get content format from HTML
						var accept = $input.attr('accept');
						
						try{
							//Check for regex
							if (undefined != accept && '' != accept){
								if ( '/' == accept.substr(0,1)){
								
								//Get field value
								val = $input.val(); 
								
								//Check field against regex
								match = eval('val.match('+accept+')');
								
								//If no match then throw error
								if ( null == match )
									error('span.acceptError');
								}
							}
						}
						catch(err){
							console.error('Accept error at: ' +$this.html())
						}
						
					}
					
					//Display error message and mark field
					function error(msgSelector){
						
						//show field error message
						$this.prevAll(msgSelector).eq(0).show();		
						
						//mark field
						$input.addClass('fieldError');
						
						//add error to list
						$.kci.errorList[$.kci.errorList.length] = $this.html();
										
						return true;
					}
					
					var $this = $(this);
					var $input = $('#'+$this.attr('for')); //Get input field from label
					var $name = $($input).attr('name');
					var err = false;
					var type = $input.attr('type');
				
					//Check field is required and not empty
					if ($this.hasClass('required') || $this.hasClass('requiredNoStar')) {
						
						//validate checkbox
						if (type == 'checkbox' && $('#' + $this.attr('for') + ':checked').length == 0) {
							err = error('span.fieldError');
						}
						
						//validate radio buttons
						else if (type == 'radio'){
							var radioBtn = $('input:radio:checked').attr('name',$name);
							var valid
							for (var x = 0;x < radioBtn.length; x++)
							{
								valid = radioBtn[x].checked
								if (valid) {break}
							}
							if(!valid)
							{
								err = error('span.fieldError');
							}
						}
						
						//validate inputs
						else 
							if ($input.val() == '') {
								err = error('span.fieldError');
							}
					}
						
					//Check content if no found so far		
					if(!err)
						acceptCheck();
				}
				catch(err){
					console.error(err);
					console.trace();
				}
			});
		
		}
	});
	
	
	$.kci = {
		errorList: new Array(),
		checkBoxList: new Array()
	}
	
	
	
	// Add error handlers on page load
	$(document).ready(function(){ 
		$('form').addFormCheck('formErrors');
	})

})(jQuery);