var thisImage = "";
var thisDesc = "test";
var ukPostageVal;
var pricetype = "normal";
var minwidth, maxwidth, mindepth, maxdepth, minprice;
var volumePrice = new Object();

$(function(){
	var validator = $("#checkout").validate({	
		rules: {
			bfirst_name: "required",
			blast_name: "required",
			baddr1: "required",
			bcity: "required",
			bcountry: "required",
			bpostalcode: "required",
			btelephonenumber: "required",
			email: { required: true, email: true },
			sfirst_name: "required",
			slast_name: "required",
			saddr1: "required",
			scity: "required",
			scountry: "required",
			spostalcode: "required",
			stelephonenumber: "required"
		},
		messages: {
			bfirst_name: " ",
			blast_name: " ",
			baddr1: " ",
			bcity: " ",
			bcountry: " ",
			bpostalcode: " ",
			btelephonenumber: " ",
			email: " ",
			sfirst_name: " ",
			slast_name: " ",
			saddr1: " ",
			scity: " ",
			scountry: " ",
			spostalcode: " ",
			stelephonenumber: " "
		},
		errorPlacement: function(error, element) {
			error.appendTo( element.parent().next() );
		}
	});
	var validator2 = $("#register").validate({	
		rules: {
			first_name: "required",
			last_name: "required",
			address1: "required",
			city: "required",
			country: "required",
			postcode: "required",
			telephone: "required",
			emailaddress: { required: true, email: true }, 
			password: "required",
			password2: {
      	equalTo: "#password"
      }
		},
		messages: {
			first_name: " ",
			last_name: " ",
			address1: " ",
			city: " ",
			country: " ",
			postcode: " ",
			telephone: " ",
			emailaddress: " ", 
			password: " ", 
			password2: " " 
		},
		errorPlacement: function(error, element) {
			error.appendTo( element.parent().next() );
		}
	});
	$('#productPart').change(function () {
		updateVariants($(this).val());
	});
	$('#productVariant').change(function () {
		updateDetails($(this).val());
	});
	$('.checkout').click(function () {
		$("#action").val("checkout");
		$("#checkout").submit();
	});
	$('.update_basket').click(function () {
		if($("#action").val() == "checkout")
		{
			location = "/php/basket.php";
		}
		else
		{
			$("#action").val("update_basket");
			$("#checkout").submit();
		}
	});
	$('.apply').click(function () 
	{
    var form = document.createElement("form");
    form.setAttribute("method", "POST");
    form.setAttribute("action", "/php/basket.php");
    
		var newField = document.createElement("input");
		newField.setAttribute("type", "hidden");
		newField.setAttribute("name", "action");
		newField.setAttribute("value", "checkout");
		form.appendChild(newField);
			
		var newField = document.createElement("input");
		newField.setAttribute("type", "hidden");
		newField.setAttribute("name", "id");
		newField.setAttribute("value", $("#pageID").val());
		form.appendChild(newField);
			
    var fields = ["promo", "voucher", "sfirst_name", "slast_name", "scompany", "saddr1", "saddr2", 
    	"saddr3", "scity", "spostalcode", "stelephonenumber", "scountyprovince", "scountry", "same_billing"];
    
		for(var i = 0; i < fields.length; i++) 
		{
			var newField = document.createElement("input");
			newField.setAttribute("type", "hidden");
			newField.setAttribute("name", fields[i]);
			newField.setAttribute("value", $("#"+fields[i]).val());
			form.appendChild(newField);
		}
		
		document.body.appendChild(form);
		form.submit();
	});
	$('.continue_shopping').click(function () {
		history.back();
	});
	$('.login').click(function () {
		$("#action").val("login");
		$("#login").submit();
	});
	$('.retrieve_password').click(function () {
		$("#action").val("retrieve_password");
		$("#login").submit();
	});
	$('.register').click(function () {	
		if($("#action").val() == "register") {
			$("#login").submit();
		} else {
			if($("#register").validate().form())
				$("#register").submit();
		}
	});
	$('.purchase').click(function () {
		$("#action").val("pay");
		if($("#checkout").validate().form())
		{
			$("#buttonRow").append('<div class="processing" style="float:right" />');
			$(".update_basket").hide();
			$(this).hide();
			$("#checkout").submit();
		}
	});
	$('.update_my_account').click(function () {
		if($("#register").validate().form())
			$("#register").submit();
	});
	$('.logout').click(function () {
		$("#logout").submit();
	});
	$('#scountry').change(function () {
		if($("#freePostage").val() == "1")
		{
			$("#postage").val("0.00");
			$("#postageText").val("FREE postage");
		}
		else
		{
			if($(this).val() == "GB")
			{
				$("#uk_postage").show();
				$("#postage").val(ukPostageVal);
			}
			else 
			{
				$("#uk_postage").hide();
				if($(this).val() == "")
				{
					$("#postage").val("0.00");
				}
				else 
				{
					if(worldPostage[$(this).val()] != undefined)
						$("#postage").val(worldPostage[$(this).val()]);
					else
						$("#postage").val($("#defaultPostage").val());
				}
			}
		}
		updatePostage();
	});
	
	$("#uk_postage :radio").click(function () {
		ukPostageVal = $(this).val();
		$("#postage").val(ukPostageVal);
		var textID = "rateText" + $(this).val().replace(".","");
		$("#postageText").val($("#"+textID).html());
		updatePostage();
	});

	$("#product_thickness").change(function()
	{
		getPriceByVolume();
	});
	
	$("#product_width").keyup(function()
	{
		checkVolumeFields();
	});
	
	$("#product_depth").keyup(function()
	{
		checkVolumeFields();
	});

});

function checkVolumeFields()
{
	var error = false;
	
	if($("#product_width").val() == "" || parseInt($("#product_width").val()) < minwidth || parseInt($("#product_width").val()) > maxwidth)
	{
		$("#product_volume_table .errors").html("<br><b>Width must be between "+minwidth+"mm and "+maxwidth+"mm</b>");
		error = true;
	}
	else
	{
		$("#product_width").val(parseInt($("#product_width").val()));
	}

	if($("#product_depth").val() == "" || parseInt($("#product_depth").val()) < mindepth || parseInt($("#product_depth").val()) > maxdepth)
	{
		$("#product_volume_table .errors").html("<br><b>Depth must be between "+mindepth+"mm and "+maxdepth+"mm</b>");
		error = true;
	}
	else
	{
		$("#product_depth").val(parseInt($("#product_depth").val()));
	}

	if(error)
	{
		$("#productPrice").hide();
		$(".productStatus").hide();
	}
	else
	{
		$("#product_volume_table .errors").html("");
		$("#productPrice").show();
		$(".productStatus").show();
		getPriceByVolume();
	}
}

function showProduct(productID, partID, pageURL)
{
	var url = "";
	if(pageURL)
		url = pageURL;
	url += "?productID=" + productID;
	if(partID)
		url += "_" + partID;
	location = url;
}

function updateParts(productID, partID) 
{
	$.ajax( {
	
		type: "POST",
		dataType: "json",
		url: "/php/products.php",
		data: { "action": "getParts", "productID": productID },
		success: function(json) {
			var i = 0;
			document.getElementById('productPart').options.length = 0;
			if(json.length > 1) {
				for(var i = 0; i < json.length; i++) 
				{
					document.getElementById('productPart').options[i] = new Option(json[i][1], json[i][0]);
				}
				$('#productParts').show();
				$('#partLine').show();
			} else {
				$('#productParts').hide();
				$('#partLine').hide();
			}
			if(partID) 
			{
				$('#productPart').val(partID);
				updateVariants(partID);
			}
			else 
			{
				updateVariants(json[0][0]);
			}
		}
		
	});
}

function updateVariants(partID) 
{
	$.ajax( {
	
		type: "POST",
		dataType: "json",
		url: "/php/products.php",
		data: { "action": "getVariants", "partID": partID },
		success: function(json) {
			var i = 0;
			document.getElementById('productVariant').options.length = 0;
			if(json.length > 1) {
				for(var i = 0; i < json.length; i++) 
				{
					document.getElementById('productVariant').options[i] = new Option(json[i][1], json[i][0]);
				}
				$('#productVariants').show();
			} else {
				$('#productVariants').hide();
			}
//			$('#productVariant').val(json[0][0]);
			updateDetails(json[0][0]);
		}
		
	});
}

function updateVoucher(voucherID) 
{
	$(".productStatus").html('<div class="add_to_basket"></div>');
	$('.add_to_basket').click(function () 
	{
		addToBasket("voucher"+voucherID);
	});
}

function updateDetails(variantID)
{
	$.ajax( {
	
		type: "POST",
		dataType: "json",
		url: "/php/products.php",
		data: { "action": "getDetails", "variantID": variantID },
		success: function(json) 
		{
			var statusDiv = "productStatus";
			var itemDiv = "itemID";
			var basketID = "";
			var productID = "";
			var productType = $("#type" + json['product_id']).val();

			if(productType == "offer" || productType == "deal")
			{
				statusDiv += json['product_id'];
				itemDiv += json['product_id'];
				productID = json['product_id'];
				basketID = ' id="basket' + json['product_id'] + '"';
			}
				
			$("#"+itemDiv).val(variantID);
			if($('#add_vat').val() == 1)
				json['price'] += ' (ex VAT)';
			$("#productPrice").html(json['price']);
			$("#productCode").html(json['code']);
			json['quantity'] > 0 ?
				$("."+statusDiv).html('<div class="add_to_basket"'+basketID+'></div>'):
				$("."+statusDiv).html('<div class="out_of_stock"></div>');
			if(json['web_order'] != "Y")
				$("."+statusDiv).html('<div class="not_online"></div>');
			if(json['var_image']) 
			{
				$("#productImage").css("background-image", "url(/images/"+json['var_image']+")");
				$("#productImage").css("height", json['var_image_height']+"px");
			}
			thisImage = "/images/"+json['large_image'];
			thisDesc = json['product'];
			
			if(json['related']) 
			{
				$("#relatedProduct").show();
				$("#relatedProducts").html(json['related']);
			} else {
				$("#relatedProduct").hide();
				$("#relatedProducts").html('');
			}
			
			if(json['deals']) 
			{
				$("#productDeals").show();
				$("#productDeals").html(json['deals']);
				$("#dealLine").show();
			} else {
				$("#productDeals").hide();
				$("#productDeals").html('');
				$("#dealLine").hide();
			}
			
			if(json['price_type'] == "volume") 
			{			
				pricetype = json['price_type'];
				minwidth = json['minwidth'];
				maxwidth = json['maxwidth'];
				widthdef = parseInt(minwidth) + parseInt((maxwidth-minwidth)/2);
				mindepth = json['mindepth'];
				maxdepth = json['maxdepth'];
				depthdef = parseInt(mindepth) + parseInt((maxdepth-mindepth)/2);
				minprice = parseFloat(json['minprice']);
				
				$("#product_volume_table").show();
				$(".productStatus").html('<div class="add_to_basket"'+basketID+'></div>');
				
				$("#product_width").attr("title", minwidth+"mm - "+maxwidth+"mm");
				$("#product_depth").attr("title", mindepth+"mm - "+maxdepth+"mm");

				if($("#product_width").val() == "")
					$("#product_width").val(widthdef);
					
				if($("#product_depth").val() == "")
					$("#product_depth").val(depthdef);
				
				var currentThickness = $("#product_thickness").val();
				
				$("#product_thickness").html("");
				var items = json['thicknesses'].split(",");
				var prices = json['prices'].split(",");
				for(var i = 0; i < items.length; i++)
				{
					$("#product_thickness").append('<option value="'+items[i]+'">'+items[i]+'</option>');
					volumePrice[items[i]] = prices[i];
				}
				
				if(currentThickness > 0)
					$("#product_thickness").val(currentThickness);
				
				getPriceByVolume();
			}
			else
			{
				$("#product_volume_table").hide();
				$(".productStatus").show();
			}
			
			if(productType == "offer" || productType == "deal")
			{
				$('#basket'+json['product_id']).click(function () 
				{
					addToBasket(json['product_id']);
				});
				
				$('#noThanks'+json['product_id']).click(function () 
				{
					$.ajax( 
					{
						type: "POST",
						url: "/php/products.php",
						data: { "action": "noThanks", "productID": json['product_id'], "productType": $("#type" + json['product_id']).val() },
						success: function(html) 
						{
							location = "/php/basket.php";
						}
					});
				});
			} 
			else 
			{
				$('.add_to_basket').click(function () 
				{
					addToBasket("");
				});
			}
		}
		
	});
}

function getPriceByVolume()
{
	var width = $("#product_width").val();
	var depth = $("#product_depth").val();
	var thick = $("#product_thickness").val();
	var unit = volumePrice[thick];
	var price = parseFloat((width*depth)*unit);
	if(price < minprice)
		price = minprice;
	$("#productPrice").html("<b>&pound;"+price.toFixed(2)+"</b>");
	$("#product_volume_price").val(price.toFixed(2));
	$("#productPrice").show();
	$(".productStatus").show();
}

function addToBasket(productID)
{
	var productType;
	
	if(productID.match("voucher"))
	{
		productType = "voucher";
		productID = productID.replace("voucher", "");
	}
	else 
	{
		productType = $("#type" + productID).val();
	}
	
	if(pricetype == "volume")
	{
		postData = { 
			"action":			"addToBasket", 
			"variantID":	$("#itemID"+productID).val(), 
			"width":			$("#product_width").val(), 
			"depth":			$("#product_depth").val(),
			"thick":			$("#product_thickness").val(),
			"price":			$("#product_volume_price").val()
		}
	}
	else
	{
		postData = { 
			"action":				"addToBasket", 
			"variantID":		$("#itemID"+productID).val(), 
			"productID":		productID, 
			"productType":	productType
		}
	}
	
	$.ajax( {
	
		type: "POST",
		url: "/php/products.php",
		data: postData,
		success: function(html) {
			var siteURL = $("#siteURL").val();
			$("#basket").html(html);
			if(siteURL.match("modula"))
				$(".productAdded").html('<a href="/php/basket.php" class="added_to_basket"></a>');
			else
				$(".productStatus").html('<a href="/php/basket.php" class="added_to_basket"></a>');
//			setTimeout(resetBasketButton, 2000);
//			if(productID && productType != "voucher")
//			if(productType != "voucher")
//				location = "/php/basket.php";
		}
		
	});
}

function resetBasketButton()
{
	$(".productStatus").html('<div class="add_to_basket"></div>');
	$('.add_to_basket').click(function () 
	{
		addToBasket("");
	});
}

function updatePage(id,link) 
{
	location = link+id;
}

function expressDelivery(value) 
{
	var currTotal = $("#total").val();
	var newTotal = 0;
	if(document.getElementById("express_delivery_box").checked) 
	{
		$("#express_delivery_val").val(value);
		$("#express_delivery").html(value);
		newTotal = parseFloat(currTotal) + parseFloat(value);
	} else {
		$("#express_delivery_val").val(0);
		$("#express_delivery").html("0.00");
		newTotal = parseFloat(currTotal) - parseFloat(value);
	}
	$("#total").val(newTotal.toFixed(2));
	$("#totalText").html(newTotal.toFixed(2));
	
}

function sameAsBilling() 
{
	if(document.getElementById("same_billing").checked) 
	{
		$("#sfirst_name").val($("#bfirst_name").val());
		$("#slast_name").val($("#blast_name").val());
		$("#scompany").val($("#bcompany").val());
		$("#saddr1").val($("#baddr1").val());
		$("#saddr2").val($("#baddr2").val());
		$("#saddr3").val($("#baddr3").val());
		$("#scity").val($("#bcity").val());
		$("#scountyprovince").val($("#bcountyprovince").val());
		$("#scountry").val($("#bcountry").val());
		$("#spostalcode").val($("#bpostalcode").val());
		$("#stelephonenumber").val($("#btelephonenumber").val());
	} else {
		$("#sfirst_name").val("");
		$("#slast_name").val("");
		$("#scompany").val("");
		$("#saddr1").val("");
		$("#saddr2").val("");
		$("#saddr3").val("");
		$("#scity").val("");
		$("#scountyprovince").val("");
		$("#scountry").val("");
		$("#spostalcode").val("");
		$("#stelephonenumber").val("");
	}	
	$('#scountry').change();
}

function viewBasket()
{
	location = "/php/basket.php";
}

function updateBasket()
{

}

function updatePostage()
{	
	if($("#postage").val() != undefined)
	{
		
		var thisTotal = parseFloat($("#runningTotal").val()) + parseFloat($("#postage").val());
		var postage = parseFloat($("#postage").val());
		
		if($("#weightPostage").val() != "")
		{
			thisTotal += parseFloat($("#weightPostage").val());
			postage += parseFloat($("#weightPostage").val());
		}
			
		$("#postageVal").html(postage.toFixed(2));
//		$("#postageVal").html();
		
		if($("#vat").val() > 0)
		{
			var post_vat = postage*.175;
			var vat = $("#vat").val() + post_vat
			
			$("#vat").val( vat.toFixed(2) );
			$("#vatVal").val( vat.toFixed(2) );
			
			thisTotal += parseFloat(vat);
			
			/*
			var vat = thisTotal*.175;
			vat = vat.toFixed(2);
			
			thisTotal += parseFloat(vat);
	
			$("#vat").val(vat);
			$("#vatVal").html(vat);
			*/
		}
		
		if(thisTotal < 0)
			thisTotal = 0;
			
		thisTotal = thisTotal.toFixed(2);
		
		$("#grandtotal").val(thisTotal);
		$("#total").val(thisTotal);
		$("#totalText").html(thisTotal);
		
	}
}