$(document).ready(function(){
	var accordionstart = 0;
	
	function addProductToCart(product, location, type, slots, rental) {
		var values = "";
		values += "product=" + product;
		values += "&location=" + location;
		values += "&type=" + type;
		values += "&slots=" + slots;
		values += "&rental=" + rental;

		var product = parseInt(product);
		var output = "";
		
		$.post("/" + THIS_Language + "/order/ajaxAddProductToCart", values, function(data){
			$("#isempty").hide();
			
			output += "<div style='clear: both;'><div id='" + $("cartitemid", data).text() + "' style='float: left; clear: left;'>";
			output += "<div style='width: 170px; float: left;'><strong>" + $("productname", data).text() + "</strong><br /> " + $("type", data).text() + "</div>";
			output += "<div style='width: 85px; float: left;'>" + $("location", data).text() + "</div>";
			output += "<div style='width: 75px; float: left;'>" + $("slots", data).text() + "</div>";
			output += "<div style='width: 70px; float: left;'>" + $("months", data).text() + "</div>";
			
			if(parseInt($("c_totalprice", data).text()) < parseInt($("c_o_totalprice", data).text())) {
				if($("localprice", data).text() != "") {
					output += "<div style='width: 100px; float: left;'>" + $("localprice", data).text() + " <font style='color: #ff0000'>-" + $("discount", data).text() + "%</font> <br /><span class='discount_small'>(" + $("o_localprice", data).text() + ")</span></div>";
				}
				else {
					output += "<div style='width: 100px; float: left;'>" + $("totalprice", data).text() + " <font style='color: #ff0000'>-" + $("discount", data).text() + "%</font> <br /><span class='discount_small'>(" + $("o_totalprice", data).text() + ")</span></div>";
				}
			}
			else {
				if($("localprice", data).text() != "") {
					output += "<div style='width: 100px; float: left;'>" + $("localprice", data).text() + " <br /><span class='small'><i>(&euro; " + $("totalprice", data).text() + ")</i></span></div>";
				}
				else {
					output += "<div style='width: 100px; float: left;'>&euro; " + $("totalprice", data).text() + "</div>";
				}
			}
			
			
			output += "<div style='float: left; width: 35px; text-align: center;'><img src='/images/delete.png' id='" + $("cartitemid", data).text() + "' class='removeFromCartButton' style='cursor: pointer; height: 15px;' /></div>";
			output += '<div style="height: 10px; clear: both;"></div></div></div>';
			
			$("#cartcontent").append(output);
			
			var id = $("cartitemid", data).text();
			
			$("#cartcontent .removeFromCartButton:last").bind("click", function() {
				var id = $(this).attr("id");
				removeProductFromCart(id);
			});
			
			updatePrice();
			wizard.accordion("activate", 0);
		}, "xml");
	}
	
	function removeProductFromCart(id) {
		var values = "";
		values += "id=" + id;
		
		$.post("/en/order/ajaxRemoveProductFromCart", values, function() {
			$("#" + id).remove();
			updatePrice();
			
		}, "xml");
		
	}
	
	function updatePrice() {
		var values = "";
		values += "productId=" + $("#product").val();
		values += "&type=" + $("#type").val();
		values += "&slots=" + $("#slots").val();
		values += "&rental=" + $("#rental").val();

		$.post("/" + THIS_Language + "/order/ajaxCalculatePrice", values, function(data) {
			var totalprice = $("totalprice", data).text();
			var normalprice = $("normalprice", data).text();
			var normalpricelocal = $("normalpricelocal", data).text();
			var discount = $("discount", data).text();
			var discountlocal = $("discountlocal", data).text();
			var secondaryprice = $("secondaryprice", data).text();
			
			if(discountlocal != "") {
				$("div#totalprice").html(secondaryprice);
				$("div#normalprice").html(normalpricelocal);
				$("div#normalsecondary").html("(" + normalprice + ")");
				$("div#discount").html(discountlocal);
				$("div#discountsecondary").html("(" + discount + ")");
				$("div#totalsecondary").html("(" + totalprice + ")");
			}
			else {
				$("div#totalprice").html(totalprice);
				$("div#normalprice").html(normalprice);
				$("div#discount").html(discount);
			//	$("div#totalseconday").html("(" + LANG_Approx + " " + secondaryprice + ")");
			}
			
			
		}, "xml");
	}
	
	function getRelatedProducts(id) {
		var values = ''; 
		values = "id=" + id;
		values += "&type=" + $("#type").val();
		
		$.post("/" + THIS_Language + "/order/ajaxGetRelatedProducts", values, function(data){
			var value = '';
			$("product", data).each(function(i) {
				var id = $("id", this).text();
				var ident = $("ident", this).text();
				var name = $("name", this).text();
				var type = $("type", this).text();
				var slots = $("slots", this).text();
				var slotsPresent = $("slotsPresent", this).text();
				var price = $("price", this).text();
				var pricePresent = $("pricePresent", this).text();
				var location = $("location", this).text();
				var rental = $("rental", this).text();
				var discount = $("discount", this).text();
				
				value += "<input type='hidden' name='" + id + "_url' id='" + id + "_url' value='" + ident + "' />";
				value += "<input type='hidden' name='" + id + "_name' id='" + id + "_name' value='" + name + "' />";
				value += "<input type='hidden' name='" + id + "_type' id='" + id + "_type' value='" + type + "' />";
				value += "<input type='hidden' name='" + id + "_slots' id='" + id + "_slots' value='" + slots + "' />";
				value += "<input type='hidden' name='" + id + "_rental' id='" + id + "_rental' value='" + rental + "' />";
				value += "<input type='hidden' name='" + id + "_location' id='" + id + "_location' value='" + location + "' />";
				
				value += "<div style='text-align: center;'>";
				value += "<br /><br />";
				value += "<a href='/" + THIS_Language + "/products/" + ident + "'><img src='/images/products/" + ident + ".png' style='border: 0px' /></a><br />";
				value += "<b>" + name + "</b><br /><span class='small'>";
				value += slotsPresent + " " + type + " / " + pricePresent;
				if(discount > 0) {
					value += "<font style='color: #ff0000;'> -" + discount + "%</font>";
				}
				value += "</span><br /><input type='button' name='" + id + "' id='" + id + "' value='Add to Cart' class='formButtonFeatures addRelatedToCartButton' />";
				value += "</div>";
			});
		
			$("#relatedProducts_container").html(value);
			
			$("#relatedProducts_container input").bind("click", function() {
				var product = $("#" + $(this).attr('name') + "_url").val();
				var location = $("#" + $(this).attr('name') + "_location").val();
				var type = $("#" + $(this).attr('name') + "_type").val();
				var slots = $("#" + $(this).attr('name') + "_slots").val();
				var rental = $("#" + $(this).attr('name') + "_rental").val();
				
				addProductToCart(product, location, type, slots, rental);
			});
		});
	}
	
	function changeProduct($p) {
		getRelatedProducts($p);
		
		var values = "id=" + $p; 
		$.post("/" + THIS_Language + "/order/ajaxGetProductDetails", values, function(data){
			
			var locationoptions = '';
			$("location", data).each(function(i) {
				var id = parseInt($("id", this).text());
				var name = $("name", this).text();
				var selected = "";
				
				if(THIS_Language == 'dk' && id == 1) {
					selected = "selected";
				}
				
				if(THIS_Language == 'no' && id == 2) {
					selected = "selected";
				}
				
				if(THIS_Language == 'fi' && id == 3) {
					selected = "selected";
				}
				
				locationoptions += "<option value='" + id + "' " + selected + ">" + name + "</option>";
			});
			$("select#location").html(locationoptions);
			
			var typeoptions = '';
			$("type", data).each(function(i) {
				var id = $("id", this).text();
				var name = $("name", this).text();
				
				typeoptions += "<option value='" + id + "'>" + name + "</option>";
			});
			$("select#type").html(typeoptions);
			
			var unitinterval = $("unitinterval", data).text();
			var unit = $("unit", data).text();
			
			var slotoptions = '';
			$("slots", data).each(function(i) {
				var minslots = parseInt($("minslots", this).text());
				var maxslots = parseInt($("maxslots", this).text());
				var stdslots = parseInt($("stdslots", this).text());
				var title = $("title", this).text();
				
				var i=0;
				for(i=(minslots/unitinterval); i<=(maxslots/unitinterval); i++) {
					var selected = '';
					var j = i * unitinterval;
					if(i == stdslots) {
						selected = "selected";
					}
										
					slotoptions += "<option value='" + j + "' " + selected + ">" + j + " " + unit + "</option>";
				}
			});
			
			var rentaloptions = '';
			$("rental", data).each(function(i) {
				$("rental", data).each(function(i) {
					var minrental = parseInt($("minrental", this).text());
					var maxrental = parseInt($("maxrental", this).text());
					var stdrental = parseInt($("stdrental", this).text());
					
					var i=0;
					for(i=minrental; i<=maxrental; i++) {
						var selected = '';
						if(i == stdrental) {
							selected = "selected";
						}
						
						var addon;
						if(i == 1) {
							addon = ' - 0% ' + LANG_Discount;
							var title = $("month", this).text();
						}
						else {
							addon = ' - ' + i*2 + '% ' + LANG_Discount;
							var title = $("months", this).text();
						}
						
						rentaloptions += "<option value='" + i + "' " + selected + ">" + i + " " + title + addon + "</option>";
					}
				});
			});
			
			$("select#slots").html(slotoptions);
			$("select#rental").html(rentaloptions);
			$("#unitContainer").html($("unit", data).text() + ":");
		});
	}
	
	$("select#product").change(function(){
		changeProduct($(this).val());
	});
	
	$("select#type").change(function(){
		getRelatedProducts($("select#product").val());
	});
	
	$("#addtocartsubmit").click(function() {
		addProductToCart($("#product").val(), $("#location").val(), $("#type").val(), $("#slots").val(), $("#rental").val());
	});
	
	$(".removeFromCartButton").click(function() {
		var id = $(this).attr("id");
		removeProductFromCart(id);
	});
	
	$("#username_new").keyup(function() {
		var values = ''; 
		values = "username=" + $(this).val();
		
		$.post("/" + THIS_Language + "/order/ajaxCheckUsername", values, function(data) {
			var options = $("result", data).text();
			
			$("div#usernameError").html(options);
		}, "xml");
	});
	
	$("#cardnumber").blur(function() {
		if($(this).val().length != 16) { var options = ERROR_CreditCardLength; } else { var options = ''; }
		
		$("div#paymentError").html(options);
	});
	$("#controlnumber").blur(function() {
		if($(this).val().length != 3) { var options = ERROR_CreditCardControlNumber; } else { var options = ''; }
		$("div#paymentError").html(options);
	});
	
	$("#paymentCreditcard").click(function() {
		$("div#creditcardContainer").show();
		$("div#wiretransferContainer").hide();
		$("div#paypalContainer").hide();
	});
	
	$("#paymentPaypal").click(function() {
		$("div#paypalContainer").show();
		$("div#wiretransferContainer").hide();
		$("div#creditcardContainer").hide();
	});
	
	$("#paymentWiretransfer").click(function() {
		$("div#wiretransferContainer").show();
		$("div#creditcardContainer").hide();
		$("div#paypalContainer").hide();
	});
	
	$("#CompleteOrder").click(function() {
		if($("#terms").attr('checked') == "checked") {
			$("#orderForm").submit();
		}
		else {
			alert(LANG_TermsAndConditionsText + ' ' + LANG_TermsAndConditions);
			return false;
		}
	});
	
	function fetchHavelaage() {
		var url = document.location.toString();

		if (url.match('#')) {
			var id = parseInt(url.split('#')[1]);
			if(id > 0) {
				accordionstart = id;
			}
		}
	}
	
	fetchHavelaage();
	
	var wizard = $("#wizard").accordion({
		header: '.title',
		autoHeight: false,
		active: accordionstart,
		icons: {
 			header: "ui-icon-circle-arrow-e",
   			headerSelected: "ui-icon-circle-arrow-s"
		}
	});
	
	var wizardButtons = $([])
	$("div.title", wizard).each(function(index) {
		wizardButtons = wizardButtons.add($(this)
		.next()
		.children(":button")
		.filter(".next, .previous")
		.click(function() {
			wizard.accordion("activate", index + ($(this).is(".next") ? 1 : -1))
		}));
	});
	
	$("#orderForm").validate({
		errorLabelContainer: "#orderForm div.error",
		rules: {
			firstname: {
				required: true,
				minlength: 2
			},
			lastname: {
				required: true,
				minlength: 2
			},
			address: {
				required: true,
				minlength: 2
			},
			city: {
				required: true,
				minlength: 2
			},
			zip: {
				required:true,
				minlength:4
				
			},
			email: {
				required: true,
				email: true
			},
			password: {
				required: true,
				minlength: 5
			},
			password2: {
				equalTo: "#passwordNew1"
			}
		},
		messages: {
			firstname: ERROR_Firstname + "<br />",
			lastname: ERROR_Lastname + "<br />",
			email: ERROR_Email + "<br />",
			zip: ERROR_Zip + "<br />",
			address: ERROR_Address + "<br />",
			city: ERROR_City + "<br />",
			phone: ERROR_Phone + "<br />",
			password: {
				required: ERROR_PasswordMinlength + "<br />",
				minlength: ERROR_PasswordMinlength + "<br />"
			},
			password2: {
				equalTo: ERROR_Password + "<br />"
			},
			
			agree: ERROR_Agree + "<br />"
		}
	});
	
	$("#loading").ajaxStart(function(){
		$(this).show();
	});
	
	$("#loading").ajaxComplete(function(){
		$(this).hide();
	});
	
	window.onload = function(){ 
		updatePrice();
		getRelatedProducts($("select#product").val());
		
		if($("#autoupdate").val() == 1) {
			newproduct = $("#autoupdateproduct").val();
			$("select#product").val(newproduct);
			changeProduct(newproduct);
		}
		else {
			newproduct = "counter-strike_16";
			$("select#product").val(newproduct);
			changeProduct(newproduct);
		}
	}
});


