function getBasketString(type, colour, price, quantity)
{
	var basketstring = '##'+type+'#'+colour+'#'+price+'#'+quantity+'#';
	return basketstring;
}

function addToBasket(type, colour, price, quantity)
{
	var cookiestring = getCookie("tablemats");
	var basketstring = getBasketString(type, colour, price, quantity);
	var searchstring = type+'#'+colour;
	if (cookiestring == null || cookiestring == '' || cookiestring.indexOf(searchstring) < 0)
	{
		cookiestring += basketstring;
		setCookie("tablemats", cookiestring);
		writeBasket();
	}
	else
	{
		addSome(type, colour, price, quantity);
	}	
}

function addSome(type, colour, price, quantity)
{
	var cookiestring = getCookie("tablemats");
	var basketstring = "##"+type+"#"+colour+"#"+price+"#";
	var index = cookiestring.indexOf(basketstring) + basketstring.length;
	var index2 = cookiestring.indexOf("#", index);
	var newquantity = parseInt(cookiestring.substring(index, index2));
	newquantity += quantity;
	if (newquantity == 0)
		cookiestring = cookiestring.substring(0, cookiestring.indexOf(basketstring))+cookiestring.substring(index2+1);
	else
		cookiestring = cookiestring.substring(0, index)+newquantity+cookiestring.substring(index2);
	setCookie("tablemats", cookiestring);
	writeBasket();
}

function deleteFromBasket(type, colour, price, quantity)
{
	var cookiestring = getCookie("tablemats");
	cookiestring = cookiestring.replace(getBasketString(type, colour, price, quantity), '');
	setCookie("tablemats", cookiestring);
	writeBasket();
}

function getBasketText(isbasket)
{
	var cookiestring = getCookie("tablemats");
	var basketstring = '';
	var type = '';
	var colour = '';
	var quantity = 0;
	var price = 0.00;
	var numitems = 1;
	while (cookiestring.indexOf('##') != -1)
	{
		cookiestring = cookiestring.substring(cookiestring.indexOf('##')+2);
		var index = cookiestring.indexOf('#');
		type = cookiestring.substring(0, index);
		cookiestring = cookiestring.substring(index+1);
		index = cookiestring.indexOf('#');
		colour = cookiestring.substring(0, index);
		cookiestring = cookiestring.substring(index+1);
		index = cookiestring.indexOf('#');
		price = parseFloat(cookiestring.substring(0, index));
		cookiestring = cookiestring.substring(index+1);
		index = cookiestring.indexOf('#');
		quantity = parseInt(cookiestring.substring(0, index));
		cookiestring = cookiestring.substring(index+1);
		basketstring += '<tr><td height=20>'+type+'</td><td>'+colour+'</td>';
		if (isbasket.indexOf("true") < 0)
			basketstring += '<td colspan=2>'+quantity;
		else
			basketstring += '<td>'+quantity+'</td><td>';
		if (isbasket.indexOf("true") > -1)
		{
			basketstring += '<input type=button onclick="addSome(\''+type+'\', \''+colour+'\', '+price+', 1);" value="+">';
			basketstring += '<input type=button onclick="addSome(\''+type+'\', \''+colour+'\', '+price+', -1);" value="-">';
		}
		basketstring += '</td><td align=right>£'+price.toFixed(2)+'</td><td align=right>£'+(price*quantity).toFixed(2)+'</td>';
		if (isbasket.indexOf("true") > -1)
			basketstring += '<td><input type=button onclick="deleteFromBasket(\''+type+'\', \''+colour+'\', '+price+', '+quantity+');" value="Delete"></td>';
		basketstring += '</tr>';
		basketstring += '<input type="hidden" name="item_name_'+numitems+'" value="'+type+' - '+colour+'">';
		basketstring += '<input type="hidden" name="amount_'+numitems+'" value="'+price.toFixed(2)+'">';
		basketstring += '<input type="hidden" name="quantity_'+numitems+'" value="'+quantity+'">';
		numitems += 1;
	}
	var subtotal = getBasketSubtotal();
	var postage = getPostage(subtotal);
	var total = getBasketTotal(subtotal, postage);
	basketstring += '<tr><td height=20 class=bb colspan=4></td><td height=20>Subtotal</td><td align=right>£'+subtotal.toFixed(2)+'</td>';
	if (isbasket.indexOf("true") > -1)
		basketstring += '<td></td>';
	basketstring += '</tr><tr><td height=20 class=bb colspan=4></td><td height=20>Postage</td><td align=right>£'+postage.toFixed(2)+'</td>';
	if (isbasket.indexOf("true") > -1)
		basketstring += '<td></td>';
	basketstring += '<input type="hidden" name="item_name_'+numitems+'" value="Delivery">';
	basketstring += '<input type="hidden" id="shipping" name="amount_'+numitems+'" value="'+postage.toFixed(2)+'">';
	basketstring += '<input type="hidden" name="quantity_'+numitems+'" value="1">';
	basketstring += '</tr><tr><td height=20 class=bb colspan=4></td><td height=20>TOTAL</td><td align=right>£'+total.toFixed(2)+'</td>';
	if (isbasket.indexOf("true") > -1)
		basketstring += '<td></td>';
	basketstring += '</tr>';
	return basketstring;
}

function getSubmitBasketString()
{
	var cookiestring = getCookie("tablemats");
	var basketstring = '';
	var type = '';
	var colour = '';
	var quantity = 0;
	var price = 0.00;
	var numitems = 1;
	while (cookiestring.indexOf('##') != -1)
	{
		cookiestring = cookiestring.substring(cookiestring.indexOf('##')+2);
		var index = cookiestring.indexOf('#');
		type = cookiestring.substring(0, index);
		cookiestring = cookiestring.substring(index+1);
		index = cookiestring.indexOf('#');
		colour = cookiestring.substring(0, index);
		cookiestring = cookiestring.substring(index+1);
		index = cookiestring.indexOf('#');
		price = parseFloat(cookiestring.substring(0, index));
		cookiestring = cookiestring.substring(index+1);
		index = cookiestring.indexOf('#');
		quantity = parseInt(cookiestring.substring(0, index));
		cookiestring = cookiestring.substring(index+1);
		basketstring += ':'+type+' - '+colour+':'+quantity+':£'+price.toFixed(2);
		basketstring += ':£0.00:£'+price.toFixed(2)+':'+(price*quantity).toFixed(2);
		numitems += 1;		
	}
	basketstring = ''+numitems+basketstring+':Delivery:::::£'+getPostage(getBasketSubtotal()).toFixed(2);
	return basketstring;
}

function getBasketSubtotal()
{
	var cookiestring = getCookie("tablemats");
	if (cookiestring == null)
		return 0;
	var price = 0.00;
	var itemprice = 0.00;
	while (cookiestring.indexOf('##') != -1)
	{
		cookiestring = cookiestring.substring(cookiestring.indexOf('##')+2);
		var index = cookiestring.indexOf('#');
		index = cookiestring.indexOf('#', index+1);
		cookiestring = cookiestring.substring(index+1);
		index = cookiestring.indexOf('#');
		itemprice = parseFloat(cookiestring.substring(0, index));
		cookiestring = cookiestring.substring(index+1);
		index = cookiestring.indexOf('#');
		quantity = parseInt(cookiestring.substring(0, index));
		cookiestring = cookiestring.substring(index+1);
		price += (itemprice * quantity);
	}
	return price;
}

function getPostage(subtotal)
{
	var postCode = "";
	if (document.getElementById('Postcode') != null)
		postCode = removeSpaces(document.getElementById('Postcode').value);		
	var postage = 0;
	if (subtotal > 0 && subtotal < 100)
		postage = 5;
	if (postCode != null && postCode != '')
	{
		if (postCode.indexOf('IV') == 0 || postCode.indexOf('HS') == 0 || postCode.indexOf('ZE') == 0)
			postage += getSurcharge();
		else if (postCode.indexOf('KW') == 0 || postCode.indexOf('BT') == 0 || postCode.indexOf('IM') == 0)
			postage += getSurcharge();
		else if (postCode.length == 7 && postCode.indexOf('PH') == 0)
		{
			var num = parseInt(postCode.substring(2, 4));
			if ((num > 29 && num < 45) || (num > 16 && num < 27) || (num > 48 && num < 51))
				postage += getSurcharge();
		}
		else if (postCode.length == 7 && postCode.indexOf('PA') == 0)
		{
			var num = parseInt(postCode.substring(2, 4));
			if ((num > 19 && num < 50) || (num > 59 && num < 79))
				postage += getSurcharge();
		}
	}
	return postage;
}

function getSurcharge()
{
	var surcharge = 2 * getQuantity();
	return surcharge;
}

function getQuantity()
{
	var cookiestring = getCookie("tablemats");
	if (cookiestring == null)
		return 0;
	var quantity = 0;
	var itemquantity = 0;
	while (cookiestring.indexOf('##') != -1)
	{
		cookiestring = cookiestring.substring(cookiestring.indexOf('##')+2);
		var index = cookiestring.indexOf('#');
		index = cookiestring.indexOf('#', index+1);
		cookiestring = cookiestring.substring(index+1);
		index = cookiestring.indexOf('#');
		cookiestring = cookiestring.substring(index+1);
		index = cookiestring.indexOf('#');
		itemquantity = parseInt(cookiestring.substring(0, index));
		cookiestring = cookiestring.substring(index+1);
		quantity += itemquantity;
	}
	return quantity;
}

function removeSpaces(string) 
{
	var tstring = "";
	if (string == null)
		return tstring;
	string = '' + string;
	splitstring = string.split(" ");
	for(i = 0; i < splitstring.length; i++)
	tstring += splitstring[i];
	return tstring;
}

function getBasketTotal(subtotal, postage)
{
	return (subtotal + postage);
}

function writeBasket()
{
	window.location.href= 'http://www.rubbertablemats.com/basket.htm';
}

function setCookie(name, value) 
{
  	var curCookie = name + "=" + escape(value);
  	var date = new Date();
	date.setTime(date.getTime()+(7*24*60*60*1000));
	var expires = "; expires="+date.toGMTString();
	var curCookie = name+"="+escape(value)+expires+"; path=/";
  	document.cookie = curCookie;
}

function addtocookie(name, value)
{
	var curCookie = getCookie(name) + escape(value);
	setCookie(name, curCookie);
}

function getCookie(name) 
{
  	var dc = document.cookie;
  	var prefix = name + "=";
  	var begin = dc.indexOf("; " + prefix);
  	if (begin == -1) 
	{
   		 begin = dc.indexOf(prefix);
    		if (begin != 0) 
			return null;
  	} 
	else
    		begin += 2;
  	var end = document.cookie.indexOf(";", begin);
  	if (end == -1)
    		end = dc.length;
  	return rehash(unescape(dc.substring(begin + prefix.length, end)));
}

function deleteCookie(name) 
{
   if (getCookie(name)) 
   {
     	document.cookie = name + "=";
   }
}

function rehash(cookiestring)
{
	var rep = /%23/g;
	cookiestring = cookiestring.replace(rep, '#');
	return cookiestring;
}

function simpleXor(text, key)
{
	var result=[];
	
	for(var i = 0; i < text.length; i++)
    	{
      		result[i] = (text.charCodeAt(i) ^ key.charCodeAt(i % key.length));
    	}
    	return result;
}

function encode(data) 
{
    	var encoding = [
	    "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", "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", "+", "/"
	];
    	var result = [];
    	var ip57   = Math.floor(data.length / 57);
    	var fp57   = data.length % 57;
    	var ip3    = Math.floor(fp57 / 3);
    	var fp3    = fp57 % 3;
    	var index  = 0;
    	var num;
    
    	for ( var i = 0; i < ip57; i++ ) 
    	{
        	for ( j = 0; j < 19; j++, index += 3 ) 
        	{
            		num = data[index] << 16 | data[index+1] << 8 | data[index+2];
            		result.push(encoding[ ( num & 0xFC0000 ) >> 18 ]);
            		result.push(encoding[ ( num & 0x03F000 ) >> 12 ]);
            		result.push(encoding[ ( num & 0x0FC0   ) >>  6 ]);
            		result.push(encoding[ ( num & 0x3F     )       ]);
        	}
        	result.push("\n");
    	}

    	for ( i = 0; i < ip3; i++, index += 3 ) 
    	{
        	num = data[index] << 16 | data[index+1] << 8 | data[index+2];
        	result.push(encoding[ ( num & 0xFC0000 ) >> 18 ]);
        	result.push(encoding[ ( num & 0x03F000 ) >> 12 ]);
        	result.push(encoding[ ( num & 0x0FC0   ) >>  6 ]);
        	result.push(encoding[ ( num & 0x3F     )       ]);
    	}

    	if ( fp3 == 1 ) 
    	{
        	num = data[index] << 16;
        	result.push(encoding[ ( num & 0xFC0000 ) >> 18 ]);
        	result.push(encoding[ ( num & 0x03F000 ) >> 12 ]);
        	result.push("==");
    	} 
    	else if ( fp3 == 2 ) 
    	{
        	num = data[index] << 16 | data[index+1] << 8;
        	result.push(encoding[ ( num & 0xFC0000 ) >> 18 ]);
        	result.push(encoding[ ( num & 0x03F000 ) >> 12 ]);
        	result.push(encoding[ ( num & 0x0FC0   ) >>  6 ]);
        	result.push("=");
    	}
   	return result.join("");
}
   
function getTransCode()
{
	var d = new Date();
	return "RFO" + (Math.random()*1000000) + "." + d.getTime();
}

function getCrypt()
{
	var vendorTxCode = getTransCode();
	var subtotal = getBasketSubtotal();
	var postage = getPostage(subtotal);
	if ((subtotal < 100 && postage > 10) || (subtotal >= 100 && postage > 0))
		if (!confirm('A surcharge of £'+getSurcharge(postage)+' has been added to your delivery costs due to the postcode entered. Please see our delivery policy for details.'))
			return false;
	var amount = getBasketTotal(subtotal, postage).toFixed(2);
	var currency = "GBP";
	var description = "Goods from Rubber Flooring Online";
	var customerEmail= document.getElementById('email').value;
	var customerName= document.getElementById('Name').value;
	var vendorEmail= "administrator@rubberflooringonline.co.uk";
	var deliveryAddress= document.getElementById('Address1').value;
	deliveryAddress += ", " + document.getElementById('Address2').value;
	deliveryAddress += ", " + document.getElementById('Town').value;
	deliveryAddress += ", " + document.getElementById('County').value;
	var deliveryPostCode= document.getElementById('Postcode').value;
	var billingAddress= deliveryAddress;
	var billingPostCode= deliveryPostCode;
	var contactNumber = document.getElementById('Phone').value;
	var shoppingBasket = getSubmitBasketString();

	var stuff = "VendorTxCode=" + vendorTxCode + "&Amount=" + amount;
	stuff += "&Currency=" + currency + "&Description=" + description;
	stuff += "&SuccessURL=http://www.rubberflooringonline.co.uk/success.htm&FailureURL=http://www.rubberflooringonline.co.uk/failure.htm";

	if ( customerEmail != "" ) 
	{
	  stuff += "&CustomerEmail=" + customerEmail;
	}
	if ( vendorEmail != "" ) 
	{
	  stuff += "&VendorEmail=" + vendorEmail;
	}
	if ( customerName != "" ) 
	{
	  stuff += "&CustomerName=" + customerName;
	}
	if (deliveryAddress != "" ) 
	{
	  stuff += "&DeliveryAddress=" + deliveryAddress;
	}
	if (deliveryPostCode != "" ) 
	{
	  stuff += "&DeliveryPostCode=" + deliveryPostCode;
	}
	if (billingAddress != "" ) 
	{
	  stuff += "&BillingAddress=" + billingAddress;
	}
	if (billingPostCode != "" ) 
	{
	  stuff += "&BillingPostCode=" + billingPostCode;
	}
	if (contactNumber != "" ) 
	{
	  stuff += "&ContactNumber=" + contactNumber;
	}
	if (shoppingBasket != "")
	{
		stuff += "&Basket="+shoppingBasket;
	}
	return stuff;
}

function setCrypt()
{
	var stuff = getCrypt();
	var crypt = encode(simpleXor(stuff,'wsNDakQCYzfnyQSd'));
	crypt = crypt.replace(/[\n\r]/g, "" );
	document.getElementById('Crypt').value = crypt;
	document.theForm.action = "https://ukvps.protx.com/vps2Form/submit.asp";
	return checkStockLevels();
}

function submitPayPal()
{
	var subtotal = getBasketSubtotal();
	var postage = getPostage(subtotal);
	if ((subtotal < 100 && postage > 10) || (subtotal >= 100 && postage > 0))
		if (!confirm('A surcharge of £'+getSurcharge()+' has been added to your delivery costs due to the postcode entered. Please see our delivery policy for details.'))
			return false;
	document.getElementById('shipping').value = postage.toFixed(2);
	document.getElementById('cmd').value = "_cart";
	document.getElementById('upload').value = "1";
	document.getElementById('business').value = "administrator@rubberflooringonline.co.uk";
	document.getElementById('currency_code').value = "GBP";
	document.getElementById('return').value = "http://www.rubberflooringonline.co.uk/success.htm";
	document.theForm.action = "https://www.paypal.com/cgi-bin/webscr";
	return checkStockLevels();
}

function checkStockLevels()
{
	var cookiestring = getCookie("basket");
	if (cookiestring == null)
		return true;
	var quantity = 0;
	var stock = 0;
	var type = '';
	var colour = '';
	var typeNum = 0;
	var colourNum = 0;
	while (cookiestring.indexOf('##') != -1)
	{
		cookiestring = cookiestring.substring(cookiestring.indexOf('##')+2);
		var index = cookiestring.indexOf('#');
		type = cookiestring.substring(0, index);
		cookiestring = cookiestring.substring(index+1);
		index = cookiestring.indexOf('#');
		colour = cookiestring.substring(0, index);
		cookiestring = cookiestring.substring(index+1);
		index = cookiestring.indexOf('#');
		cookiestring = cookiestring.substring(index+1);
		index = cookiestring.indexOf('#');
		quantity = parseInt(cookiestring.substring(0, index));
		cookiestring = cookiestring.substring(index+1);
		typeNum = getTypeNum(type);
		colourNum = getColourNum(colour);
		if (typeNum != -1 && colourNum != -1)
		{
			index = typeNum*22 + colourNum;
			stock = stockLevels[index];
			if (quantity > stock)
				return confirm('At least one of the items you have in your basket is out of stock, or stock levels are too low to fulfil your order. Delivery will therefore be 6-8 weeks. If you wish to continue, please click OK. If not, please click Cancel to go back and amend your order. Thank you!');
		}
	}
	return true;
}

function getTypeNum(type)
{
	for (var i = 0; i < typeNames.length; i++)
		if (type == typeNames[i])
			return i;
	return -1;
}

function getColourNum(colour)
{
	for (var i = 0; i < colourNames.length; i++)
		if (colour == colourNames[i])
			return i;
	return -1;
}