/*
 * Accent Validation Routine
 * 
 * Calls Mootools (more) Form.Validator with fancy bubble pointers
 */
function accentValidation(form,CSSstyle){
	if(!CSSstyle){
		var CSSstyle = false;
	}else{
		var CSSstyle = true;
	}
		
	
	var formToCheck = $(form);
	// builds a validation bubble to contain validation messages
	var buildBubble = function(field) {
		// If bubble already exists for this field, just return it
		if ($('validation-bubblewrapper-'+field.id)) return $('validation-bubblewrapper-'+field.id);
		// the wrapper to contain bubble
		var bubbleWrapper = new Element('div', {'class':'validation-bubblewrapper', 'id':'validation-bubblewrapper-'+field.id });
		// build the boxes that make warning look nice
		var WooBoxHolderB = new Element('table', { html: '', 'class': 'ErrorBoxHolderSergeiB', 'cellpadding': '0', 'cellspacing': '0' });
		// Add the table to the container
		WooBoxHolderB.inject(bubbleWrapper);
		var tbl = WooBoxHolderB;
		// Add sections of bubble to the table, work backwards as tbl.insertRow adds to top of table							
		var WoooBoxHolderBThirdRow = $(tbl.insertRow(WooBoxHolderB)).adopt(
			new Element('td', {	html: '', 'height':'4px', 'class': '' }),
			new Element('td', { html: '', 'class': 'ErrorBoxBottomLeftSergeiB'	}),
			new Element('td', { html: '', 'class': 'fill' }),
			new Element('td', { html: '', 'class': 'ErrorBoxBottomRightSergeiB' })
		);
		var WoooBoxHolderBSecondRow = $(tbl.insertRow(WooBoxHolderB)).adopt(
			new Element('td', { html: '',  'class': 'ErrorBoxPointerSergeiB' }),
			new Element('td', { html: '','class': 'fill'	}),
			new Element('td', { html: '', 'class': 'ErrorBoxMiddleSergeiB fill' }),
			new Element('td', { html: '', 'class': 'fill'	})
		);	
		var WoooBoxHolderBFirstRow = $(tbl.insertRow(WooBoxHolderB)).adopt(
			new Element('td', {	html: '', 'width':'10px' }),
			new Element('td', { html: '', 'width': '4px','height':'4px', 'class': 'ErrorBoxTopLeftSergeiB' }),
			new Element('td', {	html: '', 'class': 'fill' }),
			new Element('td', { html: '', 'class': 'ErrorBoxTopRightSergeiB' })
		);
		// Put bubble in the right place
		var widthOfElement = field.getStyle('width').toInt() + 2;
		var heightOfElement = field.getStyle('height').toInt() + 2;
		var qwing = field.getPosition();
		var XOfField = qwing.x;
		var YOfField = qwing.y-8;
		
		
		// Add it after the input it's for
		// if there's a datepicker button after, pop it after that
		bubbleWrapper.inject((field.getNext() && field.getNext().hasClass('date-picker-control')) ? field.getNext() : field,'after');
		
		if(CSSstyle){
			bubbleWrapper.setStyles({
				'display' : 'block',
				'position': 'absolute'
			});
			
			var possy = bubbleWrapper.position({
				relativeTo: field,
				position: 'upperRight',
				returnPos: 'true'
			});
			
			possy.top = possy.top.toInt() - 12;
			
			bubbleWrapper.setStyles({
				'top' : possy.top +'px',
				'left': possy.left +'px'
			});

				
			/*	
			bubbleWrapper.setStyles({
					'display' : 'block',
					'position': 'relative',
					'top' : -heightOfElement + 'px',
					'left': widthOfElement + 'px'
			});*/
			
		}else{
			
			bubbleWrapper.setStyles({
				'display' : 'block',
				'position': 'absolute',
				'top' : YOfField+'px',
				'left': XOfField+widthOfElement + 'px'
			});
		}
		
		return bubbleWrapper;
	}
	var bubbleAdd = function(bubble, adviceElement) {
		adviceElement = $(adviceElement);
		var container = bubble.getElement('td.ErrorBoxMiddleSergeiB');
		container.adopt(adviceElement);
	}
	// Removes the bubble from this field (generally because all validation has passed)
	var popBubble = function(field) {
		if ($('validation-bubblewrapper-' + field.id)) {
			$('validation-bubblewrapper-' + field.id).destroy();
			return true;
		}
		return false;
	}
	var bubbleRefresh = function(field) {
		// if theres no errors left inside the bubble, remove it
		if ($('validation-bubblewrapper-'+field.id) && $$('#validation-bubblewrapper-'+field.id+' .validation-advice').length == 0) {
			// destroy the empty bubble
			popBubble(field);
		}
	}
	// Bubble Wrap - Wraps the validation advice messages in neat little bubbles
	var bubbleWrap = function(adviceElement, field) {
		// grabe the advice element, but remove it from the dom
		adviceElement = $(adviceElement).dispose();
		field = $(field);
		// Put error message in the bubble
		bubbleAdd(buildBubble(field), adviceElement);
	}
	var myFormValidator = new FormValidator.Inline(formToCheck, {
		dateInFormatMDY: "DD/MM/YYYY",
		dateSuchAs: "31/02/2009",
		errorPrefix: "",	
		onFormValidate: function(ok){ // the ok is passed in as boolean
			if (!ok) {

			} else {
				$(formToCheck).getElements('.validation-failed').each(function(el){
					//alert(el.id)
				});
			}
		},
		onElementPass: function(field){
			popBubble(field);
		},
		onElementFail: function(field){
			InputID = field.id;
			$(formToCheck).getElements('.validation-advice').each(function(e){
				AdviceID = e.id;
				if (AdviceID.match(InputID)) {
					// Put the new validation message inside Adam's shiny bubble
					bubbleWrap(e, field);
				}
			});
		},
		scrollToErrorsOnSubmit: false,
		serial: false,
		stopOnFailure: true,
		evaluateFieldsOnBlur: true,
		evaluateFieldsOnChange: true
	});

	return myFormValidator;
}

/**
 * Standard FormValidators
 * - Here are a few generic form validators which are likely to be very commonly used.
 */

FormValidator.add('woo', {
	errorMsg: 'This woo type field is required',
	test: function(element){
		if (element.value.length == 0) return false;
		else return true;
	}
});

FormValidator.add('NameAndSurname', {
	errorMsg: 'You must enter a Name and Surname',
	test: function(element){
		if (! element.value.match( new RegExp(/^[a-z]{1,}(\s[a-z-]{2,})+$/i)) ) return false;
		else return true;
	}
});


FormValidator.add('telephone', {
	errorMsg: 'Please enter a Telephone number containing only digits,"(",")",+',
	test: function(element){
		/* Strip out spaces - just the facts mam */
		element.set('value',element.value.replace(/ /i, ""));
		if (! element.value.match( new RegExp(/^[0-9+()]{6,}/i)) ) return false;
		else return true;
	}
});

FormValidator.add('Message', {
	errorMsg: 'Please enter a Message',
	test: function(element){
		if (element.value == '') return false;
		else return true;
	}
});

FormValidator.add('postcode', {
	errorMsg: 'Please enter a valid postcode',
	test: function(element){
		element.set('value',element.value.toUpperCase());
		if (! element.value.match( new RegExp(/^[A-Z]{1,2}[A-Z0-9]{1,2} ?[0-9][A-Z]{2}$/i)) ) return false;
		else return true;

	}
});

// Validates for a date format dd/mm/yyyy
FormValidator.add('dateDDMMYYYY', {
	errorMsg: 'Please enter date as dd/mm/yyyy',
	test: function(element){
		var datePat = /^(\d{1,2})(\/)(\d{1,2})(\/)(\d{4})$/;
		var matchArray = element.value.match(datePat);
		if (matchArray == null) { 
				return false;
		}else{
		    day = matchArray[1];
			month = matchArray[3];
		   year = matchArray[5];

			if(day.length == 1){
				day = '0'+day;
			}
			if(month.length == 1){
				month = '0'+month;
			}
			element.set('value', day+'/'+month+'/'+year);
			return true;
		}
	}
});
