
/*
addEvent function from http://www.quirksmode.org/blog/archives/2005/10/_and_the_winner_1.html
*/
function addEvent( obj, type, fn )
{
	if (obj.addEventListener)
		obj.addEventListener( type, fn, false );
	else if (obj.attachEvent)
	{
		obj["e"+type+fn] = fn;
		obj[type+fn] = function() { obj["e"+type+fn]( window.event ); }
		obj.attachEvent( "on"+type, obj[type+fn] );
	}
}

/*
createElement function found at http://simon.incutio.com/archive/2003/06/15/javascriptWithXML
*/
function createElement(element) {
	if (typeof document.createElementNS != 'undefined') {
		return document.createElementNS('http://www.w3.org/1999/xhtml', element);
	}
	if (typeof document.createElement != 'undefined') {
		return document.createElement(element);
	}
	return false;
}

function insertTop(obj) {
	// Create the two div elements needed for the top of the box
	d=createElement("div");
	d.className="bt"; // The outer div needs a class name
    d2=createElement("div");
    d.appendChild(d2);
	obj.insertBefore(d,obj.firstChild);
}

function insertBottom(obj) {
	// Create the two div elements needed for the bottom of the box
	d=createElement("div");
	d.className="bb"; // The outer div needs a class name
    d2=createElement("div");
    d.appendChild(d2);
	obj.appendChild(d);
}

function initCB()
{
	// Find all div elements
	var divs = document.getElementsByTagName('div');
	var cbDivs = [];
	for (var i = 0; i < divs.length; i++) {
	// Find all div elements with cbb in their class attribute while allowing for multiple class names
		if (/\bcbb\b/.test(divs[i].className))
			cbDivs[cbDivs.length] = divs[i];
	}
	// Loop through the found div elements
	var thediv, outer, i1, i2;
	for (var i = 0; i < cbDivs.length; i++) {
	// Save the original outer div for later
		thediv = cbDivs[i];
	// 	Create a new div, give it the original div's class attribute, and replace 'cbb' with 'cb'
		outer = createElement('div');
		outer.className = thediv.className;
		outer.className = thediv.className.replace('cbb', 'cb');
	// Change the original div's class name and replace it with the new div
		thediv.className = 'i3';
		thediv.parentNode.replaceChild(outer, thediv);
	// Create two new div elements and insert them into the outermost div
		i1 = createElement('div');
		i1.className = 'i1';
		outer.appendChild(i1);
		i2 = createElement('div');
		i2.className = 'i2';
		i1.appendChild(i2);
	// Insert the original div
		i2.appendChild(thediv);
	// Insert the top and bottom divs
		insertTop(outer);
		insertBottom(outer);
	}
}

startList = function() {
	if (document.all&&document.getElementById) {
		navRoot = document.getElementById("nav");
		for (i=0; i<navRoot.childNodes.length; i++) {
			node = navRoot.childNodes[i];
			if (node.nodeName=="LI") {
				node.onmouseover=function() {
					this.className+=" over";
				}
				node.onmouseout=function() {
					this.className=this.className.replace(" over", "");
				}
			}
		}
	}
}

addEvent(window, 'load', startList);


if(document.getElementById && document.createTextNode)
{
	addEvent(window, 'load', initCB);
}


function populateMap(divMap, addressMap, commentMap)
{
	var map = null
	var geocoder = null
	
	// divMap - id of div to populate with google map
	// addressMap - address to center on, more detail the better, min 1st line & post code
	// commentMap - string to place in marker on map, HTML accepted
	
	if (GBrowserIsCompatible())
	{
		var map = new GMap2(document.getElementById(divMap));
		
		map.setUIToDefault();;
		geocoder = new GClientGeocoder();
		
		if(geocoder) {
			geocoder.getLatLng(
				addressMap,
				function(point) {
					if(!point) {
						// next block executes if the address cannot be found
						var divMapsHTML = null
						divMapsHTML = document.getElementById(divMap).innerHTML;
						document.getElementById(divMap).innerHTML = divMapsHTML + "<div class='mapErrorText'>Error locating address. Please contact directly for map.</div>";
						window.focus();
					} else {
						// address found - add point to map
						map.setCenter(point, 13);
						var marker = new GMarker(point);
						map.addOverlay(marker);
						//marker.openInfoWindowHtml(commentMap,{maxWidth:150});
					
						window.focus();
					}
				}
			);
		}
	}
}


/*
	Form Validation v2
*/

var passwordCompliance = false;
var ieDOM = false, nsDOM = false;
var stdDOM = document.getElementById; 

function initMethod() {
	//Determine the browser support for the DOM
	if( !stdDOM ) {
		ieDOM = document.all;
		
		if( !ieDOM ) {
			nsDOM = ((navigator.appName.indexOf('Netscape') != -1) && (parseInt(navigator.appVersion) ==4));
		}
	}

	passwordChanged();
}

function getObject(objectId) {
	if (stdDOM) return document.getElementById(objectId);
	if (ieDOM) return document.all[objectId];
	if (nsDOM) return document.layers[objectId];
}

function getObjectStyle(objectId) {
	if (nsDOM) return getObject(objectId);

	var obj = getObject(objectId);
	return obj.style;
}


/*
	Functions for validating certain requirements
*/

function isEmail(sValidate, sField) {
	// Validates a string as an email address
	var pattern=/^([a-zA-Z0-9_.-])+@([a-zA-Z0-9_.-])+\.([a-zA-Z])+([a-zA-Z])+/;
	if (pattern.test(sValidate)) {
		return 'valid';
	} else {
		return ' must be an e-mail address\n';
	}	
}

function isIdenticalTo(sValidate, sField) {
	// Check a field is identical to another based on the provided field name
	alert(sField);
	if (getObject(sField).value == getObject(sField+'2').value) {
		return 'valid';
	} else {
		return ' must be matching\n';
	}
	
}

function isNum(sValidate, sField) {
	// Check the input is a number	
	if (isNaN(sValidate)) {
		return ' is not a number\n';
	} else {
		return 'valid';
	}
}

function isPasswordStrength(sValidate, sField) {
	// Check a passwords strength	
	if(passwordCompliance == false) {
		return ' is not strong enough\n';
	} else {
		return 'valid';
	}
}

/*
	End specific validation requirement functions
*/

function validateForm(oForm) {
	var sReturn = '';
	
	sValidationString = oForm.elements['validation'].value

	// live coding
	bConfirm = true;
	if (bConfirm) {
		//loop through all form fields
		sFieldName = '';
		sReturn = '';
		iTotal = 0;
		bTest = false;
			
		for (var i=0;i < oForm.length;i++) {
			//check if field is require for validation
			
			sFieldName = oForm.elements[i].name
			sFieldTitle = oForm.elements[i].title
			sFieldValue = oForm.elements[i].value
			if (sFieldTitle == '') {
				sFieldTitle = sFieldName
			}	
			bTest = false;
			
			var fieldChecked = false;
			
			if (sValidationString.indexOf(sFieldName + '[isEmail]') >= 1 && sFieldName != '') {
				fieldChecked = true;
				if (sFieldValue == '') {
					sReturn += '- ' + sFieldTitle + ' is required\n';
					oForm.elements[i].style.backgroundColor = '#FFCCCC';
				} else if (sFieldValue.indexOf('@') <= 0) {
					sReturn += '- ' + sFieldTitle + ' must be an e-mail address\n';
					oForm.elements[i].style.backgroundColor = '#FFCCCC';
				} else {
					oForm.elements[i].style.backgroundColor = '';
				}
			} 
			
			if (sValidationString.indexOf(sFieldName + '[isNum]') >= 1 && sFieldName != '') {
				fieldChecked = true;
				if (sFieldValue == '') {
					sReturn += '- ' + sFieldTitle + ' is required\n';
					oForm.elements[i].style.backgroundColor = '#FFCCCC';
				} else if (isNaN(sFieldValue)) {
					sReturn += '- ' + sFieldTitle + ' is not a number\n';
					oForm.elements[i].style.backgroundColor = '#FFCCCC';
				} else {
					oForm.elements[i].style.backgroundColor = '';
				}
			}
			
			if (sValidationString.indexOf(sFieldName + '[isWholeNum]') >= 1 && sFieldName != '') {
				fieldChecked = true;
				if (sFieldValue == '') {
					sReturn += '- ' + sFieldTitle + ' is required\n';
					oForm.elements[i].style.backgroundColor = '#FFCCCC';
				} else if (isNaN(sFieldValue)) {
					sReturn += '- ' + sFieldTitle + ' is not a number\n';
					oForm.elements[i].style.backgroundColor = '#FFCCCC';
				} else if (sFieldValue.indexOf('.') > -1) {
					sReturn += '- ' + sFieldTitle + ' must be a whole number\n';
					oForm.elements[i].style.backgroundColor = '#FFCCCC';
				} else if (sFieldValue < 0) {
					sReturn += '- ' + sFieldTitle + ' must be a positive whole number.\n';
					oForm.elements[i].style.backgroundColor = '#FFCCCC';
				} else {
					oForm.elements[i].style.backgroundColor = '';
				}
			}
			
			if (sValidationString.indexOf(sFieldName + '[isIdenticalTo]') >= 1 && sFieldName != '') {
				fieldChecked = true;
				if (sFieldValue == '') {
					sReturn += '- ' + sFieldTitle + ' is required\n';
					oForm.elements[i].style.backgroundColor = '#FFCCCC';
					
				} else if (sFieldValue != oForm.elements[sFieldName+'2'].value) { 
					sReturn += '- ' + sFieldTitle + 's do not match\n';
					oForm.elements[i].style.backgroundColor = '#FFCCCC';
				} else {
					oForm.elements[i].style.backgroundColor = '';
					
				}
			}
			
			if (sValidationString.indexOf(sFieldName + '[isNotZero]') >= 1 && sFieldName != '') {
				fieldChecked = true;
				if (sFieldValue == '') {
					sReturn += '- ' + sFieldTitle + ' is required\n';
					oForm.elements[i].style.backgroundColor = '#FFCCCC';
				} else if (sFieldValue == 0) {
					sReturn += '- ' + sFieldTitle + ' must be selected\n';
					oForm.elements[i].style.backgroundColor = '#FFCCCC';
				} else {
					oForm.elements[i].style.backgroundColor = '';
				}
			}
			
			if (sValidationString.indexOf(sFieldName + '[isPasswordStrength]') >= 1 && sFieldName != '') {
				fieldChecked = true;
				if(passwordCompliance == false) {
					sReturn += '- Your password is not strong enough\n';
					oForm.elements[i].style.backgroundColor = '#FFCCCC';
				} else {
					oForm.elements[i].style.backgroundColor = '';	
				}
			}
			
			if (sValidationString.indexOf(sFieldName + '[isSelected]') >= 1 && sFieldName != '') {
				fieldChecked = true;
				//loop through entire form again to find checked radio buttons
				for (var iSub=0;iSub < oForm.length;iSub++) {				
					if (oForm.elements[iSub].name == sFieldName && oForm.elements[iSub].checked) {
						//if field is checked then set bol
						bTest = true
					}
				}
				//output message
				if (bTest && sFieldName != sPreviousFieldName) {
					oForm.elements[i].style.backgroundColor = '';
				} else if (!bTest && sFieldName != sPreviousFieldName) {
					sReturn += '- ' + sFieldTitle + ' is required\n';					
					oForm.elements[i].style.backgroundColor = '#FFCCCC';
				} else if (!bTest) {
					// colour all same names check boxes
					oForm.elements[i].style.backgroundColor = '#FFCCCC';
				} else {
					oForm.elements[i].style.backgroundColor = '';
				}		
	//ajax call for captcha			
				
			}
			
			if (sValidationString.indexOf(sFieldName + '[isCaptcha]') >= 1 && sFieldName != '') {
				fieldChecked = true;
				
				
				if (sFieldValue == '') {
					sReturn += '- ' + sFieldTitle + ' is required\n';
					oForm.elements[i].style.backgroundColor = '#FFCCCC';
				} else {
					// check if the captcha entered matches the one stored server side
					var xmlHttp;
					try {
						// Firefox, Opera 8.0+, Safari
						xmlHttp=new XMLHttpRequest();
					}
					catch (e) {
						// Internet Explorer
						try {
							xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
						}
					  	catch (e) {
							try {
								xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
							}
							catch (e) {
						  		sReturn += '- Your browser does not support AJAX, you should update to a newer, more secure browser\n'
							}
						}
					}
						
					
					
					var url = 'checkcaptcha.asp';
					url = url + '?q=' + sFieldValue;
					url = url + '&rnd=' + Math.random();
				  	xmlHttp.open("GET",url,false);
				  	xmlHttp.send(null);

					if (xmlHttp.responseText == "correct") {
						oForm.elements[i].style.backgroundColor = '';
	
							} else if (xmlHttp.responseText == 'wrong') {
								sReturn += '- ' + sFieldTitle + ' is incorrect\n';
								oForm.elements[i].style.backgroundColor = '#FFCCCC';
							} else {
								sReturn += '- ' + sFieldTitle + ' could not be verified at this time\n';	
								oForm.elements[i].style.backgroundColor = '#FFCCCC';
							}	
						}
				
			}
			
			if (sValidationString.indexOf(sFieldName) >= 1 && sFieldName != '' && fieldChecked == false) {
				if (sFieldValue == '') {
					sReturn += '- ' + sFieldTitle + ' is required\n';
					oForm.elements[i].style.backgroundColor = '#FFCCCC';
				} else {
					oForm.elements[i].style.backgroundColor = '';
				}
			} else {
				oForm.elements[i].style.backgroundColor = '';
			}		
			
			sPreviousFieldName = sFieldName
		}
		
		if (sReturn) {
			alert('Please fill out all the following required fields\nbefore submitting this form.\n' + sReturn);
			return(false)
		} else {
			return(true);
		}
	} else {
			return(false)
	}	
		//
}


function showDefault(objectId) {
	showCell(objectId, "#E2E2E2", "#E2E2E2");
}

function showCell(objectId, foreColor, backColor) {
	getObjectStyle(objectId).color = foreColor;
	getObjectStyle(objectId).backgroundColor = backColor;
}

function showWeak() {
	showCell("pwWeak", "Black", "#FF6666");

	showDefault("pwMedium");
	showDefault("pwStrong");
}

function showMedium() {
	showCell("pwWeak", "#FFCC66", "#FFCC66");
	showCell("pwMedium", "Black", "#FFCC66");
	
	showDefault("pwStrong");
}

function showStrong() {
	showCell("pwWeak", "#80FF80", "#80FF80");
	showCell("pwMedium", "#80FF80", "#80FF80");
	showCell("pwStrong", "Black", "#80FF80");
}

function showUndetermined() {
	showDefault("pwWeak");
	showDefault("pwMedium");
	showDefault("pwStrong");
}


function passwordChanged() {
	var strongRegex = new RegExp("^(?=.{8,})(?=.*[A-Z])(?=.*[a-z])(?=.*[0-9]).*$", "g");
	var mediumRegex = new RegExp("^(?=.{7,})(((?=.*[A-Z])(?=.*[a-z]))|((?=.*[A-Z])(?=.*[0-9]))|((?=.*[a-z])(?=.*[0-9]))).*$", "g");
	var enoughRegex = new RegExp("(?=.{1,}).*", "g");

	
	var pwd = getObject("txtPassword").value;

	if( false == enoughRegex.test(pwd) ) {
		showUndetermined();
		passwordCompliance = false;
	} else if( strongRegex.test(pwd) ) {
		showStrong();
		passwordCompliance = true;
	} else if( mediumRegex.test( pwd ) ) {
		showMedium();
		passwordCompliance = true;
	} else {
		showWeak();
		passwordCompliance = false;
	}
}


jQuery(document).ready(function() {
			
	// Even up the height of the 3 columns on the homepage
	//jQuery(".matchcol").equalHeights(100,300);
	
	jQuery(".videopop").colorbox({iframe:true, innerWidth:503, innerHeight:428});
	
	
	// Auto-clears and sets default value of search box if left blank
	jQuery(".searchinput").focus(function () {
		jQuery(this).val("");
	}).blur(function() {
		if (jQuery(this).val() == "") {
			jQuery(this).val(jQuery(this)[0].defaultValue);
		}
	});
		
});
