window.onload = loadImageSwapper;

function loadImageSwapper() {
	if (document.getElementsByClassName('thumbImageProd')) {  
		//var table = document.getElementById('thetable');   
		var images = document.getElementsByClassName('thumbImageProd');   
		var files = new Array();
		for (t = 0; t < images.length; t++) {           
			var image = images[t].src;  
			var filename = image.getFileName();
			var newLength = files.push ( '/easypave/images/products/large/'+filename );
		}
		/*for (i = 0; i < files.length; i++) {           
			var test = files[i];  
			alert(test)
		}*/
		function getNextImage() {
			document.mainImage.src=files[1];
			alert('Here');
		}
	}
}

document.getElementsByClassName = function(cl) {
	var retnode = [];
	var myclass = new RegExp('\\b'+cl+'\\b');
	var elem = this.getElementsByTagName('*');
	for (var i = 0; i < elem.length; i++) {
		var classes = elem[i].className;
		if (myclass.test(classes)) retnode.push(elem[i]);
	}
	return retnode;
}; 

String.prototype.getFileName = function() {
	var pos = this.lastIndexOf('/');
	return this.substring(pos+1);
}

function divHeight(i) {
	var boxH = document.getElementById('imgPopup'+i).offsetHeight;
	var boxW = document.getElementById('imgPopup'+i).offsetWidth;
	return {boxW:boxW,boxH:boxH};
}
function showCenter(point, i) {
/*
	var imgPopup = document.getElementById('imgPopup'+i);
	var boxHeight = document.getElementById('imgPopup'+i).offsetHeight;
	
	imgPopup.style.position = "absolute";

	imgPopup.style.top = point.y + "px";
//	imgPopup.style.left = point.x + "px"; // don't think we need this one
	imgPopup.style.bottom = "auto";
*/	var div = document.createElement("div");
	div.style.background = "#dedede";
	div.style.position = "absolute";
	div.style.top = point.y + "px";
	div.style.left = point.x + "px";
	div.style.width = "100px";
	div.style.height = "100px";
	document.body.appendChild(div);
}
window.size = function() {
	var w = 0;
	var h = 0;
	//IE
	if(!window.innerWidth) {
		//strict mode
		if(!(document.documentElement.clientWidth == 0)) {
			w = document.documentElement.clientWidth;
			h = document.documentElement.clientHeight;
		} else { //quirks mode
			w = document.body.clientWidth;
			h = document.body.clientHeight;
		}
	} else { //w3c
		w = window.innerWidth;
		h = window.innerHeight;
	}
	return {width:w,height:h};
}
window.center = function() {
	var hWnd = (arguments[0] != null) ? arguments[0] : {width:0,height:0};
	var _x = 0;
	var _y = 0;
	var offsetX = 0;
	var offsetY = 0;
	//IE
	if(!window.pageYOffset) {
		//strict mode
		if(!(document.documentElement.scrollTop == 0)) {
			offsetY = document.documentElement.scrollTop;
			offsetX = document.documentElement.scrollLeft;
		} else { //quirks mode
			offsetY = document.body.scrollTop;
			offsetX = document.body.scrollLeft;
		}
	} else { //w3c
		offsetX = window.pageXOffset;
		offsetY = window.pageYOffset;
	}
	_x = ((this.size().width-hWnd.width)/2)+offsetX;
	_y = ((this.size().height-hWnd.height)/2)+offsetY;
	return{x:_x,y:_y};
}

function getPos(i) {
	var e = document.getElementById('imgPopupMaster'+i);
	// determine position of currently hovered over image
	var offset = {x:0,y:0};
	while (e) {
		offset.x += e.offsetLeft;
		offset.y += e.offsetTop;
		e = e.offsetParent;
	}
	if (document.documentElement && (document.documentElement.scrollTop || document.documentElement.scrollLeft)) {
		offset.x -= document.documentElement.scrollLeft;
		offset.y -= document.documentElement.scrollTop;
	} else if (document.body && (document.body.scrollTop || document.body.scrollLeft)) {
		offset.x -= document.body.scrollLeft;
		offset.y -= document.body.scrollTop;
	} else if (window.pageXOffset || window.pageYOffset) {
		offset.x -= window.pageXOffset;
		offset.y -= window.pageYOffset;
	}
	//alert(offset.x + '\n' + offset.y); 

	// adjust the popup image, if required
	var popupBoxHeight = document.getElementById("imgPopup"+i).offsetHeight;
	var newPos = 0;

	if (popupBoxHeight < offset.y+40) {
		//do nothing
	} else {
		var moveDisp = popupBoxHeight - offset.y;
		document.getElementById("imgPopup"+i).style.position = 'absolute';
		document.getElementById("imgPopup"+i).style.bottom = -moveDisp+30+'px';
		//alert(offset.y);
	}

}


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,prefix){

	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',prefix+'functions/addToCart.php?id='+productId+'&quantity='+quantity+optionString);
			window.scrollTo(0,0);
			document.getElementById('basket_confirm').style.display = 'block';
			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('basketError','/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);
	window.location.reload(true);
}

function accountLogout() {
	//ajaxFunction('account_buttons','/functions/accountLogout.php');
	//window.location.reload(true);

	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('account_buttons').innerHTML = xmlHttp.responseText;
			window.location.reload(true); //kl 9/6
		}
	}
	string = 'http://www.easypave.com/functions/accountLogout.php';
	xmlHttp.open("GET",string,true);
	xmlHttp.send(null);


}

function searchSite(pref){
	var searchStr = document.getElementById('search').value;
	window.location=pref+'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, prefix){
	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=prefix+'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';
}

var dark_overlay;

function load_login_popup(my_account){
	dark_overlay = new Overlay($(document.body)).open();
	var divWidth = 567;
	var divHeight = 350;
	var divID = 'loginPopupDiv';
	var box;
	var content = '<a onclick="close_login_popup();" id="close_basket_popup">close</a>'
	+'<div id="loginPopupDivLeft"><span id="loginPopupDivResults"></span><label for="login_email">Email address</label><br /><input type="text" name="email" id="login_email" /><br /><br /><label for="login_pass">Password</label><br /><input type="password" name="pass" id="login_pass" /><br /><br /><a onclick="loginPopup_login(\''+my_account+'\');" style="cursor: pointer;"><img src="/images/sign_in_button.png" alt="Sign in" /></a></div>'
	+'<div id="loginPopupDivRight"><p style="margin-top: 0;"><strong>Welcome to Easypave!</strong></p><p>Creating an account only takes a few moments. You will be able to store your delivery details for future orders, as well as viewing your wishlist and more.</p><a href="/register.htm"><img src="/images/create_account_button.png" alt="Create account" /></a></div>';
	
	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 = '10000';
	return hideShowSelects('hidden');
	focus_email();
}

function focus_email(){
	document.getElementById('login_email').focus();
}

function close_login_popup(){
	document.getElementById('loginPopupDiv').style.display = 'none';
	dark_overlay.close();
}

function loginPopup_login(my_account){
	var email = document.getElementById('login_email').value;
	var password = document.getElementById('login_pass').value;
	
	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) {
			//alert(xmlHttp.readyState);
			//alert(xmlHttp.responseText);
			//alert(xmlHttp.status);
			//alert('You are logged into your account');
			if(xmlHttp.responseText == 'true'){
				if(my_account == 'true'){
					window.location='/my-account.htm';
				} else {
					dark_overlay.close();
					document.getElementById('loginPopupDiv').style.display = 'none';
					document.getElementById('account_buttons').innerHTML = '<a href="/my-account.htm"><img src="/images/my_account_button.png" alt="My account" /></a><a onclick="return accountLogout();" style="margin-left: 5px; cursor: pointer;"><img src="/images/logout_button.png" alt="Logout" /></a>';
				}
			} else {
				document.getElementById('loginPopupDivResults').innerHTML = xmlHttp.responseText;
			}
		}
	}
	var url = 'http://www.easypave.com/functions/accountLogin.php?email='+email+'&pass='+password;
	//var url = 'http://localhost/easypave/functions/accountLogin.php?email='+email+'&pass='+password;
	//xmlHttp.open("GET",'http://localhost/easypave/functions/accountLogin.php?email='+email+'&pass='+password,true);
	xmlHttp.open("GET",url,true);
	xmlHttp.send(null);
	//window.location.reload(true);
}
function show_reviews(){
	document.getElementById('reviews_content').style.display = 'block';
	document.getElementById('product_description').style.display = 'none';
}

function show_product_details(){
	document.getElementById('reviews_content').style.display = 'none';
	document.getElementById('product_description').style.display = 'block';
}
