// Pop up window scans for class="popup" then appends popup function to link.
window.onload = function() {
  if (!document.getElementsByTagName) return false;
  var lnks = document.getElementsByTagName("a");
  for (var i=0; i<lnks.length; i++) {
    if (lnks[i].className == "popup") {
      lnks[i].onclick = function() {
        popUp(this.getAttribute("href"));
        return false;
      }
    }
  }
}

// Popup Window
function popUp(winURL) {
  window.open(winURL,"popup","width=450,height=300,scrollbars,resizable");
}

sfHover = function() {
	var sfEls = document.getElementById("services").getElementsByTagName("LI");
	for (var i=0; i<sfEls.length; i++) {
		sfEls[i].onmouseover=function() {
			this.className+=" over";
		}
		sfEls[i].onmouseout=function() {
			this.className=this.className.replace(new RegExp(" over\\b"), "");
		}
	}
}

// Print Page
function printpage() {
window.print();  
}


// Form Validation
var validationErrorMessage = new Object();
validationErrorMessage['required'] = 'This information is required';
validationErrorMessage['numeric'] = 'This field requires a number';
validationErrorMessage['postcode'] = 'This field must hold a UK postal code';
validationErrorMessage['pattern'] = 'Pattern incorrect';
validationErrorMessage['email'] = 'Incorrect email address';

// CARD VALIDATION
validationErrorMessage['cardtype'] = 'Choose a card type';
validationErrorMessage['cardholdername'] = 'Enter the cardholder name';
validationErrorMessage['cardnumber'] = 'Enter a valid 16 digit card number without spaces or dashes';
validationErrorMessage['expirymonth'] = 'Select the expiry month';
validationErrorMessage['expiryyear'] = 'Select the expiry year';

var validationFunctions = new Object();
validationFunctions["required"] = isRequired;
validationFunctions["pattern"] = isPattern;
validationFunctions["postcode"] = isPostCode;
validationFunctions["numeric"] = isnumeric;
validationFunctions["email"] = isEmail;

function isRequired(formField) {
	switch (formField.type) {
		case 'text':
		case 'textarea':
		case 'select-one':
			if (formField.value)
				return true;
			return false;
		case 'radio':
			var radios = formField.form[formField.name];
			for (var i=0;i<radios.length;i++) {
				if (radios[i].checked) return true;
			}
			return false;
		case 'checkbox':
			return formField.checked;
	}	
}

function isPattern(formField,pattern) {
	var pattern = pattern || formField.getAttribute('pattern');
	var regExp = new RegExp("^"+pattern+"$","");
	var correct = regExp.test(formField.value);
	if (!correct && formField.getAttribute('patternDesc'))
		correct = formField.getAttribute('patternDesc');
	return correct;
}

function isPostCode(formField) {
	return isPattern(formField,"\\d{4}\\s*\\D{2}");
}

function isCardNumber(formField) {
	return isPattern(formField,"\\d{16}");
}

function isnumeric(formField) {
	return isPattern(formField,"\\d+");
}

function isEmail(formField) {
	return isPattern(formField,"\\w(\\.?[\\w-])*@\\w(\\.?[\\w-])*\\.[a-z]{2,6}")
}

function emptyFunction() {
	return true;
}

/*********************************/

var W3CDOM = document.createElement && document.getElementsByTagName;

function validateForms() {
	if (!W3CDOM) return;
	var forms = document.forms;
	for (var i=0;i<forms.length;i++) {
		forms[i].onsubmit = validate;
	}
}



function validate() {
	var els = this.elements;
	var validForm = true;
	var firstError = null;
	for (var i=0;i<els.length;i++) {
		if (els[i].removeError)
			els[i].removeError();
		var req = els[i].getAttribute('rel');
		if (!req) continue;
		var reqs = req.split(' ');
		if (els[i].getAttribute('pattern'))
			reqs[reqs.length] = 'pattern';
		for (var j=0;j<reqs.length;j++) {
			if (!validationFunctions[reqs[j]])
				validationFunctions[reqs[j]] = emptyFunction;
			var OK = validationFunctions[reqs[j]](els[i]);
			if (OK != true) {
				var errorMessage = OK || validationErrorMessage[reqs[j]];
				writeError(els[i],errorMessage)
				validForm = false;
				if (!firstError)
					firstError = els[i];
				break;
			}
		}
	}

	if (!validForm) {
		//alert("Errors have been found");
		location.hash = '#editform';
	}
   return validForm;
   document.getElementById("process").disabled = true;
}

function writeError(obj,message) {
	if(obj.parentNode.className.match('errorMessage') == null){
		obj.parentNode.className += ' errorMessage';
	}
	obj.onchange = removeError;
	if (obj.errorMessage || obj.parentNode.errorMessage) return;
	var errorMessage = document.createElement('span');
	errorMessage.className = 'errorMessage';
	//errorMessage.setAttribute('for',obj.id);
	//errorMessage.setAttribute('htmlFor',obj.id);
	errorMessage.appendChild(document.createTextNode(message));
	obj.parentNode.appendChild(errorMessage);
	obj.errorMessage = errorMessage;
	obj.parentNode.errorMessage = errorMessage;
}

function removeError() {
	//this.className = this.className.replace(/errorMessage/,'');
	this.parentNode.className = this.parentNode.className.replace(/errorMessage/,'');
	if (this.errorMessage) {
		this.parentNode.className = this.parentNode.className.replace(/errorMessage/,'');
		this.parentNode.removeChild(this.errorMessage);
		this.errorMessage = null;
		this.parentNode.errorMessage = null;
	}
	this.onchange = null;
}

// Form Validation ENDS

/*
cbb function by Roger Johansson, http://www.456bereastreet.com/
*/
var cbb = {
	init : function() {
	// Check that the browser supports the DOM methods used
		if (!document.getElementById || !document.createElement || !document.appendChild) return false;
		var oElement, oOuter, oI1, oI2, tempId;
	// Find all elements with a class name of cbb
		var arrElements = document.getElementsByTagName('*');
		var oRegExp = new RegExp("(^|\\s)cbb(\\s|$)");
		for (var i=0; i<arrElements.length; i++) {
	// Save the original outer element for later
			oElement = arrElements[i];
			if (oRegExp.test(oElement.className)) {
	// 	Create a new element and give it the original element's class name(s) while replacing 'cbb' with 'cb'
				oOuter = document.createElement('div');
				oOuter.className = oElement.className.replace(oRegExp, '$1cb$2');
	// Give the new div the original element's id if it has one
				if (oElement.getAttribute("id")) {
					tempId = oElement.id;
					oElement.removeAttribute('id');
					oOuter.setAttribute('id', '');
					oOuter.id = tempId;
				}
	// Change the original element's class name and replace it with the new div
				oElement.className = 'i3';
				oElement.parentNode.replaceChild(oOuter, oElement);
	// Create two new div elements and insert them into the outermost div
				oI1 = document.createElement('div');
				oI1.className = 'i1';
				oOuter.appendChild(oI1);
				oI2 = document.createElement('div');
				oI2.className = 'i2';
				oI1.appendChild(oI2);
	// Insert the original element
				oI2.appendChild(oElement);
	// Insert the top and bottom divs
				cbb.insertTop(oOuter);
				cbb.insertBottom(oOuter);
			}
		}
	},
	insertTop : function(obj) {
		var oOuter, oInner;
	// Create the two div elements needed for the top of the box
		oOuter=document.createElement("div");
		oOuter.className="bt"; // The outer div needs a class name
	    oInner=document.createElement("div");
	    oOuter.appendChild(oInner);
		obj.insertBefore(oOuter,obj.firstChild);
	},
	insertBottom : function(obj) {
		var oOuter, oInner;
	// Create the two div elements needed for the bottom of the box
		oOuter=document.createElement("div");
		oOuter.className="bb"; // The outer div needs a class name
	    oInner=document.createElement("div");
	    oOuter.appendChild(oInner);
		obj.appendChild(oOuter);
	},
	// addEvent function from http://www.quirksmode.org/blog/archives/2005/10/_and_the_winner_1.html
	addEvent : function(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]);
		}
	}
};

function sendtofriend(sPicURL) {
    window.open(sPicURL, "",
    "resizable=1,scrollbars=1,height=500,width=400");
	}


/** ULTRA-SIMPLE EVENT ADDING **/
function addEventSimple(obj,evt,fn) {
 if (obj.addEventListener)
 obj.addEventListener(evt,fn,false);
 else if (obj.attachEvent)
 obj.attachEvent('on'+evt,fn);
}

function removeEventSimple(obj,evt,fn) {
 if (obj.removeEventListener)
 obj.removeEventListener(evt,fn,false);
 else if (obj.detachEvent)
 obj.detachEvent('on'+evt,fn);
}

cbb.addEvent(window, 'load', cbb.init);
//addEventSimple(window,'load',validateForms);
//addEventSimple(window,'load',so_init);
//addEventSimple(window,'load',sfHover);

