var thisImage = "";
var thisDesc = "test";
var ukPostageVal;

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);
			$("#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['price'].match("0.00"))
					$("#productPrice").hide();
			}
			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(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 addToBasket(productID)
{
	var productType;
	
	if(productID.match("voucher"))
	{
		productType = "voucher";
		productID = productID.replace("voucher", "");
	}
	else 
	{
		productType = $("#type" + productID).val();
	}
	
	$.ajax( {
	
		type: "POST",
		url: "/php/products.php",
		data: { 
			"action": 			"addToBasket", 
			"variantID": 		$("#itemID"+productID).val(), 
			"productID": 		productID, 
			"productType": 	productType 
		},
		success: function(html) {
			$("#basket").html(html);
			$("#productStatus").html('<div class="added_to_basket"></div>');
			if(productID && productType != "voucher")
				location = "/php/basket.php";
		}
		
	});
}

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

$(function(){
	var validator = $("#checkout").validate({	
		rules: {
			bfullname: "required",
			baddr1: "required",
			bcity: "required",
			bcountry: "required",
			bpostalcode: "required",
			btelephonenumber: "required",
			email: { required: true, email: true },
			sfullname: "required",
			saddr1: "required",
			scity: "required",
			scountry: "required",
			spostalcode: "required",
			stelephonenumber: "required"
		},
		messages: {
			bfullname: " ",
			baddr1: " ",
			bcity: " ",
			bcountry: " ",
			bpostalcode: " ",
			btelephonenumber: " ",
			email: " ",
			sfullname: " ",
			saddr1: " ",
			scity: " ",
			scountry: " ",
			spostalcode: " ",
			stelephonenumber: " "
		},
		errorPlacement: function(error, element) {
			error.appendTo( element.parent().next() );
		}
	});
	var validator2 = $("#register").validate({	
		rules: {
			fullname: "required",
			address1: "required",
			city: "required",
			country: "required",
			postcode: "required",
			telephone: "required",
			emailaddress: { required: true, email: true }, 
			password: "required",
			password2: {
      	equalTo: "#password"
      }
		},
		messages: {
			fullname: " ",
			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", "sfullname", "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($(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();
	});
});

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) 
	{
		$("#sfullname").val($("#bfullname").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 {
		$("#sfullname").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());
		
		$("#postageVal").html($("#postage").val());
	
		if($("#vat").val() > 0)
		{
			var vat = thisTotal*.15;
			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);
	}
}