// AT Form.js - A jQuery Plugin
// Version 1.1
// Author - Andy Tennison / http://www.tennisons.com
/*
form plugin
	- swap all checkboxes
	- swap all select boxes
	- .hover on input.submits
	- form validation

*/
(function($) {
    //////////////////////////////////////////////////////////////////////////////
    // for each instance of the lightbox

    $.fn.ATform = function(options) {
        var opts = $.extend({}, $.fn.ATform.defaults, options);
	

        ///////////////////////////////////////////////////////////////////////////////			
        // EACH //
        return this.each(function(i) {
            debug(i + ' - ' + $(this).text());
			
			var $f = $(this);

            /////////////////////////////////////////////////////////////////////////////
            // set basic click actions
			$('input:checkbox').focus(function(){
				$(this).next('.slFake').click()
				$(this).next('.slFake').focus()
			});
	
			$('select').focus(function(){
				$(this).next('.slFake').click()
				$(this).next('.slFake').focus()
			});
			
			
			var $cb = [], $sl = [], $txt = [];
			
			// EACH checkbox
			$f.find('input:checkbox').each(function(i){

				$cb[i] = new Object;
				$cb[i].box = $(this);
				
				if($(this).parent('span.scfCheckbox').length || $(this).parents('table.scfCheckBoxList').length){

				} else {
				
				}
				
				$cb[i].label = $(this).parent('label');
				$cb[i].box.after('<a href="#" class="cbFake"></a>');
				$cb[i].fake = $cb[i].box.next('.cbFake');
				
				if($cb[i].box.is(':checked')){
					$cb[i].fake.addClass('checked')	
				}
				$cb[i].label.bind("click", function(e){
					e.preventDefault();
				});
				$cb[i].fake.bind("click",function(e){
					e.preventDefault();
					if($cb[i].fake.hasClass('checked')){
						$cb[i].fake.removeClass('checked')
						$cb[i].box.removeAttr('checked');
						$cb[i].fake.addClass("hoverOff").removeClass("hoverOn")
					} else {
						$cb[i].fake.addClass('checked')	
						$cb[i].box.attr('checked','checked')
						$cb[i].fake.removeClass("hoverOff").addClass("hoverOn")
					};
				}).bind("mouseenter", function(e){
					if($cb[i].fake.hasClass('checked')){
						$cb[i].fake.addClass("hoverOn");
					}else{
						$cb[i].fake.addClass("hoverOff");
					}
				}).bind("mouseleave", function(e){
					$cb[i].fake.removeClass("hoverOff").removeClass("hoverOn");
				}).bind("focus", function(e){
					if($cb[i].fake.hasClass('checked')){
						$cb[i].fake.addClass("hoverOn");
					}else{
						$cb[i].fake.addClass("hoverOff");
					}
				}).bind("blur", function(e){
					$cb[i].fake.removeClass("hoverOff").removeClass("hoverOn");
				})
			}); // END checkbox
			
			// EACH select box
			$f.find('select:visible').each(function(i){
			    
			    // KHH DISABLE FANCY SELECT
			    return;
			    
				if(!$(this).attr('size') || $(this).attr('size') == 1){
					$sl[i] = new Object;
					$sl[i].box = $(this);
					$sl[i].box.wrap('<div class="select"></div>').after('<div class="slInner"><input type="text" class="slFake" value="" /></div>');
					$sl[i].container = $sl[i].box.next('.slInner');
					$sl[i].fake = $sl[i].box.next('.slInner').find('.slFake');
					$sl[i].fake.css({'width':($sl[i].box.width()-6), 'height':($sl[i].box.height())});
					
					$sl[i].list = [];
					$sl[i].fake.after('<ul class="liFake"></ul>');
					$sl[i].ul = $sl[i].fake.next('.liFake');
					$sl[i].ul.css({'width':($sl[i].box.width()-14)}) //'top':($sl[i].box.height()+4), 
					
					$sl[i].length = $sl[i].box.find('option').length;
					var opSelected = -1;
					
					$sl[i].box.find('option').each(function(ii){
						$sl[i].list[ii] = new Object;
						$sl[i].list[ii].option = $(this);
						$sl[i].list[ii].name = $sl[i].list[ii].option.text();
						$sl[i].ul.append('<li><a href="#">'+$sl[i].list[ii].name+'</a></li>');
						$sl[i].list[ii].li = $sl[i].ul.find('li:last')
						
						if($sl[i].list[ii].option.is(':selected')){
							opSelected = ii;
							$sl[i].list[ii].option.addClass('on');
							$sl[i].list[ii].li.addClass('on');
							$sl[i].fake.attr('value',$sl[i].list[ii].name);
						}
						
						
						////////////////////////////////////////////////////////////
		
						$sl[i].list[ii].li.bind("mouseenter", function(e){
							$(this).addClass("hover");
						}).bind("mouseleave", function(e){
							$(this).removeClass("hover");
						}).find('a').bind("click", function(e){
							e.preventDefault();
							debug('opSelected='+opSelected+', this ii='+ii)
							if(opSelected !== ii) {
								// remove of old current
								$sl[i].list[opSelected].option.removeAttr('selected');
								$sl[i].list[opSelected].option.removeClass('on');
								$sl[i].list[opSelected].li.removeClass('on');
								
								// add to new current
								$sl[i].fake.attr('value',$sl[i].list[ii].name);
								$sl[i].list[ii].option.attr('selected','selected');
								$sl[i].list[ii].option.addClass('on');
								$sl[i].list[ii].li.addClass('on');
								opSelected = ii;
							}
							closeSL($sl[i]);
						}); // .click / .mouseEnter / .mouseLeave
					
					}) // END each.options
					
					$sl[i].box.bind('focus',function(){
						$sl[i].fake.focus();
					});
					
					$sl[i].container.bind('mouseenter',function(){
						openSL($sl[i]);
					}).bind('mouseleave', function(){
						closeSL($sl[i]);
					});
					
					$sl[i].fake.bind('focus',function(){
						openSL($sl[i]);
					});
					
					$sl[i].ul.bind('mouseleave', function(){
						//closeSL(SL);
					});
					
				}
			}); // END select box
			
			function openSL(SL){
				if($(SL.ul).is(':hidden')){
					SL.ul.slideDown(200);
					SL.fake.addClass('focus')
				}
			}
			function closeSL(SL){
				if($(SL.ul).is(':visible')){
					SL.ul.slideUp(200);
					SL.fake.removeClass('focus')
				}
			}
			
			
			// EACH input type=text, default text from title attribute
			$f.find('input[type=text][title]').each(function(i){
				$txt[i] = new Object;
				$txt[i].box = $(this);
				$txt[i].title = $(this).attr('title');
				$txt[i].val = $(this).attr('value');
				
				$txt[i].box.attr('value',$txt[i].title);
				
				$txt[i].box.bind('focus', function(){
					if($(this).attr('value') === $txt[i].title){
						$(this).attr('value','')
					};
				}).bind('blur', function(){
					if($(this).attr('value') === $txt[i].title || $(this).attr('value') === ''){
						$txt[i].box.attr('value',$txt[i].title);
					};
				});
			}); // END text input
		
		
		
			//$s = $f.find('input[type=submit]:first');
			//$s.click(function(e){});
			
			
			// form validation
			if($f.hasClass('validate')){
				// user actions
				var json = $f.find('input[name=validation]').attr('value')
				var fields = eval("(" + json + ')');
				if(fields){
					$f.find('input[type=submit]').click(function(){
						valid = validator($f);
						alert('valid='+validator($f))
						return (valid == true) ? true : false;
					});
					/*
					$('input').blur(function(){
						valid = validator($f);
					});
					*/
				}
			}
			
			function clearErrors(fs) {
				debug('errors cleared')
				$f.find('li').removeClass('error');
				$f.find('p.errMsg').hide() //.slideUp(200)
				formValid = 'none';
			}
			
			function displayErrors(field) {
				$f.find('label[for='+field.id+']').parent('li').addClass('error');
				$f.find('label[for='+field.id+']').siblings('p.errMsg').slideDown(200);
			};
			
			function validator(fs){
				debug('validator called')
				clearErrors(fs);
				valid = true;
				
				fs.find(':input').each(function(){
					currentInput = this;
					
					// normalise ID by stripping out passenger count number
					//getId = currentInput.id.split('_')[2];
					getId = currentInput.id.slice(currentInput.id.lastIndexOf('_')+1, currentInput.id.length);
					//getId = currentInput.id;
					if(fields[getId]){
						debug(getId)
						fieldRule = fields[getId];
						if(fieldRule.required){ // field is required
							if(currentInput.value == ''){
								displayErrors(currentInput);
								valid = false;
								formValid = false;
							}
						}
						if(fieldRule.actions){
							stringToValidate = currentInput.value;
							$.each(fieldRule.actions, function(name,value){
								if(rules[name]){
									internalValidity = rules[name](stringToValidate,value);
									if(!internalValidity){
										displayErrors(currentInput);
										valid = false;
										formValid = false;
										return false;
									};
								}else{
									debug('cant find validation rule for'+name+' '+value)
								};
							});
						};
					};
				});
				
			}
			
			


        }); // END this.each


        ///////////////////////////////////////////////////////////////////////////////			
        // FUNCTIONS //

    }; // end plugin ATform

    // private function
    function debug(txt) {
        if (window.console && window.console.log)
            window.console.log('debug: ' + txt);
    }

    $.fn.ATform.defaults = {
        innerContent: '',
        contentMarker: '.lbContent', // class to show content that is copied in AJAX
        topOffset: 20, 		// lightbox distance from top of screen
        galleryWidth: 708, 	// lightbox width
        videoWidth: 610, 		// lightbox width
        formWidth: 470, 		// lightbox width
        lbColor: '#000000', 	// lightbox background-color
        bgOpacity: 0.7, 		// opacity of background mask
        localForm: 'form',		// class for local form
        textareaLength: 200     // max length for all textareas
    };

})(jQuery);// end of closure

var rules = {
	string: function(value,test) {
		if (typeof test == 'boolean') {
			testVal = (value != '') ? true : false;
		} else {
			temp = test.join('|');
			testVal = (temp.match(value) != '') ? true : false;
		}
		return testVal;
	},
	regexp: function(value,test){
		myRegex = new RegExp(test);
		testVal = (value.match(myRegex)) ? true : false;
		return testVal;
	},
	minLength: function(value,test){
		testVal = (value.length >= test) ? true : false;
		return testVal;
	},
	maxLength:function(value,test){
		testVal = (value.length <= test) ? true : false;
		return testVal;
	},
	phonenumber: function(value,test) {		
		testVal = (value.match(/^[\d\s]*$/)) ? true: false;
		return testVal;
	},
	integer: function(value,test) {
		testVal = (value.match(/^\d*$/)) ? true : false;
		return testVal;
	}
}

/*
var fields = {
	"txtFromName":{
		"required":true,
		"actions":{
			"regexp":"^[A-Za-z\s\-]*$",
			"minLength":"2",
			"maxLength":"24"
		}
	},
	"txtFromEmail":{
		"required":true,
		"actions":{
			"regexp":"^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$",
			"minLength":"2",
			"maxLength":"30"
		}
	},
	"f_address":{
		"required":true,
		"actions":{
			"regexp":"^[A-Za-z\s\-]*$",
			"minLength":"2",
			"maxLength":"20"
		}
	},
	"f_title":{
		"required":true,
		"actions":{
			"string":["Mr","Mrs","Ms","Miss","Dr","Lord","Lady"],
		}
	},
	"f_phone":{
		"required":true,
		"actions":{
			"phonenumber": true,
			"minLength":"2",
			"maxLength":"20"
		}
	}
}
*/



var fields = {'txtFromName':{'required':true,'actions':{'regexp':'^[A-Za-z\s\-]*$','minLength':'2','maxLength':'24'}},'txtFromEmail':{'required':true,'actions':{'regexp':'^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$','minLength':'2','maxLength':'30'}}}

// setup all form actions in FORM.js
// .click submit - do postback, if in LB.active call LB function



