/**
 * This is the core vstall store javascript file which contains all of the standard scripting
 * code within the sites, this will minimise the number of requests to the server
 */

/**
 * DOMREADY - initialisation javascript functions to setup validations IE6 PNG fixes etc
 */
window.addEvent( 'domready', function( ) {

	   /**
	    *  Use Clientcide fixPNG library to handle IE png fixing
	    */
	   Browser.scanForPngs($('body'));
	   document.getElements('.fixPNG').each(function (el) {
		   Browser.fixPNG(el);
	   });
	   
	
       /**
        * Locate all of the basket add forms on the page and switch to AJAX submission
        */
       if ( $defined( $( 'mini_basket' ) ) ) {
    	   $$('.basket_add_form' ).addEvent( 'submit', function( e ) {
               // Stop the form submitting
    		   e = new Event( e );
    		   e.stop( );
    		   submit_via_ajax( e.target, 'mini_basket', update_basket_links, true );
    	   } );
    	   update_basket_links( );
       }

       /**
        * Add in the new elements to instruct vstall which controller and action to take 
        * once the item has been added to the basket. 
        */
       var free_delivery_forms = $$( '#free_delivery_offers .basket_add_form' );
       if ( $defined( free_delivery_forms ) ) {
    	   free_delivery_forms.removeEvents( );
    	   free_delivery_forms.each( function( el ) {
    		   new Element( 'input', {'name': 'controller', 'type': 'hidden', 'value': 'checkout'} ).injectInside( el );
    		   new Element( 'input', {'name': 'action', 'type': 'hidden','value': 'delivery_confirmation'} ).injectInside( el );
    	   } );
    	}
    
       /**
        * Loop through all of the dialogs in the system and pre-load the content to avoid 
        * a white screen at the time it is displayed
        */
       var dialogLinks = $$( 'a[rel=dialog]' );
       dialogLinks.each( function( el ) {
    	    var ajax = new Request.HTML(  {
    	    	url: el.getProperty( 'href' ),
    	    	method: 'get',
    	    	onComplete: function(responseTree, responseElements, responseHTML, responseJavaScript) {    		   
               		el.addEvent( 'click', function( e ) {
               			e = new Event( e );
               			e.stop( );
               			if ( !$defined( $( 'dialog' ) ) ) {
               				var body = $( document.body );
               				if ( window.ie6 ) body.addClass( 'fixed' ); // IE 6 Positional fix
               				var mask = new Element( 'div', { 'styles' : {'background-color' : '#000000', 'opacity' : 0, 'z-index' : 100 }, 'id' : 'mask' } );
               				mask.injectInside( body );
               				var dialog = new Element( 'div', {'styles' : {'left': '50%', 'top': -1000, 'z-index': 200}, 'id' : 'dialog'} );
               				dialog.set('html', responseHTML );
               				dialog.injectInside( body );

               				var dialogCoords = dialog.getCoordinates( );
               				fadeIn = new Fx.Morph( mask, {
               					duration : 500,
               					onComplete: function( ) {
               					dialog.setStyles( {'left': '50%', 'top': '50%', 
               						               'margin-left': ( dialogCoords['width'] / 2 ) * -1, 
               						               'margin-top': ( dialogCoords['height'] / 2 ) * -1} );
               					}
               				});
               				fadeIn.start({'opacity': 0.4 });
               			}
               		});
            	}
    	   });
    	   ajax.send();
       });
});

function toggle_wdyhau_other(element) {		
	var other_box = $$('p#account_website_wdyhau_other');
	var selected_value = element.options[element.value].text.toUpperCase();
	
	if(selected_value == 'OTHER'){		
		other_box.removeClass('hidden');		
	} else {		
		other_box.addClass('hidden');
	}
}

function toggle_additional_report_information(name)
{
	if ($defined($('spend_report'))) {
		$status = 'show';
		$('spend_report').getElements('.spacer, .additional').each(function (item) {
			if (item.hasClass('hidden')) {
				item.removeClass('hidden');
				$status = 'hide';
			} else {
				item.addClass('hidden');
				$status = 'show';
			}
		});
		$('report_holder').getElements('.additional_info_link').each(function (item) {
			if ($status == 'show') item.set('text','Show ' + name +  ' Names');
			else item.set('text','Hide '+name+' Names');
		});
	}
}

function show_detail_orderlist_row(link)
{
	var summary_row = link.getParent().getParent();
	var detail_row = link.getParent().getParent().getNext();
	summary_row.setStyles({'display': 'none'});
	detail_row.setStyles({'display': 'block', 'opacity': 0});
	new Fx.Morph( detail_row, {duration : 1000}).start({'opacity':1});	
}

/**
 * Toggle the display of the credit card information in the checkout 
 */
function toggle_cc_example()
{
	if ($('credit_card_example').hasClass('hidden')) $('credit_card_example').removeClass('hidden');
	else $('credit_card_example').addClass('hidden');
}

/**
 * Create and display a standard vstall popup window and load the specified content 
 */
function vstall_dialog_show(url, width, height, mode) {
	if ( $( 'dialog' ) == null ) {
		var body = $( document.body );
		if ( window.ie6 ) body.addClass( 'fixed' ); // IE 6 Positional fix
		var mask = new Element( 'div', {'styles' : {'background-color' : '#000000','opacity': 0},'id' : 'mask'});
		mask.injectInside( body );
		dialog = new Element( 'div', {'styles' : {'width': width + 'px', 'height': height + 'px',   
			                  'margin-left' : '-' + ( width / 2 ) + 'px',
                              'margin-top'  : '-' + ( height / 2 ) + 'px'}, 'id' : 'dialog'});
		dialog.set('html', '<iframe src="' + url + '" frameborder="0" />' );
		dialog.injectInside( body );
		fadeIn = new Fx.Morph( mask, {duration : 1000 } );
		fadeIn.start({'opacity': 0.4});
	}
}

/**
 * Hide the current popup window from the site 
 */
function vstall_dialog_hide( perform_callback )	{
	var dialogAndMask = [ $( 'dialog'), $( 'mask' ) ];
	var fx = new Fx.Elements( dialogAndMask, {
		duration: 500,
		onComplete: function( ) {
			if ($defined($( 'dialog' )))	$( 'dialog' ).destroy( );
			if ($defined($( 'mask' )))	$( 'mask' ).destroy( );
     	}
	});
	fx.start( {'0': {'opacity': 0},'1': {'opacity': 0}} );
}

function update_and_checkout_warning(form)
{
	if (confirm('Warnings have been raised based on your basket contents and your account configuration are you sure you have reviewed the content and that your are happy to place this order')) {
		if (check_process_order_cost_centres(form)) {
			form.action.value = "update_basket_confirm_warning";
			form.submit();
		}
	}
}
function update_and_checkout_approval(form)
{
	if (confirm('The contents of your shopping basket mean your order requires approval by a supervisor, please review the contents of your order and ensure you are happy to send it for approval')) {
		if (check_process_order_cost_centres(form)) {
			form.action.value = "update_basket_confirm_approval";
			form.submit();
		}
	}
}
function update_and_checkout_split(form)
{
	if (confirm('The contents of your shopping basket will be split with some of the items being sent for approval, are you sure you want to continue?')) {
		if (check_process_order_cost_centres(form)) {
			form.action.value = "update_basket_confirm_split";
			form.submit();
		}
	}
}

function update_and_checkout_prevent(form)
{
	alert('One or more ordering restrictions have been broken which means you are prevented from placing this order, please review the contents of the basket.');
	return false;
}

function check_process_order_cost_centres(form) {
	var cost_centres_assigned = true;

	// Loop through all of the form elements
	for (var i = 0; i < form.elements.length; i++) {
		// Check to see if this is a select box where only one option canbe selected
		if (form.elements[i].type == "select-one" && form.elements[i].name != 'master_cost_centres') {
			if (form.elements[i].value == '') {
				cost_centres_assigned = false;
				break;
			}
		}
	}

	if (cost_centres_assigned == false) {
		alert('Please assign a cost centre to ALL order lines');
		return false;
	}

	return true;
}

function update_and_checkout(form)
{
	if (check_process_order_cost_centres(form)) {
		form.action.value = "update_basket_checkout";
		form.submit();
		
		return true;
	} else {
		return false;
	}
}

function assign_cost_centre(form) 
{
	var form = form;
	var combo = document.getElementById('master_cost_centres')
	var cost_centre = combo.value;
	var cost_centre_name = combo.options[combo.selectedIndex].text;
	
	// Loop through all of the form elements
	for (var i = 0; i < form.elements.length; i++) {
		// Check to see if this is a select box where only one option can be selected
		if (form.elements[i].type == "select-one") {
			form.elements[i].value = cost_centre;
		}
		if (form.elements[i].type == "text") {
			form.elements[i].value = cost_centre_name;
		}
		if (form.elements[i].type == "hidden") {
			form.elements[i].value = cost_centre;
		}
	}

	return true;
}

function split_update_and_checkout(form)
{
	if (confirm('Your shopping basket will be split into two orders, are you sure you want to continue?')) {
		form.action.value = "update_basket_checkout";
		form.submit();
	}
}



function check_process_order_delivery(form) {

	if ($defined(form.customer_address_book_address_line_1)) {

		var error_message = "PLEASE REVIEW AND COMPLETE THE FOLLOWING" + "\n\n";
		var error         = 0;
	
		if (form.customer_address_book_name.value.trim() == '') {
			error_message = error_message + "* Addressee name" + "\n";
			error = 1;
		}
		if (form.customer_address_book_address_line_1.value.trim() == '') {
			error_message = error_message + "* Property number" + "\n";
			error = 1;
		}
		if (form.customer_address_book_city.value.trim() == '') {
			error_message = error_message + "* City" + "\n";
			error = 1;
		}
		if (form.customer_address_book_postcode.value.trim() == '') {
			error_message = error_message + "* Postcode" + "\n";
			error = 1;
		}
		if ($('account_website_address_postcode_validate_uk_format').value == 'Y') {
			var postcode_result =  ValidUKPostCode(form.customer_address_book_postcode.value);
			if (postcode_result != true) {
				error_message = error_message + "* Invalid UK Postcode Format - " + postcode_result + "\n";
				error = 1;		
			}
		}
		if (form.system_countries_id.value.trim() == '') {
			error_message = error_message + "* Country" + "\n";
			error = 1;
		}
		if (form.customer_address_book_telephone.value.trim() == '') {
			error_message = error_message + "* Telephone" + "\n";
			error = 1;
		}
	
		if (error == 1) {
			alert(error_message);
			return false;
		}
	
	} else {	
	
		var address_selected = false;
	
		if (form.customer_address_book_id.length == undefined) {
			address_selected = form.customer_address_book_id.checked;
		} else {
			for (var i=0; i<form.customer_address_book_id.length;i++) {
				if (form.customer_address_book_id[i].checked) {
					address_selected = true;
					break;
				}
			}
		}
	
		if (address_selected == false) {
			alert('Please select your delivery address');
			return false;
		}
		
	}
	
}

function check_process_order_confirm(form) {

	if ($defined(form.customer_payment_method_card_number)) {

		var error = 0;
		var error_message = "PLEASE REVIEW AND COMPLETE THE FOLLOWING\n\n";

		var card_type = $(form.account_website_payment_method_type_id.options[form.account_website_payment_method_type_id.selectedIndex]).get('rel');

		if(form.customer_payment_method_card_number.value.trim() == '') {
			error_message = error_message + "* Card Number\n";
			error = 1;
		}
		if(form.account_website_payment_method_type_id.value.trim() == '') {
			error_message = error_message + "* Card Type\n";
			error = 1;
		}
		if(form.customer_payment_method_expiry_month.value.trim() == '') {
			error_message = error_message + "* Expiry Month\n";
			error = 1;
		}
		if(form.customer_payment_method_expiry_year.value.trim() == '') {
			error_message = error_message + "* Expiry Year\n";
			error = 1;
		}
		if (card_type != 'LASER') {
			if(form.customer_payment_method_cv2.value.trim() == '') {
				error_message = error_message + "* Security Digits\n";
				error = 1;
			}
		}
		if(form.billing_customer_address_book_name.value.trim() == '') {
			error_message = error_message + "* Address Name\n";
			error = 1;
		}
		if(form.billing_customer_address_book_address_line_1.value.trim() == '') {
			error_message = error_message + "* First Line of Address\n";  error = 1;
		}
		if(form.billing_customer_address_book_postcode.className == 'inputfield_required') {
			if(form.billing_customer_address_book_postcode.value.trim() == '') {
				error_message = error_message + "* Postcode\n";
				error = 1;
			}
		}
		if ($('account_website_address_postcode_validate_uk_format').value == 'Y') {
			var postcode_result =  ValidUKPostCode(form.billing_customer_address_book_postcode.value);
			if (postcode_result != true) {
				error_message = error_message + "* Invalid UK Postcode Format - " + postcode_result + "\n";
				error = 1;		
			}
		}
		
		if(form.billing_customer_address_book_telephone.value.trim() == '') {
			error_message = error_message + "* Telephone\n";
			error = 1;		
		}
		
		if (error == 1) {
			alert(error_message);
			return false;
		}		
	} 
	
	if ($defined($('order_non_returnable_checkbox'))) {
		if ($('order_non_returnable_checkbox').checked == false) {
			alert('Your order contains non-returnable items please confirm you agree with the terms and conditions');
			return false;
		}
	}
	
	if (check_confirm_order(form) == false) {
		return false;
	} else {		
		if (form.delivery_rate_id && form.delivery_rate_id.value != -1) {
			var rate_selected = false;
			if (form.delivery_rate_id.length == undefined) {
				rate_selected = form.delivery_rate_id.checked;
			} else {
				for (var i=0; i<form.delivery_rate_id.length;i++) {
					if (form.delivery_rate_id[i].checked) {
						rate_selected = true;
						break;
					}
				}
			}

			if (rate_selected == false) {
				alert('Please select a delivery rate');
				return false;
			}
		}
	}

	setTimeout(function(){document.getElementById('frmprocessorder').submit();}, 500);
	show_order_progress('B2B');
	return false;
}



function check_surfer_order_confirm(form) {

	var error = 0;
	var error_message = "PLEASE REVIEW AND COMPLETE THE FOLLOWING\n\n";

	if (form.system_payment_method_id.value == 1) {

		var card_type = $(form.account_website_payment_method_type_id.options[form.account_website_payment_method_type_id.selectedIndex]).get('rel');

		if(form.customer_payment_method_card_number.value.trim() == '') {
			error_message = error_message + "* Card Number\n";
			error = 1;
		}
		if(form.account_website_payment_method_type_id.value.trim() == '') {
			error_message = error_message + "* Card Type\n";
			error = 1;
		}
		if(form.customer_payment_method_expiry_month.value.trim() == '') {
			error_message = error_message + "* Expiry Month\n";
			error = 1;
		}
		if(form.customer_payment_method_expiry_year.value.trim() == '') {
			error_message = error_message + "* Expiry Year\n";
			error = 1;
		}
		if (card_type != 'LASER') {
			if(form.customer_payment_method_cv2.value.trim() == '') {
				error_message = error_message + "* Security Digits\n";
				error = 1;
			}
		}
	} else if (form.system_payment_method_id.value == 2) {
		if(form.order_customer_reference.value.trim() == '') {
			error_message = error_message + "* Your Order Reference\n";
			error = 1;
		}
	}
	if(form.billing_customer_address_book_name.value.trim() == '') {
		error_message = error_message + "* Address Name\n";
		error = 1;
	}
	if(form.billing_customer_address_book_address_line_1.value.trim() == '') {
		error_message = error_message + "* First Line of Address\n";  error = 1;
	}
	if(form.billing_customer_address_book_address_line_1.value.trim() == '') {
		error_message = error_message + "* First Line of Address\n";  error = 1;
	}
	if(form.billing_customer_address_book_postcode.className == 'inputfield_required') {
		if(form.billing_customer_address_book_postcode.value.trim() == '') {
			error_message = error_message + "* Postcode\n";
			error = 1;
		}
	}
	if ($('account_website_address_postcode_validate_uk_format').value == 'Y') {
		var postcode_result =  ValidUKPostCode(form.billing_customer_address_book_postcode.value);
		if (postcode_result != true) {
			error_message = error_message + "* Invalid UK Postcode Format - " + postcode_result + "\n";
			error = 1;		
		}
	}
	
	if(form.billing_customer_address_book_telephone.value.trim() == '') {
		error_message = error_message + "* Telephone\n";
		error = 1;
	}
	
	if(form.account_website_wdyhau_id != undefined && form.account_website_wdyhau_id.value.trim() == '') {
		error_message = error_message + "* Where did you hear about us\n";
		error = 1;
	}


	if (error == 1) {
		alert(error_message);
		return false;
	}

	setTimeout(function(){document.getElementById('frmcheckoutpayment').submit();}, 1000);
	show_order_progress('B2C');
	return false;
}

function toggle_payment_method(system_payment_method_id) {
	document.getElementById('frmcheckoutpayment').system_payment_method_id.value = system_payment_method_id;
	if (document.getElementById('card_payments').style.display == 'none') {
		document.getElementById('card_payments').style.display = 'block';
		document.getElementById('account_payments').style.display = 'none';
		document.getElementById('card_payments_title').style.display = 'none';
		document.getElementById('account_payments_title').style.display = 'block';
	} else {
		document.getElementById('card_payments').style.display = 'none';
		document.getElementById('account_payments').style.display = 'block';
		document.getElementById('card_payments_title').style.display = 'block';
		document.getElementById('account_payments_title').style.display = 'none';
	}
}

/**
 * This function will show an overlayed progress screen when the user is checking 
 * out of the stores, a different message is shown for both B2B and B2C
 * @return
 */
function show_order_progress(mode) 
{
	var height = 100;
	var width = 200;
	
	if ( $( 'dialog' ) == null ) {
		var body = $( document.body );
		if ( window.ie6 ) body.addClass( 'fixed' ); // IE 6 Positional fix
		var mask = new Element( 'div', {'styles' : {'background-color' : '#000000','opacity': 0},'id' : 'mask'});
		mask.injectInside( body );
		dialog = new Element( 'div', {'id' : 'order_progress_dialog'});
		if (mode == 'B2C') {
			dialog.set('html','<h4>Your order is being processed</h4>' + 
							'<p class="description">Please be patient while we process your card details, you will be taken to your order confirmation when this has been completed.</p>' + 
							'<p class="image"><img src="/images/rel_interstitial_loading.gif" alt="Processing" /></p>');
		} else {
			dialog.set('html','<h4>Your order is being processed</h4>' + 
					'<p class="description">Please be patient while we save your order, you will be taken to your order confirmation when this has been completed.</p>' + 
					'<p class="image"><img src="/images/rel_interstitial_loading.gif" alt="Processing" /></p>');
		}
		dialog.injectInside( body );
		fadeIn = new Fx.Morph( mask, {duration : 250 } );
		fadeIn.start({'opacity': 0.4 });
	}
}


/**
 * Cross browser support for bookmark links 
 */
function CreateBookmarkLink() {
	var title = document.title;
	var url = document.location.href;
	if (window.sidebar.addPanel) { // Mozilla Firefox Bookmark
		window.sidebar.addPanel(title, url,"");
	} else if( window.external ) { // IE Favorite
		window.external.AddFavorite( url, title); 
	} else if(window.opera && window.print) { // Opera Hotlist
		return true; 
	}
}

/**
 * Moves selected elements from one list box to another list 
 */
function move_to_list( source, dest ) {
    source = $( source );
    dest = $( dest );
	if ( source.selectedIndex != -1 ) {
	    for ( loop = 0; loop < dest.options.length; loop++ ) {
	        option = $( dest.options[loop] );
	        if ( ( option.getValue( ) == 'none' ) ||
	             ( option.getText( ) == ' ' ) ) {
                option.remove( );
            }
	    }
	    
	    dest.removeProperty( 'disabled' );

		for (i=0;i<source.options.length;i++) {
			if (source.options[i].selected) {
				dest.options[dest.options.length] = new Option(source.options[i].text, source.options[i].value);
			}
		}
		for (i=source.options.length-1;i>=0;i--) {
			if (source.options[i].selected) {
				source.options[i] = null;
			}
		}

		if ( source.options.length == 0 ) {
		    source.setProperty( 'disabled', 'disabled' );
		    filler = new Element( 'option', {
		                          value : 'none'
		    });
		    filler.setText( ' ' );
		    filler.injectInside( source );
		}
	}
}



var user_changes = false;


function isUnsignedInteger(s) {
	return (s.toString().search(/^[0-9]+$/) == 0);
}


/**
 * Allows the user to click on a price break box to QTY to basket 
 */
function add_price_break_to_basket(link, quantity)
{
	var form = $(link).getParent().getParent().getParent();
	form.product_quantity.value = quantity;
}

/**
 * Validates the user has entered something in the search criteria box 
 */
function check_quick_search(form)
{
  // Check to see if we have a keywords option on this page
  var can_search = false;
  if (form.filter_product_keywords) {
  	 // Check for criteria
	 if (form.filter_product_keywords.value.trim() != '' && form.filter_product_keywords.value.trim() != 'Keyword Search...' &&
	     form.filter_product_keywords.value.trim() != 'Keyword Search' &&
         form.filter_product_keywords.value.trim() != 'Enter your search keywords here...' &&
         form.filter_product_keywords.value.trim() != 'Your Search Terms...') {
	 	can_search = true;
	 }
  }
  if (form.filter_product_brand_id) {
  	 // Check for criteria
	 if (form.filter_product_brand_id.value.trim() != '') {
	 	can_search = true;
	 }
  }

  if(can_search == false) {
	  alert('Tell us what you want to search for first');
	  return false;
  }
  return true;
}

/**
 * 
 * @param form
 * @return
 */
function check_send_to_a_friend(form) 
{
	if (form.customer_email_address.value.trim() == '') {
		alert('Please provided your email address');
		return false;
	} 

	if (form.customer_email_address.value.trim() != '') {
		if (!isEmail(form.customer_email_address.value)) {
			alert('Your email address is not valid');
			return false;
		}
	}
		
	if ($('referal_email_1').value.trim() == '' &&
		$('referal_email_2').value.trim() == '' &&
		$('referal_email_3').value.trim() == '') {
		alert('Please enter a least one friends email address');
		return false;
	}
		
	if ($('referal_email_1').value.trim() != '') {
		if (!isEmail($('referal_email_1').value)) {
			alert('Please provide a valid email address for friend 1');
			return false;
		}
	}
	if ($('referal_email_2').value.trim() != '') {
		if (!isEmail($('referal_email_2').value)) {
			alert('Please provide a valid email address for friend 2');
			return false;
		}
	}
	if ($('referal_email_3').value.trim() != '') {
		if (!isEmail($('referal_email_3').value)) {
			alert('Please provide a valid email address for friend 3');
			return false;
		}
	}

	// Valid submission
	return true;
}

/**
 * Validation to ensure the user has entered a voucher code in the basket
 */
function check_basket_voucher(form) {
	// Check for criteria
	if (form.account_website_voucher_code_coupon.value.trim() == '') {
		alert('Enter your promotional code');
	} else {
		form.submit();
	}
}

/**
 * Validation for the quick order form
 */
function quick_order_add(form) {
	var error = 0;
	var error_message = "PLEASE REVIEW AND COMPLETE THE FOLLOWING\n\n";

	if(form.product_primary_code.value.trim() == '') {
		error_message = error_message + "* Product Code\n";
		error = 1;
	}
	if(form.qo_product_quantity.value.trim() == '') {
		error_message = error_message + "* Quantity\n";
		error = 1;
	}
	if (error == 1) {
		alert(error_message);
		return false;
	} else {
		return true;
	}
}

/**
 * Selects the number of rows in the datagrid
 */
function select_row_count(form, prefix)
{
    rows_selector = document.getElementById( prefix + 'rows' );
    value = 0;
    if ( rows_selector != null ) {
        value = rows_selector.value;
    } else {
        value = form.datagrid_row_count.value;
    }
	document.location.href= form.action + '/' + prefix + 'page/1/' + prefix + 'rows/' + value;
}



// This function is to be used when a login form can't be genereated by the HTML helper
function generic_customer_login_validation(form) {
	var error = 0;
	var error_message = "PLEASE REVIEW AND COMPLETE THE FOLLOWING\n\n";

	if(form.customer_email_address.value.trim() == '' || form.customer_email_address.value == 'Email address...' || form.customer_email_address.value == 'Email / Login Name') {
		error_message = error_message + "* Email Address\n";
		error = 1;
	}
	if(form.customer_password.value.trim() == '') {
		error_message = error_message + "* Password\n";
		error = 1;
	}
	if (error == 1) {
		alert(error_message);
		return false;
	} else {
		return true;
	}
}

// This function is to be used when a login form can't be genereated by the HTML helper
function generic_customer_subscribe(form) {
	var error = 0;
	var error_message = "PLEASE REVIEW AND COMPLETE THE FOLLOWING\n\n";

	if(form.customer_email_address.value.trim() == '' || 
	   form.customer_email_address.value == 'Email address...' ||
		form.customer_email_address.value == 'Your e-mail address') {
		error_message = error_message + "* Email Address\n";
		error = 1;
	}
	if (error == 1) {
		alert(error_message);
		return false;
	} else {
		return true;
	}
}

function check_customer_subscribe(form)
{
	return generic_customer_subscribe(form);
}



//-----------------------------------------------------------------------------------------

// This function will load the value for the specified cookie, if the cookie is not present
// within the browser then an empty string will be returned to the calling function
function get_cookie(cookie_name)
{
	// Initialise the value we will return
	var cookie_value = '';
	// Try and locate the position of our cookie
	var posName = document.cookie.indexOf(escape(cookie_name) + '=');
	// Is the cookie name present?
	if (posName != -1) {
		// Get hold of the position of the cookie value
		var posValue = posName + (escape(cookie_name) + '=').length;
		// Find the end of the value using the delimiter
		var endPos = document.cookie.indexOf(';', posValue);
		// Extract the value of the cookie
		if (endPos != -1) cookie_value = unescape(document.cookie.substring(posValue, endPos));
		else cookie_value = unescape(document.cookie.substring(posValue));
	}

	// Return the extracted value or default value to calling function
	return (cookie_value);
};
//-----------------------------------------------------------------------------------------



/**
 * Changes the class of the parent element for the selected radio button and
 * sets all the other possible value's parent to unselected
 **/
function toggle_selection( form, element ) {

    radios = form.getElements( 'input[name=' + element + ']' );

    radios.each( function( el ) {

        radio_parent = el.getParent( );

		if ( el.checked ) {

			radio_parent.removeClass( 'unselected_item' );
			radio_parent.addClass( 'selected_item' );

		} else {

			radio_parent.addClass( 'unselected_item' );
			radio_parent.removeClass( 'selected_item' );

		}

    });

}

function check_checkout_delivery(form) {
	if (form.customer_address_book_id.value != -1) {
		var address_selected = false;

		if (form.customer_address_book_id.length == undefined) {
			address_selected = form.customer_address_book_id.checked;
		} else {
			for (var i=0; i<form.customer_address_book_id.length;i++) {
				if (form.customer_address_book_id[i].checked) {
					address_selected = true;
					break;
				}
			}
		}

		if (address_selected == false) {
			alert('Select your delivery address');
			return false;
		}
	} else {
		var error_message = "PLEASE REVIEW AND COMPLETE THE FOLLOWING" + "\n\n";
		var error         = 0;

		if (form.customer_address_book_name.value.trim() == '') {
			error_message = error_message + "* Addressee name" + "\n";
			error = 1;
		}
		if (form.customer_address_book_address_line_1.value.trim() == '') {
			error_message = error_message + "* Property number" + "\n";
			error = 1;
		}
		if (form.customer_address_book_city.value.trim() == '') {
			error_message = error_message + "* City" + "\n";
			error = 1;
		}
		if (form.customer_address_book_postcode.value.trim() == '') {
			error_message = error_message + "* Postcode" + "\n";
			error = 1;
		}
		if (form.system_countries_id.value.trim() == '') {
			error_message = error_message + "* Country" + "\n";
			error = 1;
		}
		if (form.customer_address_book_telephone.value.trim() == '') {
			error_message = error_message + "* Telephone" + "\n";
			error = 1;
		}

		if (error == 1) {
			alert(error_message);
			return false;
		}
	}
}

function toggle_checkout_delivery_rate_selection(form) {
	form.action = '/checkout/confirm';
	form.submit();
}
function check_checkout_confirmation(form) {
	if (form.delivery_rate_id.value != -1) {
		var rate_selected = false;

		if (form.delivery_rate_id.length == undefined) {
			rate_selected = form.delivery_rate_id.checked;
		} else {
			for (var i=0; i<form.delivery_rate_id.length;i++) {
				if (form.delivery_rate_id[i].checked) {
					rate_selected = true;
					break;
				}
			}
		}

		if (rate_selected == false) {
			alert('Select a delivery rate');
			return false;
		}
	}
}



function check_edit_department_form(form) {
	var selected = "";
	var result   = check_department_details(form);

	if (result == true) {
		for (i=form.users_selected.options.length-1;i>=0;i--) {
			if (selected != "") {
				selected += ",";
			}
			selected += form.users_selected.options[i].value;
		}
		form.selected_user_values.value = selected;
	}
	return result;
}

function check_cost_centre_form(form) {
	var selected = "";
	var result   = check_cost_centre_details(form);

	if (result == true) {
		for (i=form.users_selected.options.length-1;i>=0;i--) {
			if (selected != "") {
				selected += ",";
			}
			selected += form.users_selected.options[i].value;
		}
		form.selected_user_values.value = selected;
	}
	return result;
}

function check_restriction_list_form(form) {
	var selected = "";
	var result   = check_restriction_list_details(form);

	if (result == true) {
		for (i=form.users_selected.options.length-1;i>=0;i--) {
			if (selected != "") {
				selected += ",";
			}
			selected += form.users_selected.options[i].value;
		}
		form.selected_user_values.value = selected;
	}
	return result;
}

function check_user_details_form(form) {

	var selected = "";
	for (i=form.departments_selected.options.length-1;i>=0;i--) {
		if (selected != "") {
			selected += ",";
		}
		selected += form.departments_selected.options[i].value;
	}
	form.departments_selected_values.value = selected;

	var selected = "";
	for (i=form.cost_centres_selected.options.length-1;i>=0;i--) {
		if (selected != "") {
			selected += ",";
		}
		selected += form.cost_centres_selected.options[i].value;
	}
	form.cost_centres_selected_values.value = selected;

	var selected = "";
	for (i=form.delivery_addresses_selected.options.length-1;i>=0;i--) {
		if (selected != "") {
			selected += ",";
		}
		selected += form.delivery_addresses_selected.options[i].value;
	}
	form.delivery_address_selected_values.value = selected;

	var selected = "";
	for (i=form.contracts_selected.options.length-1;i>=0;i--) {
		if (selected != "") {
			selected += ",";
		}
		selected += form.contracts_selected.options[i].value;
	}
	form.contracts_selected_values.value = selected;

	var selected = "";
	for (i=form.product_catalogues_selected.options.length-1;i>=0;i--) {
		if (selected != "") {
			selected += ",";
		}
		selected += form.product_catalogues_selected.options[i].value;
	}
	form.product_catalogues_selected_values.value = selected;

	var selected = "";
	for (i=form.restriction_lists_selected.options.length-1;i>=0;i--) {
		if (selected != "") {
			selected += ",";
		}
		selected += form.restriction_lists_selected.options[i].value;
	}
	form.restriction_lists_selected_values.value = selected;

	var selected = "";
	var result   = check_account_user_details(form);

	return result;
}


// Takes the source element and checks to see if we need to enable or disable
// the associated action drop down.
function checkActions( source, action_id, required_if_enabled ) {

    validation = document.getElementById( action_id );

    if ( ( source.value != '0' ) &&
       ( source.value != '' ) ) {

        validation.disabled = false;

        if ( required_if_enabled == true ) {

            validation.className = 'inputfield_required';

        }

    } else {

        validation.disabled = true;

        if ( validation.options ) {

            validation.options[0].selected = true;

        } else {

            validation.value = '0';

        }

        validation.className = 'inputfield'

    }

}

function validate_favourites( form )
{

    form = $( form );

	var error = 0;
	var error_message = "PLEASE REVIEW AND COMPLETE THE FOLLOWING\n\n";

	if ( ( ( ( $defined( form.customer_favourite_products_folder_id ) ) &&
	         ( $( form.customer_favourite_products_folder_id ).value.trim( ) == '' ) ) ||
	       ( !$defined( form.customer_favourite_products_folder_id ) ) ) &&
	     ( $( form.customer_favourite_products_new_folder_name ).value.trim( ) == '' ) )
    {
		error_message = error_message + "* Select or create favourites folder to use\n";
		error = 1;
	}

	if (error == 1) {
		alert(error_message);
		return false;
	} else {
		return true;
	}

}

function submit_form( form ) {

    // Change this to call a function that will reload the parent page and hide the dialog
    form = $( form );
    submit_via_ajax( form, null, vstall_dialog_hide, false );

}


function mini_quick_order_add(form) {
	var error = 0;
	var error_message = "PLEASE REVIEW AND COMPLETE THE FOLLOWING\n\n";

	if(form.qo_product_primary_code.value.trim() == '') {
		error_message = error_message + "* Product Code\n";
		error = 1;
	}
	if (error == 1) {
		alert(error_message);
		return false;
	} else {
		return true;
	}
}

/**
 * This function mades an AJAX call to vstall to add a product to a restriction
 * list. It assumes that vstall is going to return the complete data grid for
 * this back to it can replace the current one with it.
 *
 **/
function restriction_add_product( eprocurement_account_restriction_list_id, product_id ) {

    add_product = new Ajax( '/account/restriction_list_product_add/' +
                            eprocurement_account_restriction_list_id + '/' +
                            product_id,
                            { method: 'get',
                              onComplete: vstall_dialog_hide,
                              update: $( 'content' ) } );
    add_product.request( );

}

/**
 * Replaces the background image of an element with one run through a Microsoft
 * proprietary filter to make transparancy work in IE6
 **/
function fix_ie6_background_png_transparancy( element )
{

    if ( $defined( element ) )
    {

        var bgImage = element.getStyle( 'background-image' );
        bgImage = bgImage.substring( 5, bgImage.length - 2 );

        if ( bgImage.substring( bgImage.length - 3 ).toUpperCase( ) == 'PNG' )
        {

            element.setStyles( {
                background: 'none',
                filter: 'progid:DXImageTransform.Microsoft.AlphaImageLoader(src=\'' + bgImage + '\', sizingMethod=\'crop\');'
            });

        }

    }

}

function delete_from_basket( e ) {
    e = new Event( e );
    e.stop( );

    var link = $( e.target );

    if ( link.get('tag') != 'a' )
    {

        link = link.getParent( );

    }

    var ajax = new Request.HTML( {
    	url: link.getProperty( 'href' ), 
        headers: {
            'Accept': 'application/xml'
        },
        onComplete: function( ) {
        	
            update_basket_links( );

        },
        update: 'mini_basket'
    } ).send();
}

function submit_via_ajax( form, element_to_update, complete_function, insert_feedback )
{

    var coords = form.getCoordinates( );

    if (form.get('rel') == 'orderpad') {
    	var status_styles = {
                'height': coords['height'],
                'line-height': coords['height']
        };
    } else {
    	var status_styles = {
            'position': 'absolute',
            'left': '0px',
            'top': '0px',
            'height': coords['height'],
            'line-height': coords['height'],
            'width': coords['width']
        };
    }

    var status = new Element( 'div', {
        'class': 'basket_status',
        'events': {
        	'custom_event': function() {
                new Fx.Morph( this, {
	                duration: 1000,
	                onStart: function () {
        	        	if (insert_feedback == true) {
        	    	        $(document.body).getElements('.basket_feedback').each(function (item) { item.destroy()});
        	        		var basket_feedback = new Element( 'div', {	'class': 'basket_feedback'});        	        	
        	        		new Element( 'h5', {'text': 'Added to basket!'}).injectInside(basket_feedback);            	        
        	        		new Element( 'a', {'text': 'View Basket','href': '/shopping/basket_view'}).injectInside(basket_feedback);
        	        		new Element( 'a', {'text': 'Checkout','href': '/process_order'}).injectInside(basket_feedback);        	        
        	        		basket_feedback.injectAfter(form);
        	        	}
                	},
    	            onComplete: function( ) {
        	            status.destroy( );
            	        form.setStyle( 'position', 'static' );
                     }
	            } ).start( {
    	            'opacity': 0
        	    } );
        	}
        },
        'styles': status_styles
    } );

    var loader = 'loader_medium.gif';

    if ( coords['height'] < 50 )
    {

        loader = 'loader_small.gif';

    }
    else if ( coords['height'] > 75 )
    {
        loader = 'loader_large.gif';
    }

    new Element( 'img', {
            'src': '/images/' + loader,
            'alt': 'Loading, please wait'
    } ).injectInside( status );
    
    var ajax = new Request.HTML(  {
    	url: form.getProperty( 'action' ),
    	method: 'post',
        data: form,
        headers: {
            'Accept': 'application/xml'
        },
        onComplete: function( ) {

        	status.fireEvent('custom_event',{},500);
            complete_function( );

        },
        onRequest: function( ) {

	        form.setStyle( 'position', 'relative' );
            status.injectInside( form );

        },
        update: element_to_update
    } );

    ajax.get( );

}

function update_basket_links( )
{

    var basket_delete_links = $$( '.qv-del' );
    basket_delete_links.removeEvents( 'click' );
    basket_delete_links.addEvent( 'click', delete_from_basket );

}


//This function will analyse the contents of the pricing form and will calculate the
//appropriate price shown next to the add to basket option this will show the actual
//price of all good being added rather than the individual costs elements
function dynamic_pricing_calc_css(form, $currency_symbol)
{
	// start by working out wether or not we are working with a single item or
	// wether there are multiple options we can check to see if a control is an array
	var total_cost = 0;
	var total_discount = 0;
	var total_vat = 0;
	var quantity = 0;
	var unit_cost = 0;
	var line_cost = 0;

	// This is a global variable defined in core_system.js and can be used to alert the user when they are about
	// to navigate away before saving / commiting any changes they have made
	user_changes = true;

	// Check for no-option standard product pricing
	if (form.product_quantity) {		
		// This is just a straight product pricing option
		total_cost = (form.product_quantity.value * form.product_cost.value);

		// Check to see if there are any QPB values for this item
		var quantity = form.product_quantity.value;
		var quantity_name = 'qpb_quantity_'  + form.primary_product_id.value;
		var costs_name = 'qpb_value_'  + form.product_id.value;
		var div_name = 'item_price_'  + form.product_id.value;
		var item_price_div = document.getElementById(div_name);
		var break_quantities = document.getElementsByName(quantity_name);
		var break_values = document.getElementsByName(costs_name);

		// Handle both multiple and single breaks
		form.product_cost.value = form.product_original_cost.value;
		if (break_quantities.length) {
			for (var i=0; i < break_quantities.length; i++) {
				var check_quantity = break_quantities[i].value;
				if (parseInt(quantity) >= parseInt(check_quantity)) {
					form.product_cost.value = break_values[i].value;
				}
			}
		} else {
			// Single break value
			if (quantity >= break_quantities.value) {
				form.product_cost.value = break_values.value;
			}
		}

		// Update the item price if possible
		if (item_price_div) {
			var item_value = form.product_cost.value;
			item_price_div.innerHTML = $currency_symbol + parseFloat(item_value).toFixed(2);
		}

		// Now we can calculate the line total
		total_cost = quantity * form.product_cost.value;
		total_discount = quantity * (form.product_standard_price.value - form.product_cost.value);
		if (total_discount < 0) total_discount = 0;
	} else {		
		// Check to see if there are multiple options available
		quantities = document.getElementsByName('variation_quantity[]');
		product_ids = document.getElementsByName('variation_product_id[]');
		product_costs = document.getElementsByName('variation_cost[]');
		product_vat_rates = document.getElementsByName('variation_vat_rate[]');
		product_original_costs = document.getElementsByName('variation_original_cost[]');
		standard_costs = document.getElementsByName('variation_standard_price[]');
		if (quantities.length) {			
			for (var n=0; n < quantities.length; n++) {
				// Check to see if there are any QPB values for this item
				var quantity = quantities[n].value;
				var product_id = product_ids[n].value;
				var quantity_name = 'qpb_quantity_'  + product_id + '[]';
				var costs_name = 'qpb_value_'  + product_id + '[]';
				var div_name = 'item_price_'  + product_id;
				var item_price_div = document.getElementById(div_name);
				var break_quantities = document.getElementsByName(quantity_name);
				var break_values = document.getElementsByName(costs_name);
				var product_vat_rate = product_vat_rates[n].value;				

				// Handle both multiple and single breaks
				product_costs[n].value = product_original_costs[n].value;
				if (break_quantities.length) {
					for (var i=0; i < break_quantities.length; i++) {
						var check_quantity = break_quantities[i].value;
						if (parseInt(quantity) >= parseInt(check_quantity)) {
							product_costs[n].value = break_values[i].value;
						}
					}
				} else {
					// Single break value
					if (quantity >= break_quantities.value) {
						product_costs[n].value = break_values.value;
					}
				}

				// Update the item price if possible
				if (item_price_div) {
					var item_value = product_costs[n].value;
					item_price_div.innerHTML = $currency_symbol + parseFloat(item_value).toFixed(2);
				}

				// Now we can calculate the line total
				line_cost = quantity * product_costs[n].value;
				line_discount = quantity * (standard_costs[n].value - product_costs[n].value);
				if (line_discount < 0) line_discount = 0;
				total_cost = total_cost + line_cost;
				total_discount = total_discount + line_discount;	
				total_vat = total_vat + (line_cost * (product_vat_rate/100))							
			}						
		} else {			
			// Check to see if there are any QPB values for this item
			var quantity = form.variation_quantity.value;
			var quantity_name = 'qpb_quantity_'  + form.variation_product_id.value + '[]';
			var costs_name = 'qpb_value_'  + form.variation_product_id.value + '[]';
			var div_name = 'item_price_'  + form.variation_product_id.value;
			var item_price_div = document.getElementById(div_name);
			var break_quantities = document.getElementsByName(quantity_name);
			var break_values = document.getElementsByName(costs_name);			

			// Handle both multiple and single breaks
			form.variation_cost.value = form.variation_orginal_cost.value;
			if (break_quantities.length) {
				for (var i=0; i < break_quantities.length; i++) {
					var check_quantity = break_quantities[i].value;
					if (parseInt(quantity) >= parseInt(check_quantity)) {
						form.variation_cost.value = break_values[i].value;
					}
				}
			} else {
				// Single break value
				if (quantity >= break_quantities.value) {
					form.variation_cost.value = break_values.value;
				}
			}

			// Update the item price if possible
			if (item_price_div) {
				var item_value = form.variation_cost.value;
				item_price_div.innerHTML = $currency_symbol + parseFloat(item_value).toFixed(2);
			}

			total_cost = (form.variation_quantity.value * form.variation_cost.value);
			total_vat = (form.variation_quantity.value * form.variation_cost.value * (form.variation_vat_rate/100));			
			total_discount = form.variation_quantity.value * (form.variation_standard_price.value - form.variation_cost.value);
		}
	}

	// Sanity check the discount
	if (total_discount < 0) total_discount = 0;

	// Check to make sure we can find the element on the form we need to write back to
	discount_div = document.getElementById('dynamic_cost_calc_discount');
	output_div = document.getElementById('dynamic_cost_calc_total');
	inc_vat_div = document.getElementById('dynamic_cost_calc_total_inc_vat');
	if (output_div) {
		output_div.innerHTML = 'Cost: ' + formatCurrency(total_cost, $currency_symbol);
	}
	if (discount_div) {
	    if (total_discount > 0.01) discount_div.style.display = '';
	    else discount_div.style.display = 'none';
		discount_div.innerHTML = 'Online Saving: ' + formatCurrency(total_discount, $currency_symbol);
	}
	if(inc_vat_div) {
		inc_vat_div.innerHTML = '(' + formatCurrency(total_vat + total_cost, $currency_symbol) + ' inc. VAT)';
	}
}


//This function will analyse the contents of the pricing form and will calculate the
//appropriate price shown next to the add to basket option this will show the actual
//price of all good being added rather than the individual costs elements
function dynamic_pricing_calc(form, $currency_symbol)
{
	// start by working out wether or not we are working with a single item or
	// wether there are multiple options we can check to see if a control is an array
	var total_cost = 0;
	var total_discount = 0;
	var quantity = 0;
	var unit_cost = 0;
	var line_cost = 0;

	// This is a global variable defined in core_system.js and can be used to alert the user when they are about
	// to navigate away before saving / commiting any changes they have made
	user_changes = true;

	// Check for no-option standard product pricing
	if (form.product_quantity) {
		// This is just a straight product pricing option
		total_cost = (form.product_quantity.value * form.product_cost.value);

		// Check to see if there are any QPB values for this item
		var quantity = form.product_quantity.value;
		var quantity_name = 'qpb_quantity_'  + form.primary_product_id.value;
		var costs_name = 'qpb_value_'  + form.product_id.value;
		var div_name = 'item_price_'  + form.product_id.value;
		var item_price_div = document.getElementById(div_name);
		var break_quantities = document.getElementsByName(quantity_name);
		var break_values = document.getElementsByName(costs_name);

		// Handle both multiple and single breaks
		form.product_cost.value = form.product_original_cost.value;
		if (break_quantities.length) {
			for (var i=0; i < break_quantities.length; i++) {
				var check_quantity = break_quantities[i].value;
				if (parseInt(quantity) >= parseInt(check_quantity)) {
					form.product_cost.value = break_values[i].value;
				}
			}
		} else {
			// Single break value
			if (quantity >= break_quantities.value) {
				form.product_cost.value = break_values.value;
			}
		}

		// Update the item price if possible
		if (item_price_div) {
			var item_value = form.product_cost.value;
			item_price_div.innerHTML = $currency_symbol + parseFloat(item_value).toFixed(2);
		}

		// Now we can calculate the line total
		total_cost = quantity * form.product_cost.value;
		total_discount = quantity * (form.product_standard_price.value - form.product_cost.value);
		if (total_discount < 0) total_discount = 0;
	} else {
		// Check to see if there are multiple options available
		if (form.variation_quantity.length) {
			for (var n=0; n < form.variation_quantity.length; n++) {
				// Check to see if there are any QPB values for this item
				var quantity = form.variation_quantity[n].value;
				var quantity_name = 'qpb_quantity_'  + form.variation_product_id[n].value + '[]';
				var costs_name = 'qpb_value_'  + form.variation_product_id[n].value + '[]';
				var div_name = 'item_price_'  + form.variation_product_id[n].value;
				var item_price_div = document.getElementById(div_name);
				var break_quantities = document.getElementsByName(quantity_name);
				var break_values = document.getElementsByName(costs_name);

				// Handle both multiple and single breaks
				form.variation_cost[n].value = form.variation_orginal_cost[n].value;
				if (break_quantities.length) {
					for (var i=0; i < break_quantities.length; i++) {
						var check_quantity = break_quantities[i].value;
						if (parseInt(quantity) >= parseInt(check_quantity)) {
							form.variation_cost[n].value = break_values[i].value;
						}
					}
				} else {
					// Single break value
					if (quantity >= break_quantities.value) {
						form.variation_cost[n].value = break_values.value;
					}
				}

				// Update the item price if possible
				if (item_price_div) {
					var item_value = form.variation_cost[n].value;
					item_price_div.innerHTML = $currency_symbol + parseFloat(item_value).toFixed(2);
				}

				// Now we can calculate the line total
				line_cost = quantity * form.variation_cost[n].value;
				line_discount = quantity * (form.variation_standard_price[n].value - form.variation_cost[n].value);
				if (line_discount < 0) line_discount = 0;
				total_cost = total_cost + line_cost;
				total_discount = total_discount + line_discount;
			}
		} else {
			// Check to see if there are any QPB values for this item
			var quantity = form.variation_quantity.value;
			var quantity_name = 'qpb_quantity_'  + form.variation_product_id.value + '[]';
			var costs_name = 'qpb_value_'  + form.variation_product_id.value + '[]';
			var div_name = 'item_price_'  + form.variation_product_id.value;
			var item_price_div = document.getElementById(div_name);
			var break_quantities = document.getElementsByName(quantity_name);
			var break_values = document.getElementsByName(costs_name);

			// Handle both multiple and single breaks
			form.variation_cost.value = form.variation_orginal_cost.value;
			if (break_quantities.length) {
				for (var i=0; i < break_quantities.length; i++) {
					var check_quantity = break_quantities[i].value;
					if (parseInt(quantity) >= parseInt(check_quantity)) {
						form.variation_cost.value = break_values[i].value;
					}
				}
			} else {
				// Single break value
				if (quantity >= break_quantities.value) {
					form.variation_cost.value = break_values.value;
				}
			}

			// Update the item price if possible
			if (item_price_div) {
				var item_value = form.variation_cost.value;
				item_price_div.innerHTML = $currency_symbol + parseFloat(item_value).toFixed(2);
			}

			total_cost = (form.variation_quantity.value * form.variation_cost.value);
			total_discount = form.variation_quantity.value * (form.variation_standard_price.value - form.variation_cost.value);
		}
	}

	// Sanity check the discount
	if (total_discount < 0) total_discount = 0;

	// Check to make sure we can find the element on the form we need to write back to
	discount_div = document.getElementById('dynamic_cost_calc_discount');
	output_div = document.getElementById('dynamic_cost_calc_total');
	if (output_div) {
		output_div.innerHTML = 'Cost: ' + formatCurrency(total_cost, $currency_symbol);
	}
	if (discount_div) {
		discount_div.innerHTML = 'Online Saving: ' + formatCurrency(total_discount, $currency_symbol);
	}
}

//This function will format the specified value into a suitable format for the screen
function formatCurrency(num, $currency_symbol)
{
	// Clean up the number string
	num = num.toString().replace(/\|\,/g,'');
	// Default to zero if invalid
	if(isNaN(num)) num = "0";
	sign = (num == (num = Math.abs(num)));
	num = Math.floor(num*100+0.50000000001);
	cents = num%100;
	num = Math.floor(num/100).toString();
	if(cents<10) cents = "0" + cents;
	for (var i = 0; i < Math.floor((num.length-(1+i))/3); i++)
	num = num.substring(0,num.length-(4*i+3))+','+
	num.substring(num.length-(4*i+3));
	return (((sign)?'':'-') + $currency_symbol + num + '.' + cents);
}


//This function will validate a standard pricing panel to ensure all of the
//relevant information has been provided to ensure sensible data is sent to
//the server in the future
function product_add_validation(form)
{

	// Initialise the variables
	var error = 0; var error_message = "PLEASE COMPLETE THE FOLLOWING\n\n";
	var quantity = 0;

	// Check for no-option standard product pricing
	if (form.product_quantity) {
		// This is just a straight product pricing option
		quantity = form.product_quantity.value;
	} else {

	    quantities = $( form ).getElements( 'input[name^=variation_quantity]' );
	    quantities.each( function( variation_quantity ) {

	        quantity = quantity + variation_quantity.value;

	    });

	}

	// Make sure we have a quantity at this point
	if (quantity <= 0) {
		error = 1;
		error_message = "Please specify a valid quantity";
	}

	// Check to make sure we can continue
	if (error == 1) {
		alert(error_message);
		return false;
	} else {
		return true;
	}
}


//-----------------------------------------------------------------------------------------
//The following functions are used to control navigation around the system and can be used 
//to ensure the user has saved data to the database before they navigate away from a page
//this will ensure the system is user friendly. All links within the system should be 
//wrapped with these function calls
//-----------------------------------------------------------------------------------------
//Initialise the site wide data changed flag, this will be used by screen to warn the user 
//where they attempt to navigate to a URL when changes to a page have been made 
var data_changed = false;

//This function will be used site wide linked to the change event on all edit controls this 
//will set the data changed flag which will then be used in navigation checks
function changes() {
	data_changed = true;
}

//This common function is used site wide to goto to a URL with or without params this will check 
//the data changed flag and get the user to confirm the navigation before moving off the page.
function goto_url(url) {
	if (check_navigate()) { 
		//We need to check to see if we are in an IFRAME if this is the case we need to set the 
		//document location property for the parent document and not the IFRAME document
		window.parent.document.location.href = url;
		data_changed = false;
	}
}

//This function is used to allow the user to navigate through pages of a datagrid within the system 
//this will ensure the status of the page is captured which will allow us to update the status 
//of the check boxes as the user navigated through the pages. Javascript cookies are used to pass 
//this information to PHP, PHP is then responsible for setting the initial status of the controls
function datagrid_goto_url(url) {
	window.parent.document.location.href = url;
	data_changed = false;
}

//This function is used site wide to check the state of the data changed flag where the user has 
//changed anything they will need to confirm the changes.
function check_navigate() {
	//Check the data flag
	if (data_changed == true) {
		// Something has changed get the user to confirm the changes
		if (confirm('Are you sure you want to navigate away from the current page? if you click OK you will loose the changes you have made')) return true;
		else return false;
	}
	else return true;
}

//-----------------------------------------------------------------------------------------


//-----------------------------------------------------------------------------------------
//The following core functions are are low level checks used within the form validation 
//code within the system, this is part of the system level HTML helper classes
//-----------------------------------------------------------------------------------------

//This function will create a trim function on the string class which we can 
//use to ensure the customer has provided data in a relevant field
String.prototype.trim = function() {
return this.replace(/^\s*|\s*$/g, "")
}

//This function will do a numeric check on each char that is input, as its inputted
//If it finds a none numeric char it strips it straight away, ((e) is event)
//this will also validate to ensure the value is a valid integer
function keyPress_float(e, control, decimals) {   
	// Get hold of the key press event
	var key = (window.event) ? event.keyCode : e.which;   
	if (window.event) key = event.keyCode   
	else key = e.which   
	
	// backspace (8) 
	if (key == 8 || key == 0) return;   

	// returns for form submission
	if (key == 10 || key == 13) return;   

//if dot (46) we need to check there is only one
	var decimal_pos = control.value.indexOf(".");
	if (key == 46 && decimal_pos == -1) return;
	
	// We need to enforce the decimals 
	if (decimal_pos > -1) {
		var decimal_counter = control.value.length - decimal_pos - 1;
		if (decimal_counter < decimals) {
			if (key > 47 && key < 58) return;
		}
	} else {
		// Was key that was pressed a numeric character (0-9) or backspace (8) 
		if (key > 47 && key < 58) return; // if so, do nothing   else // otherwise, discard character    
	}

	// Squash the keypress under IE and firefox
	if (window.event) window.event.returnValue = null;     
	else e.preventDefault(); 
}

//This function will do a numeric check on each char that is input, as its inputted
//If it finds a none numeric char it strips it straight away, ((e) is event)
//this will also validate to ensure the value is a valid integer
function keyPress_integer(e, control) {   
	// Get hold of the key press event
	var key = (window.event) ? event.keyCode : e.which;   
	if (window.event) key = event.keyCode   
	else key = e.which   
	
	// returns for form submission
	if (key == 10 || key == 13) return;   
	// Was key that was pressed a numeric character (0-9) or backspace (8) 
	if ( key > 47 && key < 58 || key == 8 || key == 0) return; // if so, do nothing   else // otherwise, discard character    
	
	// Squash the keypress under IE and firefox
	if (window.event) window.event.returnValue = null;     
	else e.preventDefault(); 
}

function keyPress_sem_path(e, control) {
	// Get hold of the key press event
	var key = (window.event) ? event.keyCode : e.which;   
	if (window.event) key = event.keyCode   
	else key = e.which   
	
	// returns for form submission
	if (key == 10 || key == 13) return;   
	// Was key that was pressed a numeric character (0-9) or backspace (8) 
	if (key > 47 && key < 58 || key == 8 || key == 0) return; // if so, do nothing  
	// Lowercase a-z and uppercase A-Z
	if (key >= 65 && key <= 90 || key >= 97 && key <= 122) return; // if so, do nothing  
 // Sepcial keyword characters underscore (95) or forward slash (47) 
	if (key == 95 || key == 47) return; // if so, do nothing
	
	// Squash the keypress under IE and firefox
	if (window.event) window.event.returnValue = null;     
	else e.preventDefault(); 
}

function keyPress_sem_keyword(e, control) {
	// Get hold of the key press event
	var key = (window.event) ? event.keyCode : e.which;   
	if (window.event) key = event.keyCode   
	else key = e.which   
	
	// returns for form submission
	if (key == 10 || key == 13) return;   
	// Was key that was pressed a numeric character (0-9) or backspace (8) underscore (95)
	if (key > 47 && key < 58 || key == 8 || key == 0 || key == 95) return; // if so, do nothing  
	// Lowercase a-z and uppercase A-Z
	if (key >= 65 && key <= 90 || key >= 97 && key <= 122) return; // if so, do nothing  

	// Squash the keypress under IE and firefox
	if (window.event) window.event.returnValue = null;     
	else e.preventDefault(); 
}

//This function will check the string provided is in the correct format
//This will be used by all of the validation classes used within the system
function isEmail(argvalue) 
{

if (argvalue.indexOf(" ") != -1) return false;
else if (argvalue.indexOf("@") == -1) return false;
else if (argvalue.indexOf("@") == 0) return false;
else if (argvalue.indexOf("@") == (argvalue.length-1)) return false;

arrayString = argvalue.split("@"); 
// var retSize = customSplit(argvalue, "@", "arrayString");

if (arrayString[1].indexOf(".") == -1)
 return false;
else if (arrayString[1].indexOf(".") == 0)
 return false;
else if (arrayString[1].charAt(arrayString[1].length-1) == ".") {
 return false;
}

return true;
}

//This functio checks the pattern of the URL
//to ensure it's valid
function isURL(domain_name) 
{
	var regexp = /(ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/
	return regexp.test(domain_name);
}

//check for valid numeric strings	
function isNumeric(string_value) {
	var ValidChars = "0123456789";
	var Char;
	var Result = true;

	if (string_value.length == 0) return false;

	//  test strString consists of valid characters listed above
	for (i = 0; i < string_value.length && Result == true; i++) {
		Char = string_value.charAt(i);
		if (ValidChars.indexOf(Char) == -1) {
			Result = false;
			break;
		}
	}
	return Result;
}


function ValidUKPostCode(PostCode) {
	//validate to the following
	//(GIR 0AA|[A-PR-UWYZ]([0-9]{1,2}|([A-HK-Y][0-9]|[A-HK-Y][0-9]([0-9]|[ABEHMNPRV-Y]))|[0-9][A-HJKS-UW]) [0-9][ABD-HJLNP-UW-Z]{2})
	//
	//(GIR 0AA|
	// [A-PR-UWYZ]
	// (
	//   [0-9]{1,2}
	//   |
	//   (
	//     [A-HK-Y][0-9]
	//     |
	//     [A-HK-Y][0-9]
	//     (
	//       [0-9]
	//       |
	//       [ABEHMNPRV-Y]
	//     )
	//   )
	//   |
	//   [0-9][A-HJKS-UW]
	// )
	// [0-9][ABD-HJLNP-UW-Z]{2}
	//)
	//
	//http://postcode.royalmail.com
	//
	
	//declare the mootools arrays
	var Numeric = ['0','1','2','3','4','5','6','7','8','9'];
	var Alpha = ['A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'];
	var InAlpha = ['A','B','D','E','F','G','H','J','L','N','P','Q','R','S','T','U','W','X','Y','Z'];
	var OutAlpha1 = ['A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','R','S','T','U','W','Y','Z'];
	var OutAlpha2 = ['A','B','C','D','E','F','G','H','J','K','S','T','U','W'];	
	var OutAlpha3 = ['A','B','C','D','E','F','G','H','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y'];
	var Alpha = ['A','B','E','H','M','N','P','R','V','W','X','Y'];
	var Alphanumeric = ['A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z','0','1','2','3','4','5','6','7','8','9'];

	// convert all alphas to upper case	
	var TestCode = PostCode.toUpperCase();

	// get the length
	var PostcodeArray = [];
    var charcount = 0; 
	for (i=0; i<TestCode.length; i++) {
		if (Alphanumeric.indexOf(TestCode.charAt(i)) > -1) {
			PostcodeArray.include(TestCode.charAt(i));
			charcount++;
		}
	}
	
	// Length Checks
	if (charcount > 7) return 'Postcode too long';
	if (charcount < 5) return 'Postcode too short';
	
	if (InAlpha.indexOf(PostcodeArray[PostcodeArray.length-1]) == -1) return 'Last character should be in [ABD-HJLNP-UW-Z] - ' + PostcodeArray[PostcodeArray.length-1];
	if (InAlpha.indexOf(PostcodeArray[PostcodeArray.length-2]) == -1) return 'Second to last character should be in [ABD-HJLNP-UW-Z]';
	if (Numeric.indexOf(PostcodeArray[PostcodeArray.length-3]) == -1) return 'Third from last character should be numeric';
	
	var TempArray = []; 
	PostcodeArray.each(function (item, index) {
		if (index == 3) TempArray.include(' ');
		TempArray.include(item);
	});
	var PostcodeArray = [];
	TempArray.each(function (item, index) { PostcodeArray.include(item); });
	
	// check the Outward Code
	if (OutAlpha1.indexOf(PostcodeArray[0]) > -1) {
		if (Numeric.indexOf(PostcodeArray[1]) > -1) {
			// ok so far - now we could branch
			if (PostcodeArray[2] == ' ') { 
				// valid A9 9AA case
				return true; 
			} else {
				if (Numeric.indexOf(PostcodeArray[2]) > -1) {
					if (PostcodeArray[3] == ' ') {
						// valid A99 9AA case
						return true; 
					} else {
						return 'The fourth character should be a space';
					}
				} else {
					if (OutAlpha2.indexOf(PostcodeArray[2]) > -1) {
						if (PostcodeArray[3] == ' ') {
							// value A9A 9AA case
							return true;
						} else {
							return 'The fourth character should be a space';
						}
					} else {
						return 'The third character should be in [0-9A-HJKS-UW]';
					}
				}				
			}
		} else 	{			
			if (OutAlpha3.indexOf(PostcodeArray[1]) > -1) {
				if (Numeric.indexOf(PostcodeArray[2]) > -1) {
					if (PostcodeArray[3] == ' ') {
						// value AA9 9AA case
						return true;
					} else if (Numeric.indexOf(PostcodeArray[3]) > -1) {
						if (PostcodeArray[4] == ' ') {
							// value AA99 9AA case
							return true;
						} else {
							return 'The fifth character should be a space';
						}
					} else if (OutAlpha4.indexOf(PostcodeArray[3]) > -1) {
						if (PostcodeArray[4] == ' ') {
							// value AA9A 9AA case
							return true;
						} else {
							return 'The fifth character should be a space';
						}
					} else {
						return 'The fourth character should be in [0-9ABEHMNPRV-Y]';
					}
				}
			} else {
				return 'The second character should be in [0-9A-HK-Y]';
			}
		}
	} else {	
		return 'The first character should be in [A-PR-UWYZ]';
	}
}
