// JavaScript Document

function preload_image( img )
{
	var preload=new Image();
	preload.src="(" + img + ")";
}

preload_image( "/assets/images/loading.gif" ) ;
preload_image( "/assets/images/updating.gif" ) ;
preload_image( "/assets/images/loading-dark.gif" ) ;
preload_image( "/assets/images/updating-dark.gif" ) ;
preload_image( "/assets/images/ajax-loader.gif" ) ;

// Current Page Reference
// copyright Stephen Chapman, 1st Jan 2005
// you may copy this function but please keep the copyright notice with it
function getURL(uri) 
{
	uri.dir = location.href.substring(0, location.href.lastIndexOf('\/'));
	uri.dom = uri.dir.substring(uri.dir.indexOf('.')+1); 
	if (uri.dom.substr(0,7) == 'http:\/\/') uri.dom = uri.dom.substr(7);
	uri.path = ''; 
	var pos = uri.dom.indexOf('\/'); 
	if (pos > -1) {uri.path = uri.dom.substr(pos+1); uri.dom = uri.dom.substr(0,pos);}
	uri.page = location.href.substring(uri.dir.length+1, location.href.length+1);
	pos = uri.page.indexOf('?');
	if (pos > -1) {uri.page = uri.page.substring(0, pos);}
	pos = uri.page.indexOf('#');
	if (pos > -1) {uri.page = uri.page.substring(0, pos);}
	uri.ext = ''; 
	pos = uri.page.indexOf('.');
	if (pos > -1) {uri.ext =uri.page.substring(pos+1); 
	uri.page = uri.page.substr(0,pos);}
	uri.file = uri.page;
	if (uri.ext != '') uri.file += '.' + uri.ext;
	if (uri.file == '') uri.page = 'index';
	uri.args = location.search.substr(1).split("?");
	return uri;
}

var uri = new Object();
getURL(uri);

var eventX = 0 ;
var eventY = 0 ;
Event.observe(document, 'mousedown', getcords);

function getcords(e)
{
	eventX = Event.pointerX(e);
	eventY = Event.pointerY(e);
//	for testing put the mouse cords in a div
//	$('infomercial').innerHTML = 'mouseX:' + eventX + '-- mouseY:' + eventY;
}

function displayEmail() {
	
	// Generic email hiding routine from spam bots

	// The function takes 3 optional parameters
	// 1 - The email prefix (e.g. "sales@", "myname@", etc). This is defaulted to "info" by the function if not supplied
	// 2 - The text to display on the page (e.g. "myname"). If omitted, the full email address is shown
	// 3 - The domain. This is defaulted in the function and is not usually supplied unless you want to display different domains
	
	prefix	= "info" ;
//	url		= "tecsa.org.uk" ;
	url		= uri.dom ;
	
	// How many arguments passed?
	numargs = arguments.length ;

	if ( numargs >= 1 ) prefix 	= arguments[0] ;	// Set the new prefix to the first argument
	if ( numargs >= 2 ) text 	= arguments[1] ;	// Set the new text to the second argument
	if ( numargs >= 3 ) url 	= arguments[2] ;	// Set the new domain to the last argument
	if ( numargs >= 4 ) useimg 	= arguments[3] ;	// Are we using an image based link?

	// Build the default text to be displayed - only if not supplied as an argument
	if ( numargs <= 1 ) text	= prefix + "@" + url ;

	// Build the link
	mylink = "<a href='mailto:" + prefix + "@" + url + "'>" + text + "</a>" ;
	if ( numargs >= 4 )
	{
		if ( useimg == 1 )
		{
			mylink = "<a href='mailto:" + prefix + "@" + url + "'><img src='/assets/images/icons/email.png' alt='Email " + text + "' title='Email " + text + "' border='0' align='absmiddle'></a>" ;
		}
	}
	
	// Output
	document.write( mylink ) ;
	
}

function toggle_div ( id )
{
	if (document.getElementById) { // DOM3 = IE5, NS6
		if (document.getElementById(id).style.display == "none" || document.getElementById(id).style.display == ""){
			document.getElementById(id).style.display = 'block';
			document.getElementById(id).style.visibility = 'visible';
		} else {
			document.getElementById(id).style.display = 'none';			
			document.getElementById(id).style.visibility = 'hidden';
		}	
	} else { 
		if (document.layers) {	
			if (document.id.display == "none" || document.id.display == ""){
				document.id.display = 'block';
				document.id.visibility = 'visible';
			} else {
				document.id.display = 'none';
				document.id.visibility = 'hidden';
			}
		} else {
			if (document.all.id.style.visibility == "none" || document.all.id.style.visibility == "" ) {
				document.all.id.style.display = 'block';
				document.all.id.style.visibility = 'visible';
			} else {
				document.all.id.style.display = 'none';
				document.all.id.style.visibility = 'hidden';
			}
		}
	}
}

function hide_div ( id )
{
	if (document.getElementById) { // DOM3 = IE5, NS6
		if ( !(document.getElementById(id).style.display == "none" || document.getElementById(id).style.display == "")){
			document.getElementById(id).style.display = 'none';			
			document.getElementById(id).style.visibility = 'hidden';
		}	
	} else { 
		if (document.layers) {	
			if (!(document.id.display == "none" || document.id.display == "")){
				document.id.display = 'none';
				document.id.visibility = 'hidden';
			}
		} else {
			if (!(document.all.id.style.visibility == "none" || document.all.id.style.visibility == "" )){
				document.all.id.style.display = 'none';
				document.all.id.style.visibility = 'hidden';
			}
		}
	}
}

function show_div ( id )
{
	if (document.getElementById) { // DOM3 = IE5, NS6
		if (document.getElementById(id).style.display == "none" || document.getElementById(id).style.display == ""){
			document.getElementById(id).style.display = 'block';
			document.getElementById(id).style.visibility = 'visible';
		} 	
	} else { 
		if (document.layers) {	
			if (document.id.display == "none" || document.id.display == ""){
				document.id.display = 'block';
				document.id.visibility = 'visible';
			}
		} else {
			if (document.all.id.style.visibility == "none" || document.all.id.style.visibility == "" )
			{
				document.all.id.style.display = 'block';
				document.all.id.style.visibility = 'visible';
			}
		}
	}
}

// =======================================================================
// AJAX Stuff
// =======================================================================

// =======================================================================
// ajax_preload_into( page, div )
// This function loads a given page (ie a PHP file under the /cms directory)
// into the DIV passed as the second parameter. Technically this could be 
// any page - HTML included.
// =======================================================================

function update_basket( category, parent, product, variant )
{
	close_divs();
	// Set up the URL of the page to be loaded
	var url = '/cms/core/ecube/basket/add-to-basket.php' ;
	var myAjax = new Ajax.Request( 
			url,
			{
				method: 'get',
				parameters: {cat: category, par: parent, prod: product, variant: variant},
				onComplete: processBasketUpdate
			}
		)
}

function update_wishlist( category, parent, product, variant )
{
	close_divs();
	// Set up the URL of the page to be loaded
	var url = '/cms/core/ecube/account/wishlist-add.php' ;
	var myAjax = new Ajax.Request( 
			url,
			{
				method: 'get',
				parameters: {cat: category, par: parent, prod: product, variant: variant},
				onComplete: processSaveResponsePublic
			}
		)
}

// =======================================================================
// ajaxInitialise( page, div, callback )
// This function loads a given page (ie a PHP file under the /cms directory)
// into the DIV passed as the second parameter. Technically this could be 
// any page - HTML included. The third parameter (optional) - callback - allows us to
// call javascript functions to operate on the content loaded in the DIV; the
// reason for this is that the called file cannot execute JavaScript code, and
// so we apply the JS code after the page has loaded
// =======================================================================

function ajaxInitialise( page, div )
{
	// We can optionally pass a CSS modification as a third parameter
	// As this facility was added mid-way through the application development it is easier
	// to accomdate the optional parameter by using the "arguments" properties rather than 
	// restrospectively mod all calls in the code!
	numargs = arguments.length ;
	if ( numargs >= 3 )
	{
		postcall = arguments[2] ;	// Set the style mods for the container
	}
	else
	{
		// Set the default
		postcall = "" ;
	}
	close_divs();

	// Set up the URL of the page to be loaded
	var url = '/cms/' + page ;
	show_div( div ) ;
	if ( div == 'cmsconsole' ) 
	{
		div = "consoleinner" ;
		inner = "<img src='/assets/images/loading.gif' border=0>" ;
	}
	if ( div == 'switch' ) 
	{
		div = "switchinner" ;
		inner = "<img src='/assets/images/ajax-loader.gif' border=0 align=absmiddle><img src='/assets/images/loading-dark.gif' border=0 align=absmiddle>" ;
	}
	$(div).update(inner) ;
	$(div).innerHTML ;
//	alert ( postcall ) ;
	if ( postcall == "" )
	{
		var myAjax = new Ajax.Updater( div, url ) ;
	}
	else
	{
		var myAjax = new Ajax.Updater( div, url, { onSuccess: setTimeout( postcall, 1000 ) } ) ;
//		var myAjax = new Ajax.Updater( div, url ) ;
	}
	window.location.href = '#pagetop' ;
}

// =======================================================================
// ajax_preload_into( page, div )
// This function loads a given page (ie a PHP file under the /cms directory)
// into the DIV passed as the second parameter. Technically this could be 
// any page - HTML included.
// =======================================================================

function ajax_preload_into( page, div )
{
	close_divs();
	// Set up the URL of the page to be loaded
	var url = '/cms/' + page ;
	show_div( div ) ;
	$(div).update("<img src='/assets/images/ajax-loader.gif' border=0 align=absmiddle><img src='/assets/images/loading-dark.gif' border=0 align=absmiddle>") ;
	$(div).innerHTML ;
	var myAjax = new Ajax.Updater( 
			div,
			url
	)
}

function ajax_preload_inner( page, div )
{

	// We can optionally pass a CSS modification as a third parameter
	// As this facility was added mid-way through the application development it is easier
	// to accomdate the optional parameter by using the "arguments" properties rather than 
	// restrospectively mod all calls in the code!
	numargs = arguments.length ;
	if ( numargs >= 3 )
	{
		modstyle = arguments[2] ;	// Set the style mods for the container
		// If the CSS "width" parameter is zero (ie spoofed or invalid) we set the default to 600
		if ( parseInt(modstyle) == 0 )
		{
			modstyle = 400 ;
		}
		
	}
	else
	{
		// Set the default
		numargs = 3 ;
		modstyle = 400 ;
	}

	close_divs();
	// Set up the URL of the page to be loaded
	var url = '/cms/' + page ;
	show_div( div ) ;
	$('switchinner').update("<img src='/assets/images/ajax-loader.gif' border=0 align=absmiddle><img src='/assets/images/loading-dark.gif' border=0 align=absmiddle>") ;
	$('switchinner').innerHTML ;
	var myAjax = new Ajax.Updater( 
			'switchinner',
			url
		)
	// If the CSS mod has been set
	if ( numargs >= 3 )
	{
		if ( modstyle == 100 ) $('switchinner').setStyle({width: '100px'}) ;
		if ( modstyle == 200 ) $('switchinner').setStyle({width: '200px'}) ;
		if ( modstyle == 300 ) $('switchinner').setStyle({width: '300px'}) ;
		if ( modstyle == 400 ) $('switchinner').setStyle({width: '400px'}) ;
		if ( modstyle == 500 ) $('switchinner').setStyle({width: '500px'}) ;
		if ( modstyle == 600 ) $('switchinner').setStyle({width: '600px'}) ;
		if ( modstyle == 700 ) $('switchinner').setStyle({width: '700px'}) ;
		if ( modstyle == 800 ) $('switchinner').setStyle({width: '800px'}) ;
	}
}

// =======================================================================
// ajax_background_job( page )
// This function executes a PHP (or other script) file in the background
// It is a method to call a script from the page without worrying about
// whether the script passes or fails
// =======================================================================

function ajax_background_job( page )
{
	// Set up the URL of the page to be loaded
	var url = '/cms/' + page ;
	var myAjax = new Ajax.Request( 
					url, 
					{
						method: 'get'
					}
				 )
}

function update_country ( country_id, region_id )
{

	page = "/core/ecube/basket/change-zone.php" ;
	
	// Set up the URL of the page to be loaded
	var url = '/cms/' + page ;
	var myAjax = new Ajax.Request( 
					url, 
					{
						method: 'get',
						parameters: {c: country_id, s: region_id},
						onComplete: check_country_update
					}
				 )
}

function check_country_update ( originalRequest )
{
	var reply = originalRequest.responseText;

	var response = reply.split("|") ;

	ajax_status 	= response[0] ;
	ajax_subdivision= response[1] ;
	ajax_html		= response[2] ;

	if ( ajax_status == "extend" ) 
	{
		if ( ajax_subdivision != "" && ajax_html != "" )
		{
//			$('switchinner').insert({ bottom: ajax_html }) ;
			$('regions').update(ajax_html) ;
			$('regions').innerHTML ;
		}
	}
	else
	{
		hide_div('switch') ;
		location.href = '/cms/core/ecube/basket/refresh-page.php' ;
	}
}

function handleResponse( originalRequest )
{
	var reply = originalRequest.responseText;
	$(div).update(reply) ;
	$(div).innerHTML ;
}

// =======================================================================
// ajax_process_form_public ( form_name )
// This is the core AJAX form handler.
// It pre-processes forms doing any inline checking (with JS).
// If the form validates, it is executed - the function required to process
// the form is defined in the ACTION tag of the form itself.
// The script (PHP) returns a "pass" or "fail" depending on its result
// This (crude) method allows us to process forms via AJAX and handle the
// response. We need a better response handler so that we can direct the 
// AJAX in a more sophisticated way (e.g. XML response telling this function
// what to do next)
// =======================================================================

function ajax_process_form_public ( form_name ) 
{
	if ( form_name == "icpsignup" )
	{
		if (document.icpsignup["fields_email"].value == "") 
		{
			document.icpsignup["fields_email"].focus();
			alert("The Email field is required.");
			return false;
		}
	}
  
  	fielddata = $(form_name).serialize(true) ;

	$(form_name).request({
//		encoding: 'iso-8859-1',
//		contentType: 'multipart/form-data',
		method: 'post',
		parameters: fielddata,
		onComplete: processSaveResponsePublic
	})
}

// =======================================================================
// ajax_form_handler ( form_name )
// This function submits forms to the relevant script - it is an AJAX
// wrapper to ensure that the form response is captured and handled in
// an AJAXian way - this allows us to perform further AJAX calls after
// the form is submitted if needed
// =======================================================================

function ajaxFormHandler ( form_name ) 
{
	if ( form_name == "icpsignup" )
	{
		if (document.icpsignup["fields_email"].value == "") 
		{
			document.icpsignup["fields_email"].focus();
			alert("The Email field is required.");
			return false;
		}
	}
  
	fielddata = $(form_name).serialize(true) ;

	$(form_name).request({
//		encoding: 'iso-8859-1',
//		contentType: 'multipart/form-data',
		method: 'post',
		parameters: fielddata,
		onComplete: ajaxResponseHandler
	})
}

// =======================================================================
// ajax_process_form_remote ( form_name )
// This function takes a forms input and passes it to the PHP function
// as a straight back-end job - no response is awaited, it is a "fire and forget"
// =======================================================================

function ajax_process_form_remote ( form_name ) 
{
	if ( form_name == "icpsignup" )
	{
		if (document.icpsignup["fields_email"].value == "") 
		{
			document.icpsignup["fields_email"].focus();
			alert("The Email field is required.");
			return false;
		}
	}
  
	$(form_name).request() ;
}

// =======================================================================
// saythanks()
// A specical case of the response message
// =======================================================================

function saythanks() {
	close_divs();
	element = $('messages') ;
	element.update("Thank you") ;
	$('messages').addClassName('success') ;
	Fat.fade_element('messages', 60, 2000, '#CCCCCC', '#111111');
}

// =======================================================================
// ajaxResponseHandler ( originalRequest )
// This is the core AJAX form response handler.
// It picks up the response result after a form is submitted via AJAX. The
// returned data tells the AJAX handler what to do next. The format of the 
// response is as follows:
//
//	status|action|element|text/url
//
// status	= The status of the form submission; "pass" or "fail"
// action	= What to do next; "close", "message", "ajax"
// element	= The element to display the message in, or to load the URL into
// text/url	= The data; This is either a free text message or a URL
//
// =======================================================================

function ajaxResponseHandler ( originalRequest )
{
	
	var reply = originalRequest.responseText;
	
	var response = reply.split("|") ;

	ajax_status 	= response[0] ;
	ajax_action 	= response[1] ;
	ajax_element 	= response[2] ;
	ajax_data 		= response[3] ;
	
	// Tidy up - close AJAX windows (quick and dirty method)
	hide_div( 'switch' ) ;
	hide_div( 'cmsconsole' ) ;

	// If we are to display a message on screen, close the AJAX DIVs, open the 
	// message port and display the message on screen
	if ( ajax_action == "message" )
	{
		element = $(ajax_element) ;
		show_div(ajax_element) ;
		// If the result was successful, show a "success" message, if not show a "failure" message
		if ( ajax_status == "pass" ) {
			element.update(ajax_data) ;
			element.addClassName('success') ;
			Fat.fade_element(ajax_element, 60, 2000, '#CCCCCC', '#111111');
		} else {
			element.update(ajax_data) ;
			element.addClassName('failure') ;
			Fat.fade_element(ajax_element, 60, 2000, '#CCCCCC', '#111111');
		}
	}

	// If we are directed to perform a new AJAX call, we do what we need to ...
	if ( ajax_action == "ajax" )
	{
		// If the element we are to us is the admin console, call the admin AJAX loader
		if ( ajax_element == "cmsconsole" )
		{
			ajax_preload( ajax_data ) ;
		}
		else
		{
			// If the element we are to us is the public console, call the admin AJAX loader
			if ( ajax_element == "switch" )
			{
				ajax_preload_inner( ajax_data, ajax_element, 600 ) ;
			}
			else
			{
				// It is assumed we are loading into a generic container
				ajax_preload_into( ajax_data, ajax_element ) ;
			}
		}
	}

	// If we are directed to perform a tidy up (this is usually after a back-end 
	// callback which requires no on-screen response
	if ( ajax_action == "close" )
	{
		// Do nothing - windows already closed :)
	}

	// If we are to redirect to a new HTML page, do the redirect
	if ( ajax_action == "redirect" )
	{
		// Redirect to the new URL
		location.href = ajax_data ;
	}

}

function processSaveResponsePublic( originalRequest )
{
	var reply = originalRequest.responseText ;
	var response = reply.split("|") ;
//alert ( response ) ;
	close_divs();
	element = $('messages') ;

	show_div('messages') ;
	if ( response[0] == "pass" ) {
		element.update(response[1]) ;
		$('messages').addClassName('success') ;
		Fat.fade_element('messages', 60, 2000, '#FFFFFF', '#CCFF99');
		setTimeout('hideMessages()', 3000) ;
	} else {
		element.update(response[1]) ;
		$('messages').addClassName('failure') ;
		Fat.fade_element('messages', 60, 2000, '#FFFFFF', '#CCFF99');
		setTimeout('hideMessages()', 3000) ;
	}
}

function hideMessages() 
{
	Effect.DropOut( 'messages' ) ;
}

function processBasketUpdate( originalRequest )
{
	var reply = originalRequest.responseText ;
	var response = reply.split("|") ;
//alert ( response ) ;
	element = $('basketmessage') ;
	$('basketmessage').style.top = ( eventY - 85 ) + "px" ;
	$('basketmessage').style.left = ( eventX - 10 ) + "px" ;
	show_div('basketmessage') ;
	
	if ( response[0] == "pass" ) {
		$('basketinner').update(response[1]) ;
		$('basketinner').addClassName('success') ;
		Fat.fade_element('basketinner', 60, 2000, '#FFFFFF', '#CCFF99');
		setTimeout('hideBasketMessages()', 3000) ;
	} else {
		$('basketinner').update(response[1]) ;
		$('basketinner').addClassName('failure') ;
		Fat.fade_element('basketinner', 60, 2000, '#FFFFFF', '#CCFF99');
		setTimeout('hideBasketMessages()', 3000) ;
	}
}

function hideBasketMessages() 
{
	Effect.Fade( 'basketmessage' ) ;
}

// =======================================================================
// close_divs()
// Generic script to close the DIVs in the header (makes sure there is 
// space whichever DIV we might be opening later)
// =======================================================================

function close_divs()
{
	if ( layer_exists( 'basket' ) ) hide_div( 'basket' ) ;
	if ( layer_exists( 'basketmessage' ) ) hide_div( 'basketmessage' ) ;
	if ( layer_exists( 'newsletter' ) ) hide_div( 'newsletter' ) ;
	if ( layer_exists( 'account' ) ) hide_div( 'account' ) ;
	if ( layer_exists( 'search' ) ) hide_div( 'search' ) ;
	if ( layer_exists( 'messages' ) ) hide_div( 'messages' ) ;
}

function layer_exists ( layer_id )
{
	return ( $( layer_id ) != null ) ;
}

function close_ajaxian ( id )
{
	// Check if there is a second argument
	// If so, this is a flag to indicate if we need to remove the tinyMCE control
	numargs = arguments.length ;
	if ( numargs >= 1 )
	{
		close_tinymce = arguments[1] ;	// Set the style mods for the container
	}
	else
	{
		// Set the default
		close_tinymce = false ;
	}

	// Close TinyMCE editor if needed
	if ( close_tinymce ) deactivateEditors() ;

	// Remove the content from within the selected DIV
	inner = "" ;
	if ( id == 'cmsconsole' ) div = "consoleinner" ;
	if ( id == 'switch' ) div = "switchinner" ;
	$(div).update(inner) ;
	$(div).innerHTML ;

	// Remove the controlling DIV
	hide_div( id ) ;

}

// =======================================================================
// attach_currency_changer()
// Attaches the currency changer DIV to the document where the mouse is
// =======================================================================

function attach_user_control( txt ) {
	var newhtml = '<div id="close">' ;
	newhtml = newhtml + '<a href="javascript:hide_div(\'currencyswitch\');">' ;
	newhtml = newhtml + '<img alt="Close" src="/assets/images/design/close.gif"/>' ;
	newhtml = newhtml + '</a>' ;
	newhtml = newhtml + '</div>' ;
	newhtml = newhtml + txt ;
	$('switchinner').update(newhtml) ;
	show_div( 'switch' ) ;
}

// =======================================================================
// Google toolbar "fixer"
// This gracefully manages the google toolbar's habit of changing field colours
// =======================================================================

if(window.attachEvent)
    window.attachEvent("onload",setListeners);
  
  function setListeners(){
    inputList = document.getElementsByTagName("INPUT");
    for(i=0;i<inputList.length;i++){
      inputList[i].attachEvent("onpropertychange",restoreStyles);
      inputList[i].style.backgroundColor = "";
    }
    selectList = document.getElementsByTagName("SELECT");
    for(i=0;i<selectList.length;i++){
      selectList[i].attachEvent("onpropertychange",restoreStyles);
      selectList[i].style.backgroundColor = "";
    }
  }

  function restoreStyles(){
    if(event.srcElement.style.backgroundColor != "" && event.srcElement.style.backgroundColor != "#a0d0ff"){
      event.srcElement.style.backgroundColor = "#222222"; /* color of choice for AutoFill */
      document.all['googleblurb'].style.display = "block";
    }
  }

// =======================================================================
// Callback JS - Used post-AJAX load
// =======================================================================

function draggable( mydiv, mytag )
{

   Sortable.create( mydiv ,
     { tag: mytag, overlap:'horizontal', constraint: false,
//     { tag: mytag, dropOnEmpty: true, overlap: 'horizontal', containment: [ mydiv ], constraint: false,
		onUpdate:function()
		{
	 		new Ajax.Request('/cms/bespoke/notebook/update-images.php', 
							 {
								 asynchronous:true, evalScripts:true, 
							  	 onComplete:function(request)
								 {
								 	new Effect.Highlight( mydiv,{startcolor:'#b2c891', endcolor:'#FFFFFF'});
								 }, 
							  	 parameters: { sortorder: Sortable.serialize( mydiv ), elementname: mydiv }
							  })
		}
    })

}

// =======================================================================
// AJAX file uploader results
// =======================================================================

function stopUpload(statusflag, messagetext)
{
    document.getElementById('statusmessage').innerHTML = messagetext;
    document.getElementById('f1_upload_process').style.visibility = 'hidden';
    document.getElementById('f1_upload_process').style.display = 'none';
	setTimeout( ajax_preload( 'bespoke/notebook/update.php' ), 2000 ) ;
	return true;
}

// =======================================================================
// AJAX confirm action/delete
// =======================================================================

function confirmDelete( id )
{
	var answer = confirm ( "Are you sure you want to delete the image?" )

	if ( answer )
	{
		var url = '/cms/bespoke/notebook/delete-image.php?id=' + id ;
		var myAjax = new Ajax.Request( 
						url, 
						{
							method: 'get',
							onComplete: ajax_preload( 'bespoke/notebook/update.php' )
						}
					 )
	}

}

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

// =======================================================================
// Check country for subdivisions
// This is used in the checkout to decide if we need to display a drop-down
// of the regions (subdivisions) for the country selected (e.g. states in
// the USA, counties in the UK, etc.)
// =======================================================================

function checkCountryRegions( countryid, restrictbyzone, fieldname )
{

	page = "/core/ecube/basket/check-countries.php" ;
//	alert ( countryid.value + "|" + restrictbyzone + "|" + fieldname ) ;
	// Set up the URL of the page to be loaded
	var url = '/cms/' + page ;
	var myAjax = new Ajax.Request( 
					url, 
					{
						method: 'get',
						parameters: {c: countryid.value, r: restrictbyzone, f: fieldname},
						onComplete: display_region_switch
					}
				 )

}

// Display the new country region switcher (e.g. list of states) if required
// 	ajax_status: if this is "extend" we need to display the list
//	ajax_subdivision: this is the field we need to replace (its containing ID)
//	ajax_html: the new selection list to insert
function display_region_switch ( originalRequest )
{
	var reply = originalRequest.responseText;

	var response = reply.split("|") ;

	ajax_status 	= response[0] ;
	ajax_subdivision= response[1] ;
	ajax_html		= response[2] ;
//	alert ( ajax_status + "|" + ajax_subdivision + "|" + ajax_html ) ;

	if ( ajax_status == "extend" ) 
	{
		if ( ajax_subdivision != "" && ajax_html != "" )
		{
			var check_image = $(ajax_subdivision).next().identify();
			if ( check_image == "insertedImage" ) $(ajax_subdivision).next().remove()
//			$('switchinner').insert({ bottom: ajax_html }) ;
			$(ajax_subdivision).replace(ajax_html) ;
			$(ajax_subdivision).innerHTML ;
		}
	}
	// If we have to reset the field to a text field, check if it already is a
	// text field and leave it alone if it is (it is likely that the visitor has
	// already entered their county/state and won't be pleased to enter it again)
	if ( ajax_status == "reset" ) 
	{
//		alert ( ajax_status + "|" + ajax_subdivision + "|" + ajax_html ) ;
		if ( ajax_subdivision != "" && ajax_html != "" )
		{
			var existing = $(ajax_subdivision).type ;
//			alert ( existing ) ;
			var check_image = $(ajax_subdivision).next().identify();
			if ( check_image == "insertedImage" ) $(ajax_subdivision).next().remove()
			if ( existing != "text" )
			{
				$(ajax_subdivision).replace(ajax_html) ;
				$(ajax_subdivision).innerHTML ;
			}
		}
	}
}

function urldecode( str ) {
    // http://kevin.vanzonneveld.net
    // +   original by: Philip Peterson
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // *     example 1: urldecode('Kevin+van+Zonneveld%21');
    // *     returns 1: 'Kevin van Zonneveld!'
    
    var ret = str;
       
    ret = ret.replace(/\+/g, '%20');
    ret = decodeURIComponent(ret);
    ret = ret.toString();
 
    return ret;
}

// =======================================================================
// This function swaps the YES/NO form controls and sets the hidden field
// accordingly - this can be used from any form
// =======================================================================

function toggle_yes_no ( formname, fieldname, newstate )
{

	var form = $(formname);
	var data = form[fieldname];

	var yes_icon_id = fieldname + "_Y" ;
	var no_icon_id = fieldname + "_N" ;
	var yes_icon_selected = '/assets/images/forms/yes-selected.png' ;
	var yes_icon_deselected = '/assets/images/forms/yes-deselected.png' ;
	var no_icon_selected = '/assets/images/forms/no-selected.png' ;
	var no_icon_deselected = '/assets/images/forms/no-deselected.png' ;

	if ( newstate == "Y" )
	{
		$(yes_icon_id).src = yes_icon_selected ;
		$(no_icon_id).src = no_icon_deselected ;
	}
	else
	{
		$(yes_icon_id).src = yes_icon_deselected ;
		$(no_icon_id).src = no_icon_selected ;
	}

	$(data).value = newstate ;
	
}

// =======================================================================
// Import additional JS code as needed 
// This avoids needing to update the template and add additional JS modules
// =======================================================================

function count_price_slices( curr_min, curr_max )
{
	count = 0 ;
	for ( jj=curr_min; jj<=curr_max; jj++ )
	{
		count += price_slice[jj] ;
	}
	return count ;
}

var Affinity = {
  Version: '0.7.0',
  require: function(libraryName) 
  {
    // inserting via DOM fails in Safari 2.0, so brute force approach
    document.write('<script type="text/javascript" src="'+libraryName+'"><\/script>');
  },
  REQUIRED_PROTOTYPE: '1.6.0',
  load: function() 
  {
    function convertVersionString(versionString)
	{
      var r = versionString.split('.');
      return parseInt(r[0])*100000 + parseInt(r[1])*1000 + parseInt(r[2]);
    }
 
    if((typeof Prototype=='undefined') || 
       (typeof Element == 'undefined') || 
       (typeof Element.Methods=='undefined') ||
       (convertVersionString(Prototype.Version) < 
        convertVersionString(Affinity.REQUIRED_PROTOTYPE)))
       throw("Affinity requires the Prototype JavaScript framework >= " +
        Affinity.REQUIRED_PROTOTYPE);
    
    $A(document.getElementsByTagName("script")).findAll( function(s) 
	{
	  return (s.src && s.src.match(/scriptaculous\.js(\?.*)?$/))
    }).each( function(s) 
	{
      var path = s.src.replace(/scriptaculous\.js(\?.*)?$/,'');
      var includes = s.src.match(/\?.*load=([a-z,]*)/);
      (includes ? includes[1] : 'lightbox,carousel,tabcontent,fat').split(',').each(
       function(include) { Affinity.require(path+include+'.js') });
    });
  }
}

Affinity.load();
