function get_trade_notice() {
	if (document.getElementById('trade_notice')) {
		if (!get_cookie('hide_ob_trade_notice')) {
			document.getElementById('trade_notice').style.display = '';
		}
	}
}

function hide_trade_notice() {

	if (document.getElementById('trade_notice')) {
	
		set_cookie('hide_ob_trade_notice', '1', 1, '/', '', '');
		document.getElementById('trade_notice').style.display = 'none';
	}
	
}

function hide(element) {
	if (document.getElementById(element)) {
		//set_cookie('hide_ob_trade_notice', '1', 1, '/', '', '');
		document.getElementById(element).style.display = 'none';
	}
}

function get_cookie(check_name) {
	// first we'll split this cookie up into name/value pairs
	// note: document.cookie only returns name=value, not the other components
	var a_all_cookies = document.cookie.split( ';' );
	var a_temp_cookie = '';
	var cookie_name = '';
	var cookie_value = '';
	var b_cookie_found = false; // set boolean t/f default f
	
	for ( i = 0; i < a_all_cookies.length; i++ )
	{
		// now we'll split apart each name=value pair
		a_temp_cookie = a_all_cookies[i].split( '=' );
		
		
		// and trim left/right whitespace while we're at it
		cookie_name = a_temp_cookie[0].replace(/^\s+|\s+$/g, '');
	
		// if the extracted name matches passed check_name
		if ( cookie_name == check_name )
		{
			b_cookie_found = true;
			// we need to handle case where cookie has no value but exists (no = sign, that is):
			if ( a_temp_cookie.length > 1 )
			{
				cookie_value = unescape( a_temp_cookie[1].replace(/^\s+|\s+$/g, '') );
			}
			// note that in cases where cookie is initialized but no value, null is returned
			return cookie_value;
			break;
		}
		a_temp_cookie = null;
		cookie_name = '';
	}
	if ( !b_cookie_found ) 
	{
		return null;
	}
}



function set_cookie( name, value, expires, path, domain, secure ) {
	// set time, it's in milliseconds
	var today = new Date();
	today.setTime( today.getTime() );
	
	/*
	if the expires variable is set, make the correct
	expires time, the current script below will set
	it for x number of days, to make it for hours,
	delete * 24, for minutes, delete * 60 * 24
	*/
	if ( expires )
	{
	expires = expires * 1000 * 60 * 60;
	}
	var expires_date = new Date( today.getTime() + (expires) );

	document.cookie = name + "=" +escape( value ) +
	( ( expires ) ? ";expires=" + expires_date.toGMTString() : "" ) +
	( ( path ) ? ";path=" + path : "" ) +
	( ( domain ) ? ";domain=" + domain : "" ) +
	( ( secure ) ? ";secure" : "" );
}


function getBaseURL() {
	if (location.host == 'dev.presencemultimedia.co.uk') {
		return '/onebutton/';
	}
	return '/';
}

function getElementsByClass(searchClass,node,tag) {
	var classElements = new Array();
	if ( node == null )
		node = document;
	if ( tag == null )
		tag = '*';
	var els = node.getElementsByTagName(tag);
	var elsLen = els.length;
	var pattern = new RegExp("(^|\\s)"+searchClass+"(\\s|$)");
	for (i = 0, j = 0; i < elsLen; i++) {
		if ( pattern.test(els[i].className) ) {
			classElements[j] = els[i];
			j++;
		}
	}
	return classElements;
}

function setUpTradeApplicationFormToggleFields() {	
	toggleFields('status_radios');
	toggleFields('new_customer_radios');
}

function toggleFields(parentID) {

	// reads checked status of radios/checkboxes in parentID
	// if checked, shows the elements with class 'fields_<elementID>'
	// hides all others with matching class names
	
	if (document.getElementById(parentID)) {
		// get all inputs in parent
		var parent = document.getElementById(parentID);
		var inputs = parent.getElementsByTagName('INPUT');
		// loop through
		for (var i = 0; i < inputs.length; i++) {
			var input = inputs[i];
			// check it is a radio or checkbox
			var inputType = input.getAttribute('type');
			if (inputType == 'checkbox' || inputType == 'radio') {
				// class to match
				var className = 'fields_' + input.getAttribute('id');
				// find all elements in this document matching class
				var elements = getElementsByClass(className);
				for (i = 0; i < elements.length; i++) {
					element = elements[i];
					// if radio/checkbox checked, show the elements, otherwise hide
					if (input.checked) {
						element.style.display = '';
					} else {
						element.style.display = "none";
					}
				}
			}
		}
	}
}

function toggleClass(className) {
	// toggle visibility of elements by their class name
	var elements = getElementsByClass(className);
	for (i = 0; i < elements.length; i++) {
		element = elements[i];
		if (element.style.display == 'none') {
			//toggleArrow(className, 'open');
			element.style.display = '';
		} else {
			//toggleArrow(className, 'close');
			element.style.display = "none";
		}
	}
}

function changeImage(e) {
	
	var element;
	
	// cross browser method of finding out who is calling this function
	// this is the IE way
	if (window.event && window.event.srcElement) {
		element = window.event.srcElement;
	}
	if (e && e.target) {
		element = e.target;
	}
	
	// make sure we get an anchor tag
	while (element != document.body && element.nodeName.toLowerCase() != 'a') {
		element = element.parentNode;
	}
	
	// get the value of the element
	//var src = element.src;
	// change the src of the main image
	//var mainImage = document.getElementById("imagePlaceholder");
	//mainImage.src = src;
	
	// get the id of the div to toggle (found in the rel attribute of the anchor)
	var toggleDiv = element.getAttribute("rel");
	//alert(toggleDiv);
	
	var toggleDivs = new Array('productImage1', 'productImage2', 'productImage3');
	for (var i = 0; i < toggleDivs.length; i++) {
		
		var tempToggleDiv = toggleDivs[i];
		if (document.getElementById(tempToggleDiv)) {
			//alert(element);
			if (tempToggleDiv == toggleDiv) {
				document.getElementById(tempToggleDiv).style.display = '';
			} else {
				document.getElementById(tempToggleDiv).style.display = 'none';
			}
		}
	}
	
	// turn off all borders first
	var images = document.getElementById("productImages").getElementsByTagName("img");
	for (var i = 0; i < images.length; i++) {
		var image = images[i];
		image.style.borderColor = '#ccc';
	}
	
	// turn on selected image border
	element.style.borderColor = '#c36';
	
	// cancel default anchor link
	if (window.event) {
		window.event.returnValue = false;
	} else {
		e.preventDefault();
	}
}

function togglePopUpLink(activeElement) {
	// hide all links first
	var stuff = new Array('image1XL', 'image2XL', 'image3XL');
	for (var i = 0; i < stuff.length; i++) {
		
		var element = stuff[i];
		if (document.getElementById(element)) {
			//alert(element);
			if (element == activeElement) {
				document.getElementById(element).style.display = '';
			} else {
				document.getElementById(element).style.display = 'none';
			}
		}
	}
}

function removeChildren(elementID) {
	var parent = document.getElementById(elementID);
	// remove all existing nodes
	while (parent.childNodes.length > 0) {
		parent.removeChild(parent.childNodes[0]);
	}
}

function rebuildLargeProductImage(elementID) {
	// look for a large image
	if (document.getElementById(elementID)) {
	
		var XLImageIdHref = document.getElementById(elementID).value;
		
		// update #largeProductImage
		var XLImageLink = document.getElementById("largeProductImage");
		
		var XLImageLinkAnchor = document.createElement("a");
		XLImageLinkAnchor.setAttribute('href', XLImageIdHref);
		// attach popLargeWindow function to anchor
		addEvent(XLImageLinkAnchor, 'click', popLargeImage, false);
		XLImageLinkAnchor.onclick = cancelClick; // for the benefit of Safari
		
		var XLImageLinkAnchorText = document.createTextNode('View Large Image');
		
		// join them all together
		XLImageLinkAnchor.appendChild(XLImageLinkAnchorText);
		XLImageLink.appendChild(XLImageLinkAnchor);
		// append to #largeProductImage
	}
}

function setUpImageSwap() {	
	if (document.getElementById) {
		if (document.getElementById("productImages")) {
			/* build an array of all links in 'productImages' */
			var anchors = document.getElementById("productImages").getElementsByTagName("a");
			for (var i = 0; i < anchors.length; i++) {
				var element = anchors[i];
				addEvent(element, 'click', changeImage, false);
				element.onclick = cancelClick; // for the benefit of Safari
			}
		}
	}	
}

function addEvent(elm, evType, fn, useCapture) {
	// cross-browser event handling for IE5+, NS6 and Mozilla 
	// By Scott Andrew 
	if (elm.addEventListener) { 
		elm.addEventListener(evType, fn, useCapture); 
		return true; 
	} else if (elm.attachEvent) { 
		var r = elm.attachEvent('on' + evType, fn); 
		return r; 
	} else {
		elm['on' + evType] = fn;
	}
}

function cancelClick() { return false; } // for the benefit of Safari
	
function previewImage(formname, listname, intwidth, intheight) {

	var sel = document.forms[formname].elements[listname];
	var imageid = sel.options[sel.selectedIndex].value;
	
	var ShowPage = 'preview_image.php?file=' + imageid;
	var leftpos = (screen.width - intwidth) / 2;
	var toppos = (screen.height - intheight) / 2;
	var winprops = 'toolbar=0, scrollbars=1, location=0, statusbars=0, menubar=0, width=' + intwidth + ', height=' + intheight + ', left=' + leftpos + ', top=' + toppos + ', resizable=1';
    var popupwindow = window.open(ShowPage, 'preview_image', winprops);
}

function clearMe(thefield){
	if (thefield.defaultValue==thefield.value) {
		thefield.value = "";
	}
} 

function pop(ShowPage, intwidth, intheight) {

	var leftpos = (screen.width - intwidth) / 2;
	var toppos = (screen.height - intheight) / 2;
	var winprops = 'toolbar=0, scrollbars=1, location=0, statusbars=0, menubar=0, width=' + intwidth + ', height=' + intheight + ', left=' + leftpos + ', top=' + toppos + ', resizable=1';
    var popupwindow = window.open(ShowPage, 'poppage', winprops);

}

function popLargeImage(e) {

	var element;
	
	/* cross browser method of finding out who is calling this function */
	// this is the IE way
	if (window.event && window.event.srcElement) {
		element = window.event.srcElement;
	}
	if (e && e.target) {
		element = e.target;
	}
	
	/* get the value of the element */
	var url = element.href;
	
	alert(url);
	
	var intwidth = 600;
	var inheight = 600;
	var leftpos = (screen.width - intwidth) / 2;
	var toppos = (screen.height - intheight) / 2;
	var winprops = 'toolbar=0, scrollbars=1, location=0, statusbars=0, menubar=0, width=' + intwidth + ', height=' + intheight + ', left=' + leftpos + ', top=' + toppos + ', resizable=1';
    var popupwindow = window.open(url, 'poppage', winprops);

}

function toggleEnableField(myForm) {

	foo = myForm.send_invoice.checked;
	
	if (foo) {
		myForm.invoice_name.disabled=false;
		myForm.invoice_name.style.backgroundColor='#fff';
	} else {
		myForm.invoice_name.disabled=true;
		myForm.invoice_name.value='';
		myForm.invoice_name.style.backgroundColor='#eee';
	}
	
}

function duplicateAddresses(myForm) {

	myForm.billing_address1.value = myForm.postal_address1.value;
	myForm.billing_address2.value = myForm.postal_address2.value;
	myForm.billing_town.value = myForm.postal_town.value;
	myForm.billing_city.value = myForm.postal_city.value;
	myForm.billing_postcode.value = myForm.postal_postcode.value;
	myForm.billing_country.selectedIndex = myForm.postal_country.selectedIndex;


}

function duplicateInvoiceAddress() {
	var checked = document.getElementById('copyInvoiceAddress').checked;
	if (checked) {
		document.getElementById('delivery_address_1').value = document.getElementById('invoice_address_1').value;
		document.getElementById('delivery_address_2').value = document.getElementById('invoice_address_2').value;
		document.getElementById('delivery_town').value = document.getElementById('invoice_town').value;
		document.getElementById('delivery_city').value = document.getElementById('invoice_city').value;
		document.getElementById('delivery_postcode').value = document.getElementById('invoice_postcode').value;
		document.getElementById('delivery_country').value = document.getElementById('invoice_country').value;
	}
}

// toggle visibility

function toggle(targetID) {
	if (document.getElementById) {
		target = document.getElementById(targetID);
		alert(target.style.display);
		if (target.style.display == "none") {
			target.style.display = "";
		} else {
			target.style.display = "none";
		}
	}
}

function toggleSignInForm() {
	if (document.getElementById) {
		theForm = document.getElementById('signInForm');
		theRadio = document.getElementById('signInRadio_2');
		theEmailField = document.getElementById('signInEmail');
		if (theRadio.checked) {
			theForm.style.display = '';
			theEmailField.focus();
		} else {
			theForm.style.display = 'none';
		}
	}
}



function toggleItem(targetID, target2ID) {
	if (document.getElementById) {
		target = document.getElementById(targetID);
		target2 = document.getElementById(target2ID);
		if (target.style.display == "none") {
			target.style.display = "";
			target2.style.backgroundImage = "url('/lifecentre/images/triangle-open.gif')";
		} else {
			target.style.display = "none";
			target2.style.backgroundImage = "url('/lifecentre/images/triangle-close.gif')";
		}
	}
}

function newImage(arg) {	
	if (document.images) {		
		rslt = new Image();		
		rslt.src = arg;		
		return rslt;	
	}
}

function changeImages() {	
	if (document.images && (preloadFlag == true)) {		
		for (var i=0; i<changeImages.arguments.length; i+=2) {			
			document[changeImages.arguments[i]].src = changeImages.arguments[i+1];		
		}	
	}
}

var preloadFlag = false;

function preloadImages() {	
	if (document.images) {		
		img_1 = newImage("../images/donate_button_on.gif");
		preloadFlag = true;
	}
}
	
function goJump(which_form) {
	self.location.href=which_form.jump.options[which_form.jump.selectedIndex].value;
}

function selectJump(which_form) {
	self.location.href=which_form.jump.options[which_form.jump.selectedIndex].value;
}

function activeEnquiryType(which_form) {

	if (document.getElementById) {
	
		// hide all submenus to begin with
		document.getElementById("submenu_4").style.display = "none";
		document.getElementById("submenu_5").style.display = "none";
		document.getElementById("submenu_16").style.display = "none";
		
		foo = which_form.enquiryType.options[which_form.enquiryType.selectedIndex].value;
		
		//alert(foo);
		targetID = "submenu_" + foo;
	
		target = document.getElementById(targetID);
		if (target) {
			target.style.display = "";
		}
	} else {
		// don't support the DOM, show all submenus
		document.getElementById("submenu_4").style.display = "";
		document.getElementById("submenu_5").style.display = "";
		document.getElementById("submenu_16").style.display = "";
	}
	
}

function validateNumber(field, msg, min, max) {
	if (!min) { min = 0 }
	if (!max) { max = 255 }
	if ( (parseInt(field.value) != field.value) || field.value.length < min || field.value.length > max) {
		alert(msg);
		field.focus();
		field.select();
		return false;
	}
	return true;
}

function validateString(field, msg, min, max) {
	if (!min) { min = 1 }
	if (!max) { max = 65535 }
	if (!field.value || field.value.length < min || field.value.max > max) {
		alert(msg);
		field.focus();
		field.select();
		return false;
	}
	return true;
}

function validateEmail(email, msg, optional) {
	if (!email.value && optional) {
		return true;
	}

	var re_mail = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z])+$/;
	
	if (!re_mail.test(email.value)) {
		alert(msg);
		email.focus();
		email.select();
		return false;
	}
	return true;
}

function validateList(listname, msg) {

	var foo = listname.selectedIndex;

	if (foo == 0 || foo == -1) {
		alert(msg);
		return false;
	}
	
	return true;
	
}

function addLoadEvent(func) {
	var oldonload = window.onload;
	if (typeof window.onload != 'function') {
		window.onload = func;
	}
	else {
		window.onload = function() {
			oldonload();
			func();
		}
	}
}

function setDeliveryDetailsAsBilling() {
	document.getElementById('customerName').value = document.getElementById('billingName').value;
	document.getElementById('deliveryAddress1').value = document.getElementById('billingAddress1').value;
	document.getElementById('deliveryAddress2').value = document.getElementById('billingAddress2').value;
	document.getElementById('deliveryAddress3').value = document.getElementById('billingAddress3').value;
	document.getElementById('deliveryCity').value = document.getElementById('billingCity').value;
	document.getElementById('deliveryCounty').value = document.getElementById('billingCounty').value;
	document.getElementById('deliveryCountry').value = document.getElementById('billingCountry').value;
	document.getElementById('deliveryPostcode').value = document.getElementById('billingPostcode').value;
}

function checkSignIn() {
	if (document.getElementById('signInRadio_1') && document.getElementById('signInRadio_2')) {
		var radio_1 = document.getElementById('signInRadio_1');
		var radio_2 = document.getElementById('signInRadio_2');
		if (!radio_1.checked && !radio_2.checked) {
			alert('Please either sign-in or create an account.');
			return false;
		}
	}
}

function validateRegistration(formName) {

	if (!validateString(formName.firstname, 'Please provide your firstname.', 1, 100)) { return false; }
	if (!validateString(formName.surname, 'Please provide your surname.', 1, 100)) { return false; }
	if (!validateEmail(formName.email, 'Please supply a valid email address.', 0)) { return false; }
	if (!validateString(formName.organisation, 'Please provide the name of your organisation.', 1, 200)) { return false; }
	if (!validateList(formName.organisation_size_id, 'Please indicate the size of the organisation')) { return false; }
	if (!validateString(formName.postcode, 'Please provide your postcode.', 1, 20)) { return false; }
	if (!validateString(formName.username, 'Please provide a username between 4 and 20 characters long.', 4, 20)) { return false; }
	if (!validateString(formName.password, 'Please provide a password between 4 and 20 characters long.', 4, 20)) { return false; }
	
	if (document.getElementById('input_reason')) {
		var reason = document.getElementById('input_reason');
		if (reason.selectedIndex == 1 || reason.selectedIndex == 2) {
			if (!validateString(formName.planningID, 'Please provide your Planning ID', 1, 100)) { return false; }
		}
	}
}

function validateTradeOrder(thisForm) {

	if (!validateString(thisForm.company, 'Please provide your company/shop name', 1, 200)) { return false; }
	if (!validateString(thisForm.name, 'Please provide your name', 1, 200)) { return false; }
	if (!validateEmail(thisForm.email, 'Please provide a valid email address', 0)) { return false; }
	if (!validateString(thisForm.delivery_address_1, 'Please provide the 1st line of your delivery address', 1, 200)) { return false; }
	if (!validateString(thisForm.delivery_postcode, 'Please provide your delivery postcode', 1, 200)) { return false; }
	if (!validateString(thisForm.invoice_address_1, 'Please provide the 1st line of your invoice address', 1, 200)) { return false; }
	if (!validateString(thisForm.invoice_postcode, 'Please provide your invoicing postcode', 1, 200)) { return false; }
}

function validateTradeApplication(thisForm) {
	if (!validateString(thisForm.buyer_name, 'Please provide your name.', 1, 100)) { return false; }
	if (!validateString(thisForm.username, 'Please choose a username between 4 and 20 characters.', 4, 20)) { return false; }
	if (!validateString(thisForm.pass, 'Please choose a password between 4 and 20 characters.', 4, 20)) { return false; }
	if (!validateString(thisForm.trading_name, 'Please provide your trading name.', 1, 100)) { return false; }
	if (!validateString(thisForm.address, 'Please provide your trading address.', 1, 600)) { return false; }
	if (!validateString(thisForm.postcode, 'Please provide your postcode.', 1, 20)) { return false; }
	if (!validateString(thisForm.tel, 'Please provide your telephone number.', 1, 30)) { return false; }
	if (!validateEmail(thisForm.email, 'Please provide a valid email address.', 0)) { return false; }
	if (!validateString(thisForm.vat_no, 'Please provide your VAT Number.', 1, 60)) { return false; }
	
	if (document.getElementById('status_limited').checked) {
		if (!validateString(thisForm.company_no, 'Please provide your Company Registration Number', 1, 100)) { return false; }
	}
	
	// if a sole trader, need values for home address
	if (document.getElementById('status_sole_trader').checked) {
		if (!validateString(thisForm.home_address, 'Please provide your home address', 1, 600)) { return false; }
		if (!validateString(thisForm.home_postcode, 'Please provide your home postcode', 1, 20)) { return false; }
		if (!validateString(thisForm.home_tel, 'Please provide your home telephone number', 1, 100)) { return false; }
	}
	
	// a new customer, need to supply all details of referees
	if (document.getElementById('new_customer_yes').checked) {
	
		if (!validateString(thisForm.ref1_name, 'Please provide a name for Reference 1.', 1, 100)) { return false; }
		if (!validateString(thisForm.ref1_address, 'Please provide an address for Reference 1.', 4, 600)) { return false; }
		if (!validateString(thisForm.ref1_postcode, 'Please provide the postcode for Reference 1.', 4, 20)) { return false; }
		if (!validateString(thisForm.ref1_tel, 'Please provide a telephone number for Reference 1.', 1, 100)) { return false; }
		if (!validateEmail(thisForm.ref1_email, 'Please provide a valid email address for Reference 1.', 0)) { return false; }
		
		if (!validateString(thisForm.ref2_name, 'Please provide a name for Reference 2.', 1, 100)) { return false; }
		if (!validateString(thisForm.ref2_address, 'Please provide an address for Reference 2.', 4, 600)) { return false; }
		if (!validateString(thisForm.ref2_postcode, 'Please provide the postcode for Reference 2.', 4, 20)) { return false; }
		if (!validateString(thisForm.ref2_tel, 'Please provide a telephone number for Reference 2.', 1, 100)) { return false; }
		if (!validateEmail(thisForm.ref2_email, 'Please provide a valid email address for Reference 2.', 0)) { return false; }
		
	}
}


addLoadEvent(setUpImageSwap);
addLoadEvent(setUpTradeApplicationFormToggleFields);
addLoadEvent(get_trade_notice);