/**
 * @author patrickc
 */



/** @id FormFlavour */
	function FormFlavour(){
		this.attachEvents		= AttachEvents;
		this.checkElement		= CheckElement;		
		this.checkForm 			= CheckForm;		
		this.createAlert		= CreateAlert;	
		this.init				= Init;
		this.setAlert			= SetAlert;	
		this.reset				= Reset;
		this.toolTip			= ToolTip;
		
		this.isset				= false;
		this.templateName		= 'divFormAlertTemplate';
		this.tempId				= 0;
		
		
		
/**
 * Method, initiates a form
 * @id FormFlavour.Init
 * @alias Init
 * @memberOf FormFlavour
 * @param {String} form, form name/id
 * @param {Object} form
 * @return {Void}
 */		
		/** @id FormFlavour.Init */
		function Init(){
			if (!arguments.length){
				for (name in validation.validation){
					this.attachEvents(name);
					if (window.logger){logger.log('attachingEvents '+ name)}
				}
			} else {
				for (var i=0;i<arguments.length;i++){
					this.attachEvents(arguments[i]);
				}
			}
		}

/**
 * Method, attaches the event handelers to each element that has validation rules
 * @id FormFlavour.AttachEvents
 * @alias AttachEvents
 * @memberOf FormFlavour
 * @param {String} form, form name/id
 * @param {Object} form
 * @return {Void}
 */		
		/** @id FormFlavour.AttachEvents */
		function AttachEvents(form){
			form = validation.formValidation.get(form);
			if (!form){
				if (window.logger){logger.log('AttachEvents: form not found');}
				return;
			}
			if (form.flavourIsset){return;}
			if (!form.validationArray){
				var v = validation.formValidation.checkForm(form); // attach rules
			}
			form.flavourIsset = true;
			form.onreset = function(){validation.flavour.reset(form.name)};
			if (window.logger){logger.log('rules attached, form.isValid : '+ v);}
			if (form.validationArray){
				for (name in form.validationArray){
					if (document.getElementById(name)){
						el = document.getElementById(name);
						el.checkme = el.onblur = validation.flavour.checkElement;
						if (el.type=='button'||el.type=='submit'){
							el.onblur = function (){this.reset()};
						}else if (el.type.match('select')){
							el.onchange = el.checkme;
						}else if (el.type=='text'){
							//el.onkeyup = el.checkme;
						}
						// el.onfocus = validation.flavour.setFocus; 
					}
				}			
			}
		}

/**
 * Method, sets the alert style, visability and value
 * @id FormFlavour.SetAlert
 * @alias SetAlert
 * @memberOf FormFlavour
 * @param {String} el id
 * @param {Object} el
 * @return {Void}
 */		
		/** @id FormFlavour.SetAlert */
		function SetAlert(el){
			el = validation.formValidation.get(el);
			
		}

/**
 * Method, creates an alert object from an HTML template. 
 * This is likely to change a lot per flavour
 * @id FormFlavour.CreateAlert
 * @alias CreateAlert
 * @memberOf FormFlavour
 * @param {String} el id
 * @param {Object} el
 * @return {Void}
 */		
		/** @id FormFlavour.CreateAlert */
		function CreateAlert(el){
			el = validation.formValidation.get(el);
			el.alert = document.getElementById(this.templateName).cloneNode(true);
			el.alert.id = 'formFlavourId'+(++this.tempId);
			el.relativeParent = GetRelativeParent(el);
			el.relativeParent.appendChild(el.alert);


			el.alert.update = function(cn,el,show){
				if (show){
					this.getElementsByTagName('SPAN')[0].className 				= cn;
					this.getElementsByTagName('SPAN')[0].firstChild.nodeValue 	= el.message +' ';
				}
				this.setVisibility(el,show);
			}
			
			el.alert.setPosition = function(el){
				var offsetX = -4;
				
				this.style.visibility="hidden";
				this.style.display="block";
				this.style.left = ( GetOffsetX(el) ) + offsetX + 'px';
				this.style.top = ( GetOffsetY(el) + ( (el.offsetHeight - this.offsetHeight ) /2 ) )+'px';
				this.style.visibility="visible";
				this.style.display="none";
								
				function GetOffsetX(el){
					var node = el;
					var i = 0;
					while(node!=el.relativeParent){
						i+= node.offsetLeft;
						node=node.offsetParent;
					} 
					i+= el.offsetWidth;
					return i;
				}
				function GetOffsetY(el){
					var node = el;
					var i = 0;
					while(node!=el.relativeParent){
						i+= node.offsetTop;
						node=node.offsetParent;
					} 
					return i;
				}
			}
			
			el.alert.setVisibility = function(el,show){
				if (show){
					if (this.active){return;};
					this.setPosition(el);
					if (window.transition && user.jsSupportLevel>2) {
						if (window.logger){logger.log('transition: found fading in')}
						this.onfinish = null;
						//transition.fade(this,100,30,4,10);
						//this.style.display = 'block';
						//this.style.visibility = 'visible';
						if (!this.shadow){
							$(this).after("<img src='/global/lib/form/simpleinline/i/shadow.png' id='shadow"+this.id+"' style='position:absolute;z-index:1' />");
							this.shadow = document.getElementById('shadow'+this.id);
						}
						this.shadow.style.left = this.style.left;
						this.shadow.style.top = this.style.top;
						$(this).show().hide().fadeIn("slow");
						$(this.shadow).show();
					} else {
						this.style.visibility = 'visible';
					}
					this.active = true;
				} else {
					if (window.transition && this.active && user.jsSupportLevel>2) {
						if (window.logger){logger.log('transition: found fading out')}
						//transition.fade(this,30,100,4,10);
						$(this).fadeOut()
						$(this.shadow).hide();
					} else {
						this.style.visibility = 'hidden';
					}
					this.active = false;
				}
			}
			el.reset = function(){this.alert.setVisibility(this,false);}

			function GetRelativeParent(el){
				while(el){
					if (IsRelative(el)){
						return el;
					}
					el = el.offsetParent;
				}
				return document.getElementsByTagName('BODY')[0];
				
				function IsRelative(el){
					var position = '';
					if(el.currentStyle){
					    position = el.currentStyle['position'];
					} else if (document.defaultView.getComputedStyle){
					    position = document.defaultView.getComputedStyle(el,'')['position'];
					} else {return false;}
					if (position.toLowerCase()=='relative'){
						return true;
					} else {
						return false;
					}
				}
			}
		}

/**
 * Method, checkes an individual element, and sets its alert 
 * @id FormFlavour.CheckElement
 * @alias CheckElement
 * @memberOf FormFlavour
 * @return {Void}
 */		
		/** @id FormFlavour.CheckElement */
		function CheckElement(){
			var ok = true;
			if (!this.alert){validation.flavour.createAlert(this);}
			if (validation.formValidation.checkElement(this)){
				this.alert.setVisibility(this,false);
			} else {
				this.alert.update('error',this,true);
				ok = false;
			} 
			return ok;
		}

/**
 * Method, alerts helper text 
 * @id FormFlavour.ToolTip
 * @alias ToolTip
 * @memberOf FormFlavour
 * @return {Void}
 */		
		/** @id FormFlavour.ToolTip */
		function ToolTip(){
			if (!this.alert){validation.flavour.createAlert(this);}
			this.message = 'This is a reqired field';
			this.alert.update('help',this,true);
		}
/**
 * Method, reset the form alerts
 * @id FormFlavour.Reset
 * @alias Reset
 * @memberOf FormFlavour
 * @param {String} form, form name/id
 * @param {Object} form
 * @return {Boolean}
 */		
		/** @id FormFlavour.Reset */
		function Reset(form){
			form = validation.formValidation.get(form);
			if (form.validationArray){
				for (name in form.validationArray){
					if (document.getElementById(name) && document.getElementById(name).reset){
						document.getElementById(name).reset();
					}
				}			
			}			
		}

/**
 * Method, checkes entire form in one go
 * @id FormFlavour.CheckForm
 * @alias CheckForm
 * @memberOf FormFlavour
 * @param {String} form, form name/id
 * @param {Object} form
 * @return {Boolean}
 */		
		/** @id FormFlavour.CheckForm */
		function CheckForm(form){
			form = validation.formValidation.get(form);
			if (!form){
				if (window.logger){logger.log('CheckForm: no such form using document.forms[0]')}
				if (document.forms[0]){form = document.forms[0]}
			} else {
				if (window.logger){logger.log('CheckForm: form exists')}
			}
			form.isValid 	= true;
			form.focusEl 	= null;
			var isValid 	= form.isValid;
			var el			= null;
			if (!form.validationArray && validation.validation[form.name]){
				form.validationArray = validation.validation[form.name];
				if (window.logger){logger.log('CheckForm: ['+ form.name +']');}
			} else {
				if (window.logger && !form.validationArray){logger.log('CheckForm: no validation array ['+ form.name +']');}
			}			
			for (name in form.validationArray){
				if (document.getElementById(name)){
					el = document.getElementById(name);
					isValid = el.checkme();
					if (!isValid && form.isValid){
						form.isValid = isValid
						form.focusEl = el;
					}
				}
			}
			return form.isValid;
		} 
		
		
	}



	if (!window.validation){
		validation = new Object;
	}	
	
	validation.flavour 	= new FormFlavour;
	validation.flavour.linkOnError = function(){
		window.location = "#linkContent";
	}
	validation.checkForm 		= function(form){
		if (window.bCancel && bCancel == true){return true;}
		if (!validation.flavour.checkForm(form)){
			return false;
		} else {
			return true;
		}
	}; 	
	if (window.$){
		if (user.jsSupportLevel>1){
		if (user.jsSupportLevel > 2){window.transition = true;}
		$(document).ready(function(){
			if ($("div.form_contact").length>0){
				$("div.form_contact").eq(0).css({'position':'relative'})
			} else {
				$("#divPageContent").css({'position':'relative'})
			}
			validation.flavour.cleanForms();
		});
		}
	} 
	
	validation.flavour.cleanForms = function(){
		var forms = document.getElementsByTagName('form');
		for (var i=0;i<forms.length;i++){
			clean(forms[i])
			if (window.logger){logger.log('CleanForm: ['+ forms[i].name +']');}
		}
		window.WebForm_OnSubmit = function(){return true;}
		window.WebForm_FireDefaultButton = function(){return true;}
		window.WebForm_DoPostBackWithOptions = function(){return true}
		validation.flavour.init();
		
		function clean(el){
			clean(el);
			var els = document.getElementsByTagName('input');
			for (var i=0;i<els.length;i++){
				clean(els[i])
			}
			els = document.getElementsByTagName('select');
			for (i=0;i<els.length;i++){
				clean(els[i])
			}
			els = document.getElementsByTagName('textarea');
			for (i=0;i<els.length;i++){
				clean(els[i])
			}
			function clean(el){
				el.onsubmit = null;
				el.onkeypress = null;
				el.onchange = null;
			}
		}
	}
	
	
