function ajaxFunction(div, string)
{
var xmlHttp;
cursor_wait();
try
  {
  // Firefox, Opera 8.0+, Safari
  xmlHttp=new XMLHttpRequest();
  }
catch (e)
  {
  // Internet Explorer
  try
    {
    xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
    }
  catch (e)
    {
    try
      {
      xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
      }
    catch (e)
      {
      alert("Your browser does not support AJAX!");
      return false;
      }
    }
  }
  xmlHttp.onreadystatechange=function()
    {
    if(xmlHttp.readyState==4)
      {
      cursor_clear();
      document.getElementById(div).innerHTML = xmlHttp.responseText;
      }
    }
  xmlHttp.open("GET",string,true);
  xmlHttp.send(null);
  }

function addToCart(productId,quantity,stock){

var optionString = "";

var quantity = parseFloat(quantity);
var stock = parseFloat(stock);

if(quantity > stock){

document.getElementById('basketError').innerHTML = '<p style="color: #cc0000;">Not enough stock, please amend quantity.</p>';

}

else{

// add options to string

if(document.getElementById('totalOptions')){

var i=0;
var total = document.getElementById('totalOptions').value;
var divID;

while (i<=total)
{
divID = 'option_'+i;

if(document.getElementById(divID)){
optionString+='&option_'+i+'='+document.getElementById(divID).value;
}

i=i+1;
}

}

if(!isNaN(quantity) && quantity != '0'){
ajaxFunction('basket','/functions/addToCart.php?id='+productId+'&quantity='+quantity+optionString);
document.getElementById('basketError').innerHTML = '';
}

else{
document.getElementById('basketError').innerHTML = '<p style="color: #cc0000;">Please enter a quantity.</p>';
return false;
}

}

}

function wishlistLoginEvent(productID, quantity,e){

if(window.event) // IE
{
keynum = e.keyCode
}
else if(e.which) // Netscape/Firefox/Opera
{
keynum = e.which
}

if(keynum == '13'){

return addToWishlist(productID, quantity,'login');

}

}

function addToWishlist(productID, quantity, toggle){

if(quantity != '0' && quantity.length > 0 && productID.length > 0){

cursor_wait();

// check if logged in

var xmlHttp;

if(toggle == 'login' && document.getElementById('signInEmail') && document.getElementById('signInPassword')){
email = document.getElementById('signInEmail').value;
password = document.getElementById('signInPassword').value;
string = '/functions/checkoutLogin.php?email='+email+'&pass='+password;
}

else{
string = '/functions/wishlistCheck.php?productID='+productID+'&qty='+quantity;
}

try
  {
  // Firefox, Opera 8.0+, Safari
  xmlHttp=new XMLHttpRequest();
  }
catch (e)
  {
  // Internet Explorer
  try
    {
    xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
    }
  catch (e)
    {
    try
      {
      xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
      }
    catch (e)
      {
      alert("Your browser does not support AJAX!");
      return false;
      }
    }
  }
  xmlHttp.onreadystatechange=function()
    {
    if(xmlHttp.readyState==4)
      {
	cursor_clear();
      var loggedin = xmlHttp.responseText;

	if(loggedin == 'true'){

	// add to wishlist

	if(document.getElementById('popupDiv')){
	popupDisplayNone('popupDiv');
	}

	addToWishlist2(productID,quantity);

	}

	else{

	if(toggle == 'login'){
	document.getElementById('loginError').innerHTML = xmlHttp.responseText;
	document.getElementById('loginError').style.display = 'block';
	}

	else{
	popupDiv(xmlHttp.responseText, 500, 400);
	}

	}

      }
    }

  xmlHttp.open("GET",string,true);
  xmlHttp.send(null);

}

}

function addToWishlist2(productID, quantity){

// add options to string

if(document.getElementById('totalOptions')){

var i=0;
var total = document.getElementById('totalOptions').value;
var optionString = "";
var divID;

while (i<=total)
{
divID = 'option_'+i;

if(document.getElementById(divID)){
optionString+='&option_'+i+'='+document.getElementById(divID).value;
}

i=i+1;
}

}

if(quantity.length > 0 && quantity != '0'){
ajaxFunction('accountLogin','/functions/addToWishlist.php?id='+productID+'&quantity='+quantity+optionString);
}

else{
document.getElementById('basketError').innerHTML = '<p style="color: #cc0000;">Please enter a quantity.</p>';
return false;
}

}

function removeFromCart(productId){

ajaxFunction('basket','/functions/removeFromCart.php?id='+productId);

}

function accountLogin(){

var email = document.getElementById('email').value;
var password = document.getElementById('password').value;

ajaxFunction('accountLogin','/functions/accountLogin.php?email='+email+'&pass='+password);

}

function accountLogout()
{
ajaxFunction('accountLogin','/functions/accountLogout.php');
}

function searchSite(){
var searchStr = document.getElementById('search').value;
window.location='/search.htm?search=' + escape(searchStr);
}

function searchSuggest(e){

var resultLimit = 7;

var searchStr = document.getElementById('search').value;

if(searchStr.length > 1){

if(window.event) // IE
{
keynum = e.keyCode
}
else if(e.which) // Netscape/Firefox/Opera
{
keynum = e.which
}

resultLimit = resultLimit -1;

if(keynum == '37' || keynum == '39'){
// do nothing for now
}

else if(keynum == '40'){

// if down cursor pressed

if(document.getElementById('searchSuggest').innerHTML == ''){
ajaxFunction('searchSuggest','/functions/searchSuggest.php?search='+escape(searchStr)+'&addClass=1');
displayBlock('searchSuggest');
}

else{

var i = 0;
var change;
var div;
var div2Change;
var noneSelected = 1;

	while(i<=resultLimit){

	div = 'ssid_'+i;

	if(document.getElementById(div)){

		if(document.getElementById(div).className == 'active'){
		div2Change = i+1;
		div2ChangeStr = 'ssid_'+div2Change;
		if(document.getElementById(div2ChangeStr)){
		document.getElementById(div).className = '';
		}
		noneSelected = 0;
		}

		if(i == div2Change){
		document.getElementById(div).className = 'active';
		}
	}
	i=i+1;
	}

if(noneSelected == 1){
if(document.getElementById('ssid_0')){
document.getElementById('ssid_0').className = 'active';
}
}

}

}

else if(keynum == '38'){
// up arrow pressed

var i = resultLimit;
var change;
var div;
var div2Change;

	while(i>=0){

	div = 'ssid_'+i;

	if(document.getElementById(div)){

		if(document.getElementById(div).className == 'active'){
		document.getElementById(div).className = '';
		if(i == 0){
		document.getElementById('searchSuggest').innerHTML = '';
		displayNone('searchSuggest');
		}
		div2Change = i-1;
		}

		if(i == div2Change){
		document.getElementById(div).className = 'active';
		}

	}
	i=i-1;
	}

}

else if(keynum == '27'){
// escape key pressed
document.getElementById('searchSuggest').innerHTML = '';
displayNone('searchSuggest');
}

else if(keynum == '13'){
// if return key pressed

var i = 0;
var div;
var newSearch;
var newSearchStr;


	while(i<=resultLimit){

	div = 'ssid_'+i;

	if(document.getElementById(div)){

		if(document.getElementById(div).className == 'active'){
		newSearch = '1';
		newSearchStr = document.getElementById(div).innerHTML;
		document.getElementById(div).className = '';
		}

	}

	i=i+1;
	}


if(newSearch == '1'){
document.getElementById('search').value = newSearchStr;
document.getElementById('searchSuggest').innerHTML = '';
displayNone('searchSuggest');
}

else{
window.location='/search.htm?search=' + escape(searchStr);
}

}

else{
ajaxFunction('searchSuggest','/functions/searchSuggest.php?search='+escape(searchStr));
displayBlock('searchSuggest');
}

}

else{
document.getElementById('searchSuggest').innerHTML = '';
displayNone('searchSuggest');
}

}

function fillSearchField(searchStr){

document.getElementById('search').value = searchStr;

}

function changeRating(rating,div){
document.getElementById(div).style.backgroundImage = 'url(/images/rating_'+rating+'.gif)';
if(div == 'reviewRating'){
document.getElementById('rating').value = rating;
}
}

function submitRating(rating, product_id){
ajaxFunction('ratingsPanel','/functions/submitRating.php?rating='+rating+'&product_id='+product_id);
}

function originalRating(rating){
document.getElementById('ratingsBG').style.backgroundImage = 'url(/images/rating_'+rating+'.gif)';
}

function displayNone(div){
document.getElementById(div).style.display = 'none';
}

function delayedDisplayNone(div){
setTimeout("displayNone('searchSuggest')", 100);
}

function displayBlock(div){
document.getElementById(div).style.display = 'block';
}

function passwordLogin(e){

if(window.event) // IE
{
keynum = e.keyCode
}
else if(e.which) // Netscape/Firefox/Opera
{
keynum = e.which
}

if(keynum == '13'){

var email = document.getElementById('email').value;
var password = document.getElementById('password').value;

ajaxFunction('accountLogin','/functions/accountLogin.php?email='+email+'&pass='+password);

}

}

function editReview(review_id, rating){

var reviewName = 'review_name_' + review_id;
var reviewImage = 'review_rating_' + review_id;
var reviewContent = 'review_content_' + review_id;
var reviewImageSrc = document.getElementById(reviewImage).src;

document.getElementById('name').value = document.getElementById(reviewName).innerHTML;
document.getElementById('reviewRating').style.backgroundImage = 'url('+reviewImageSrc+')';
document.getElementById('review').innerHTML =  document.getElementById(reviewContent).innerHTML;
document.getElementById('rating').value = rating;

displayBlock('reviewForm');

}

function checkoutCheck(toggle){

var content;
var xmlHttp;
var email;
var password;
var string;

cursor_wait();

if(toggle == 'login' && document.getElementById('signInEmail') && document.getElementById('signInPassword')){
email = document.getElementById('signInEmail').value;
password = document.getElementById('signInPassword').value;
string = '/functions/checkoutLogin.php?email='+email+'&pass='+password;
}

else{
string = '/functions/checkoutCheck.php';
}

try
  {
  // Firefox, Opera 8.0+, Safari
  xmlHttp=new XMLHttpRequest();
  }
catch (e)
  {
  // Internet Explorer
  try
    {
    xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
    }
  catch (e)
    {
    try
      {
      xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
      }
    catch (e)
      {
      alert("Your browser does not support AJAX!");
      return false;
      }
    }
  }
  xmlHttp.onreadystatechange=function()
    {
    if(xmlHttp.readyState==4)
      {
	cursor_clear();
	if(xmlHttp.responseText == 'true'){
	//post form
	document.forms['delivery'].submit();
	}

	else{
	if(toggle == 'login'){
	document.getElementById('loginError').innerHTML = xmlHttp.responseText;
	document.getElementById('loginError').style.display = 'block';
	}

	else{
	popupDiv(xmlHttp.responseText, 500, 400)
	}

	}
      }
    }
  xmlHttp.open("GET",string,true);
  xmlHttp.send(null);
}

function loginEvent(e){

if(window.event) // IE
{
keynum = e.keyCode
}
else if(e.which) // Netscape/Firefox/Opera
{
keynum = e.which
}

if(keynum == '13'){

return checkoutCheck('login');

}

}

function popupDiv(content, divWidth, divHeight){

var divID = 'popupDiv';
var box;

if(document.getElementById(divID)){
box = document.getElementById(divID);
}

else{
box = document.createElement("div");
box.setAttribute("id",divID);
document.body.appendChild(box);
}


	var scrollingLeft = Math.round((document.documentElement.clientWidth/2)-(box.style.width/2)) - (divWidth / 2);
	var scrollingTop = Math.round((document.documentElement.clientHeight/2)-(box.style.height/2)+document.documentElement.scrollTop) - (divHeight / 2);

	box.style.width = divWidth+'px';
	box.innerHTML = content;
	box.style.display = 'block';
	box.style.position = 'absolute';
	box.style.top = scrollingTop+'px';
	box.style.left = scrollingLeft+'px';
	box.style.zIndex = '1';

	return hideShowSelects('hidden');

}

function popupDisplayNone(div){
document.getElementById(div).style.display = 'none';
document.getElementById(div).style.width = '';
hideShowSelects('visible');
}

function hideShowSelects(toggle){

if(navigator.appName == 'Microsoft Internet Explorer'){

var e=document.getElementsByTagName("select");

	for(var i=0;i<e.length;i++)
	{
	e[i].style.visibility = toggle;
	}

return false;
}

else{
return false;
}

}

function deliveryCalc(cartTotal, vat){

var deliveryOption = document.getElementById('deliveryOption').value;
deliveryOptionArr = deliveryOption.split("-");

cartTotal = parseFloat(cartTotal);
deliveryOption = parseFloat(deliveryOptionArr[1]);
var total = cartTotal + deliveryOption;

var deliveryCost;

if(parseFloat(deliveryOptionArr[1]) > 0){
deliveryCost = '&pound;'+deliveryOptionArr[1];
}

else{
deliveryCost = 'FREE';
}

total_with_vat = total * vat;
vatCost = total_with_vat - total;

document.getElementById('deliveryTotal').innerHTML = deliveryCost;
document.getElementById('checkoutVAT').innerHTML = '&pound;'+vatCost.toFixed(2);
document.getElementById('checkoutTotal').innerHTML = '&pound;'+total_with_vat.toFixed(2);

}

function onlyNumbers(e)
			{
	var iKeyCode;
	if (!e) {
		var e = window.event;
	}
	if (e.keyCode) {
		iKeyCode = e.keyCode;
	} else {
		if (e.which) {
			iKeyCode = e.which;
		}
	}
	switch(iKeyCode) {
		case 8:
		case 9:
		case 35:
			break;
		case 36:
			break;
		case 37:
		case 38:
		case 39:
		case 40:
		case 46:
			break;
		case 48:
		case 49:
		case 50:
		case 51:
		case 52:
		case 53:
		case 54:
		case 55:
		case 56:
		case 57:
			if (e.shiftKey || e.altKey){
				return false;
			}
			break;
		case 96:
		case 97:
		case 98:
		case 99:
		case 100:
		case 101:
		case 102:
		case 103:
		case 104:
		case 105:
			//return correct numeric from keypad
			return iKeyCode - 48; break;
		case 110:
		//case 190:
			//if you are supporting decimal points
		//	return '.';	break;
		default: return false;
	}
}

function validateFormElements(formElements, frm)
{

var notValid = 0;
var elementId;
var element;

for (x in formElements)
{

elementId = formElements[x];
element = document.getElementById(elementId);

if(element){

	if(element.value.length == 0){
	notValid = 1;
	element.style.border = '1px solid #cc0000';
	}
	else{
	element.style.border = '1px solid #cccccc';
	}

}

}

if(notValid > 0){
return false;
}

else{
document.forms[frm].submit();
}

}

function addOptionLoad(selectID,optionType){

divWidth = 300;
divHeight = 250;

	switch(optionType) {
	case "option_name":
	title = 'Option Name';
	break;

	case "option_value":
	title = 'Option Value';
	break;

	default:

	}

content = '<h2>'+title+'</h2><input type="test" id="optionValueInput" /><br /><a onclick="return addOption(\''+selectID+'\',\''+optionType+'\');" class="button">Add</a>';

popupDiv(content, divWidth, divHeight);

}

function addOption(selectID,optionType){

optionValueInput = document.getElementById('optionValueInput').value;

displayNone('popupDiv');
ajaxFunction(selectID,'/functions/addOption.php?option='+optionValueInput+'&type='+optionType);

}

function updateQuantity(bpi){

var bpq;
var bpid;
var qs = '';
var j;

	for(var i=0;i<bpi;i++)
	{
	if(i>0)qs+='&';
	bpq = 'bpq_'+i;
	bpid = 'bpid_'+i;
	qs+= 'bid_'+document.getElementById(bpid).value+'='+document.getElementById(bpq).value;
	}

	window.location='/functions/updateQuantity.php?'+qs;

}

// pcl params
cp_set_config("access_token", "c902f-a1e92-f482d-0002a");
cp_set_config("form",   "addAddress");
cp_set_config("elements", "address_company,address_line1,address_line2,,addressTown,addressCounty,addressPostcode");
cp_set_config("max_width", "220px");

function lookupAddress(){
document.getElementById('addressPostcode').value = document.getElementById('afpc').value;
crafty_postcode_lookup();
}

function areaCalc(width,height,price,squared,product_id){

var divWidth = 300;
var divHeight = 250;
var content='<h2>Paving Calculator</h2>\
<label for="areaWidth">Area width</label><input type="text" id="areaWidth" />m<br />\
<label for="areaHeight">Area height</label><input type="text" id="areaHeight" />m<br />\
<label for="tileWidth">Tile width</label><input type="text" id="tileWidth" value="'+width+'" />mm<br />\
<label for="tileHeight">Tile height</label><input type="text" id="tileHeight" value="'+height+'" />mm<br />\
<label for="tilePrice">Tile price</label>&pound;<input type="text" id="tilePrice" value="'+price+'" /><br />\
Approx. tiles m&#178;: <span id="squareTilesResult"></span><br />\
Approx. tiles: <span id="tilesResult"></span><br />\
Cost: &pound;<span id="costResult"></span><br />\
<a onclick="return calcArea();">Calculate</a>\
';

popupDiv(content, divWidth, divHeight);

}

function calcArea(product_id){

var div = 'q_'+product_id;

var areaWidth = document.getElementById('areaWidth').value;
var areaHeight = document.getElementById('areaHeight').value;

var areaWidthMM = areaWidth * 1000;
var areaHeightMM = areaHeight * 1000;

var width = document.getElementById('tileWidth').value;
var height = document.getElementById('tileHeight').value;
var price = document.getElementById('tilePrice').value;

var approxTilesWidth = Math.ceil(areaWidthMM / width);
var approxTilesHeight = Math.ceil(areaHeightMM / height);

var approxTiles = approxTilesWidth * approxTilesHeight;

var cost = approxTiles * price;

document.getElementById('areaCalculatorRight').innerHTML = '<p>Tiles: <span>'+approxTiles+'</span></p><p>Total: <span>&pound;'+cost.toFixed(2)+'</span></p>';
document.getElementById(div).value = approxTiles;

}

window.addEvent('domready', function() {

		if($('areaCalculator')){
		var element = $('areaCalculator');
		$('calculateTiles').addEvent('click', element.tween.bind(element, ['height', '155px']));
		}
});

function selectColour(img_id, dropdown_id, colour){

// change current to grey border

var dropdown = 'option_'+dropdown_id;
var currentlySelected = document.getElementById(dropdown).value;
var selectedImage = 'colour_option_'+currentlySelected;

document.getElementById(selectedImage).style.borderColor = '#999999';

// change value of dropdown

document.getElementById(dropdown).value = img_id;

// change image to black border

var selectImage = 'colour_option_'+img_id;
document.getElementById(selectImage).style.borderColor = '#000000';

// change name selected colour text

document.getElementById('selectedColour').innerHTML = colour;

}

// Changes the cursor to an hourglass
function cursor_wait() {
document.body.style.cursor = 'wait';
}

// Returns the cursor to the default pointer
function cursor_clear() {
document.body.style.cursor = 'default';
}