/**
* Template Ordering JS
*/
var tOrd = {
	
	//Common Document Elements
	orderForm:false,
	fieldsets:false,
	loggedUser:false,

	init : function () {
		tOrd.orderForm = $('orderForm');
		tOrd.fieldsets = tOrd.orderForm.getElementsByTagName('fieldset');
				
		//Capture Screen Info
		$('clientViewport').value = $D.getViewportWidth() + '*' + $D.getViewportHeight();
		$('clientScreen').value = screen.width + '*' + screen.height;
		
		
		var design = $('chooseTemplate');
		var templateCells = design.getElementsByTagName('div'); //All template containing divs
		
		//Activate Chosen Template Cells
		var config = {
			elType : 'div',
			allEls : templateCells
		}
		$E.on(design.getElementsByTagName('input'), 'focus', tOrd.activateElement, config);
		
		//Activate Fieldsets
		config = {
			elType : 'fieldset',
			allEls : tOrd.fieldsets
		}
						
		$E.on(tOrd.orderForm.getElementsByTagName('input'), 'focus', tOrd.activateElement, config);
		$E.on(tOrd.orderForm.getElementsByTagName('select'), 'focus', tOrd.activateElement, config);
		$E.on(tOrd.orderForm.getElementsByTagName('textarea'), 'focus', tOrd.activateElement, config);
		
		//Listen for submission. Basic validation
		$E.on(tOrd.orderForm, 'submit', tOrd.validate);
		$E.on('company', 'blur', tOrd.logUser);
	},
	
	/**
	* Log partial info via Ajax. In case of incompleted orders
	* @param e. Blur event
	* @return void
	*/
	logUser : function(e) {
		if(tOrd.loggedUser) return; //Quit if already done
		
		var name = $('name').value;
		var company = $('company').value;
		if(company == '') return;
		var name = name.concat(' of ').concat(company);
		name = 'data='.concat(encodeURIComponent(name));
		$C.asyncRequest('POST', 'ajax/template-order.php', {
			success:function(o){
				tOrd.loggedUser = true; //Mark as done
			},
			failure:function(o){}
			}, 
			name);
	},
	
	/**
	 * Common func. to visually highlight (CSS active class) for ONE of a SET of like elements
	 * @param (event) ev. The click event
	 * @param (Object) config. config.elType = HTML element type (string) to look for and activate. config.allEls = EL references to ALL els in the group (to be deactivated) 
	 */
	activateElement : function(ev, config) {
				
		//Deactivate all first
		for (var i=0; i<config.allEls.length; i++) {
			$D.removeClass(config.allEls[i], 'active');
		}
		
		//Climb DOM to find parent of appropriate type to activate (max steps)
		var max = 6; //avoid infinite loop
		i = 0;
		var elType = config.elType.toLowerCase();
		var tgt = $E.getTarget(ev);
		while(tgt.tagName.toLowerCase() != elType && i < max) {
			tgt = tgt.parentNode;
			i++;
		}
		$D.addClass(tgt, 'active');
	},
	
	/**
	* Validation functions for each REQUIRED field
	* runs on passed value and returns error message if any
	* @return string
	*/
	validationFuncs : {
		name:function(value) {
			if(value.length < 5 || value.search(' ') == -1) return 'Full name required';
			if(value.length > 25) return 'Your name too long (' + value.length + ' characters; 25 max)';
		},
		company:function(value) {
			if(value.length < 3) return 'Company name invalid (too short)';
			if(value.length > 35) return 'Company name too long (' + value.length + ' characters; 50 max)';
		},
		phone:function(value) {
			value = value.replace(/[^0-9]/, ''); //Remove non-digits
			if(value.search(/[0-9]{8,12}/) == -1) return 'Phone number invalid';
		},
		address:function(value) {
			if(value.length < 10) return 'Postal address missing, or too short';
		},
		postcode:function(value){
			value = value.replace(' ', ''); //remove spaces
			if(value.search(/[0-9]{4,6}/) == -1) return 'Postcode missing or invalid';
		}
	},
	
	
	/**
	 * Check that at LEAST one, of a set of radio or checkboxes is checked
	 * @param {Array} inputSet. Input DOM element references
	 * @return {Bool}
	 */
	oneChecked:function(inputSet) {
		for(i=0; i<inputSet.length; i++) {
			input = inputSet[i];
			if(input.type != 'radio' && input.type != 'checkbox') continue;
			if(input.checked) return true;
		}
		return false;
	},
	
	
	/**
	* Respond to form submission, check required fields
	*/
	validate:function(e) {
		$E.preventDefault(e);
		
		//Spam Question Answered
		var els = $('spamFieldset').getElementsByTagName('input');
		if(!tOrd.oneChecked(els)) {
			alert("The Anti-Spam Question wasn't answered");
			return;
		}
	
		//Design chosen
		els = $('chooseTemplate').getElementsByTagName('input');
		if(!tOrd.oneChecked(els)) {
			alert("No Website Template was chosen");
			return;
		}
		
		//Required Form fields
		
		var errorMsg = '';
		
		for(field in tOrd.validationFuncs) {
			//field is string naming the field. Corresponds to DOM ID and function name
			var fieldEl = $(field);
			if(!fieldEl) continue;
			
			//Append THIS error msg (if any) to full list
			var msg = tOrd.validationFuncs[field](fieldEl.value);
			if(msg) errorMsg = errorMsg.concat(msg + "\n"); 
		}
		if(errorMsg) {
			alert(errorMsg.replace(/\n$/, '')); //Strip trailing new line
			return;
		}
		
		//No Errors
		tOrd.orderForm.submit();
	}
	
}
$E.onDOMReady(tOrd.init);