var basket = new Basket();

var campaignObject = null;
$(document).ready(function(){
	
	if ($.cookie("discount") && basket.getActiveDiscount() == ""){
		$.cookie("discount", null);
	}
	
	// Search for campaigns to activate

	$(".campaign_cp").each(function(){
		var campaignId = $(this).attr("id");
		// Depending on type choose diff renderinger method
		renderCampaign(campaignId, function(data){
			if(data.statusmsgs[0].status == "success"){
				var folder = data.statusmsgs[0].data.folder;
				var htmlData = $.ajax({
					async: false,
					url: (folder + "index.php"),
					data: {
						campaignId: campaignId
						} // we could send along campaign id so that content to draw info from database instead of hardcoding
				}).responseText;
				$.getScript(folder + "script.js", function(data, textStatus){
					eval(data);
					campaignObject.ready(htmlData);
					campaignObject.display();
				});				
			}
		});
	});

	if ($.url.attr("file") == "basket.php"){
		$(":input[name=lemail]").change(function(){
			var email = $(this).val();
			var url = "funktioner/ajax.mc.php";
			$.get(url, {
				sid: Math.random(),
				e: email
			}, function(){} );
		});
		
		var $zip = $(":input[name=lzip]");
		var $address = $(":input[name=lgade1]");
		if ($($zip).val()){
			handleZipChange($($zip).val());
		}
		
		$("#dialog_address").dialog({
			bgiframe: true,
			autoOpen: false,
			draggable: false,
			resizable: false,
			width: 350,
			title: "OBS!",
			modal: true,
			buttons: {
				"Bibehålla adressen" : function(event){
					basket.disableDiscount($.cookie("discount").split("|")[0], $.cookie("discount").split("|")[1], function(result){
						if ($.cookie("discount")) {
							$.cookie("discount", null);
						}
						$("form[name=info]").attr("action", "basket.php");
						$("form[name=info]").submit();
					});
					$(this).dialog("close");
				},
				"Fylla i en ny adress" : function(event){
					$address.val("");
					$zip.val("");
					$.cookie("customer", null);
					$.cookie("customer_name", null);
					$.cookie("customer_address", null);
					$.cookie("customer_zip", null);
					$.cookie("customer_phone", null);
					$.cookie("customer_email", null);
					$(this).find("#defaultchoice").remove();
					$(this).dialog("close");
				}
			},
			close: function(event, ui){
				if ($("#defaultchoice", this).size() > 0){
					basket.disableDiscount($.cookie("discount").split("|")[0], $.cookie("discount").split("|")[1], function(result){
						$("form[name=info]").attr("action", "basket.php");
						$("form[name=info]").submit();
					});
				}
			}
		});
		
		$address.add($zip).change(function(event){
			if ($address.val() != "" && $zip.val() != ""){
				var jCustomer = getCustomer($address.val(), $zip.val());
				var activeDiscount = basket.getActiveDiscount();
				if (jCustomer['new'] == false && activeDiscount != "") {
					$("#dialog_address").html($("#dialogtemplate_address").html());
					$("#dialog_address").dialog("open");
				} else {
					$.cookie("customer", jCustomer.id, { expires: 730 });
					$.cookie("customer_name", jCustomer.name, { expires: 730 });
					$.cookie("customer_address", jCustomer.address, { expires: 730 });
					$.cookie("customer_zip", jCustomer.zip, { expires: 730 });
					$.cookie("customer_phone", jCustomer.phone, { expires: 730 });
					$.cookie("customer_email", jCustomer.email, { expires: 730 });
				}
			}
		});	
		
		// === Address toggle ===
		$('#andenFaktAdr').click(function(e){
			toggleLevAdr($(this).attr('checked'), false);
		});
		
		// === Pay buttons ===
		$('input[name=topaycpr]').click(function(e){
			return validatorfakturaPrivat(document.forms.info);
		});
		$('input[name=topaycvr]').click(function(e){
			return validatorfaktura(document.forms.info);
		});
		$('input[name=topaykort]').click(function(e){
			return validatornonfaktura(document.forms.info);
		});
		
		// === Name sync ===
		var fn_lname2payment = function(e) {
			$('#f2nameprivat').add('#f2nameerhverv').html($(this).val());
		};
		$('#lname').keyup(fn_lname2payment).change(fn_lname2payment).blur(fn_lname2payment);
		
		// === Phone number sync ===
		var fn_lphone2payment = function(e) {
			$('#f2phoneprivat').add($('#f2phoneerhverv')).val($(this).val());
		};
		$('#lphone').keyup(fn_lphone2payment).blur(fn_lphone2payment);
		var fn_payment2lphone = function(e) {
			$('#lphone').val($(this).val());
		};
		$('#f2phoneprivat').add('#f2phoneerhverv').change(fn_payment2lphone).blur(fn_payment2lphone);
		
		// === E-mail sync ===
	    var fn_lemail2payment = function(e) {
			$('#f2emailprivat').add('#f2emailerhverv').html($(this).val());
		};
		$('#lemail').change(fn_lemail2payment).blur(fn_lemail2payment);
	
		// === Set proper required fields
		toggleLevAdr($(this).attr('checked'), false); // but don't submit
	} // end of basket.php

	$("input[name=buy]").each(function(i){
		if ($(this).parents(".product").find(".discount").size()){
			$(this).click(function(event){	
				var discountCookie = $.cookie("discount");
				var customerCookie = $.cookie("customer");
				var $dialogDiscount = $("#dialog_discount");
				var $product = $(this).parents(".product").eq(0);
				var number = $($product).find("input[name=number]").val();
				var productId = $($product).attr("id");
				var discountId = $(".discount", $product).eq(0).attr("id");
				if (discountCookie){
					var discountArray = discountCookie.split("|");
					if (discountArray[0] == discountId && discountArray[1] == productId){
						basket.add(productId, number, function(){});
						basket.applyDiscount(discountId, productId, function(){ // shouldnt be necessary but if host name is changed a new session is created without a discount.
							basket.update(function(updatedBasket){
								updateBasket($("#smallbasket"), updatedBasket, productId);
							});
						});
					} else {
						var $dialogChoice = $("#dialog_discountchoice");
						$($dialogChoice).html($("#dialogtemplate_choose").html());
						$($dialogChoice).find("form").prepend("<input type='hidden' name='quantity' id='quantity' value='" + number + "'/>");
						$($dialogChoice).find("form").prepend("<input type='hidden' name='discountId' id='discountId' value='" + discountId + "'/>");
						$($dialogChoice).find("form").prepend("<input type='hidden' name='productId' id='productId' value='" + productId + "'/>");		$($dialogChoice).find("form").prepend("<input type='hidden' name='oldDiscountId' id='oldDiscountId' value='" + discountArray[0] + "'/>");
						$($dialogChoice).find("form").prepend("<input type='hidden' name='oldProductId' id='oldProductId' value='" + discountArray[1] + "'/>");
						$($dialogChoice).dialog("open");						
					}
				} else {
					$($dialogDiscount).html($("#dialogtemplate_form").html());
					$($dialogDiscount).find("form").prepend("<input type='hidden' name='quantity' id='quantity' value='" + number + "'/>");
					$($dialogDiscount).find("form").prepend("<input type='hidden' name='discountId' id='discountId' value='" + discountId + "'/>");
					$($dialogDiscount).find("form").prepend("<input type='hidden' name='productId' id='productId' value='" + productId + "'/>");
					$($dialogDiscount).dialog('open');
				}
				event.preventDefault();
			});
		} else {
			activateBuyButton($(this).parents(".product").eq(0));
		}
	});
	
	var elSmallbasket = $("#smallbasket");
	activateAddOne(elSmallbasket);
	activateRemoveOne(elSmallbasket);
	
	// TODO check antal og tilføj bemærkning om at det er kun er 1 produkt
	// TODO check om der allerede er anvendt en rabat, er det tilfældet skal man kun vælge hvilken produkt tilbudet skal gælde for.
	var discountButtons = {
		"Ja tack!": function(event) {
			var tips = $("#tips", this), address = $("#address", this), zip = $("#zip", this), bothFields = $([]).add(address).add(zip);
			tips.text("");
			var bValid = true;
			bothFields.removeClass('ui-state-error');
			if (address.val().length < 5){
				address.addClass('ui-state-error');
				tips.append("Adressfältet skall innehålla minst 5 tecken.<br/>").effect("highlight",{},1500);
				bValid = false;
			}
			if (!(/^([0-9]){5}$/.test(zip.val()))){
				zip.addClass('ui-state-error');
				tips.append("Ogiltigt postnummer (Ex. på postnr: 20001)<br/>").effect("highlight",{},1500);
				bValid = false;
			}	
			if(bValid){
				var jCustomer = getCustomer(address.val(), zip.val());
				var discountId = $(this).find("#discountId").val();
				var productId = $(this).find("#productId").val();
				var quantity = $(this).find("#quantity").val();
				basket.add(productId, quantity, function(){});
				if (jCustomer['new'] == false) {
					$(this).html($("#dialogtemplate_warning").html());
					$(this).dialog('option', 'buttons', { 
						"Ok": function() { 
							$(this).dialog("close"); 
						}
					});
					$(this).dialog('option', 'title', 'OBS!');
					$.cookie("customer", jCustomer.id, { expires: 730 });
					$.cookie("customer_name", jCustomer.name, { expires: 730 });
					$.cookie("customer_address", jCustomer.address, { expires: 730 });
					$.cookie("customer_zip", jCustomer.zip, { expires: 730 });
					$.cookie("customer_phone", jCustomer.phone, { expires: 730 });
					$.cookie("customer_email", jCustomer.email, { expires: 730 });
					$("input[name=buy]").each(function(i){ // unbind discount dialog and activate normal behaviour
						if ($(this).parents(".product").find(".discount").size()){
							$(this).unbind("click");
							activateBuyButton($(this).parents(".product").eq(0));
						}
					});
					// remove discounts
					$(".product .discount").each(function(){
						$(this).fadeOut(3000, function(){
							$(this).remove();
						});
					});
				} else {
					// set new customer cookie
					$.cookie("discount", discountId + "|" + productId, { expires: 1 });
					$.cookie("customer", "new", { expires: 730 });
					$.cookie("customer_address", $(this).find("#address").eq(0).val(), { expires: 730 });
					$.cookie("customer_zip", $(this).find("#zip").eq(0).val(), { expires: 730 });
					basket.applyDiscount(discountId, productId, function(){});
					$(this).dialog('close');
				}
			}
		},
		"Nej": function(event) {
			var productId = $(this).find("#productId").val();
			var quantity = $(this).find("#quantity").val();
			basket.add(productId, quantity, function(){});
			$(this).dialog("close");
		}
	};
	$("#dialog_discount").dialog({
			bgiframe: true,
			autoOpen: false,
			draggable: false,
			resizable: false,
			title: "ERBJUDANDE",
			modal: true,
			buttons: discountButtons,
			close: function() {
				$(this).html($("#dialogtemplate_form").html());
				$(this).dialog('option', 'buttons', discountButtons);
				$(this).dialog('option', 'title', 'ERBJUDANDE');
				basket.update(function(updatedBasket){
					updateBasket($("#smallbasket"), updatedBasket, null);
				});
			}
		});
		
	var choiceButtons = {
		"Ja tack!": function(event) {
			var discountId = $(this).find("#discountId").val();
			var productId = $(this).find("#productId").val();
			var quantity = $(this).find("#quantity").val();
			
			$.cookie("discount", discountId + "|" + productId, { expires: 1 });
			basket.add(productId, quantity, function(){});
			basket.applyDiscount(discountId, productId, function(){});
			$(this).dialog("close");
		},		
		"Nej, lägg varan i varukorgen till normalpris": function(event) {
			var productId = $(this).find("#productId").val();
			var quantity = $(this).find("#quantity").val();
			basket.add(productId, quantity, function(){});
			$(this).dialog("close"); 
		}
	};
	
	$("#dialog_discountchoice").dialog({
			bgiframe: true,
			autoOpen: false,
			draggable: false,
			resizable: false,
			minHeight: 50,
			width: 350,
			title: "ÄNDRA ERBJUDANDET",
			modal: true,
			buttons: choiceButtons,
			close: function() {
				$(this).html($("#dialogtemplate_choose").html());
				$(this).dialog('option', 'buttons', choiceButtons);
				$(this).dialog('option', 'title', 'ÄNDRA ERBJUDANDET');
				basket.update(function(updatedBasket){
					updateBasket($("#smallbasket"), updatedBasket, null);
				});
			}
		});
;});

function toggleLevAdr(checked, submit)
{
  if (submit == null) submit = true;
  if (!checked)
  {
    document.getElementById('fakturainfo').style.display = 'none';
    document.forms.info.elements.fname.className="tf";
    document.forms.info.elements.fgade1.className="tf";
    document.forms.info.elements.fzip.className="tf";
    document.forms.info.elements.fcity.className="tf";
  }
  else
  {
    document.getElementById('fakturainfo').style.display = 'inline';
    document.forms.info.elements.fname.className="required tf";
    document.forms.info.elements.fgade1.className="required tf";
    document.forms.info.elements.fzip.className="required tf";
    document.forms.info.elements.fcity.className="required tf";
  }
  if (submit)
  {
    document.forms.info.action = 'basket.php';
    document.forms.info.submit();
  }
}

function activateBuyButton(elProduct){
	$(":input[name=buy]", elProduct).click(function(event){
		event.preventDefault();
		var number = $(elProduct).find("input[name=number]").val();
		var id = $(elProduct).attr("id");
		basket.add(id, number, function(){
			basket.update(function(updatedBasket){
				updateBasket($("#smallbasket"), updatedBasket, id);
			});
		});
	});
}
function activateAddOne(elBasket){
	$(".lilleplusknap", elBasket).each(function(i){
		$(this).click(function(event){
			event.preventDefault();
			var elId = $(this).prev().prev();
			var id = $(elId).val();
			basket.add(id, 1, function(){
				basket.update(function(updatedBasket){
					updateBasket($("#smallbasket"), updatedBasket, id);
				});
			});
		});
	});
}
function activateRemoveOne(elBasket){
	$(".lilleminusknap", elBasket).each(function(i){
			$(this).click(function(event){
			event.preventDefault();
			var elId = $(this).prev();
			var id = $(elId).val();
			basket.remove(id, 1, function(){
				basket.update(function(updatedBasket){
					updateBasket($("#smallbasket"), updatedBasket, id);
				});
			});
		});
	});
}
function updateBasket(elBasket, updatedBasket, id){
	$(elBasket).html(updatedBasket);
	if (id && $("input[value=" + id + "]", elBasket).size()) {
		$("input[value=" + id + "]", elBasket).parents("tr").stop().effect("highlight", {}, 3000);
	} else {
		$(elBasket).stop().effect("highlight", {}, 3000);
	}
	activateAddOne(elBasket);
	activateRemoveOne(elBasket);
}
function getCustomer(address, zip){
	var customer = eval($.ajax({
		url: "funktioner/ajax.customer.php",
		dataType: "json",
		data: ({
			action: "lookup",
			address: address,
			zip: zip
			}),
		async: false
	}).responseText);
	return customer;
}
function formatPrice(price){
	var formater = new NumberFormat(price);
	formater.setPlaces(2);
	formater.setSeparators(true, formater.PERIOD, formater.COMMA);
	return formater.toFormatted();
}
function renderCampaign(campaignId, callback){
	$.post("funktioner/ajax.cp.php",
		{
			id: campaignId,
			a: "gui"
		},
		function(data){ callback(data); },
		"json"
	);
}
/**
 * Constructs a new Basket object
 */
function Basket(sid){
	this.sid = sid;
	this.url = "funktioner/ajax.basket.php";
}

/**
 * Adds an item to the basket.
 */
Basket.prototype.add = function(id, quantity, callback){
	$.post(this.url, 
		{
			sid: this.sid,
			add: id,
			quantity: quantity
		}, 
		function(result){ callback(result); }
	);
};
Basket.prototype.addOne = function(id, callback){
	this.add(id, 1, callback);
};

/** 
 * Removes an item from the basket.
 */
Basket.prototype.remove = function(id, quantity, callback){
	$.post(this.url, 
		{
			sid: this.sid,
			remove: id,
			quantity: quantity
		}, 
		function(result){ callback(result); }
	);	
};
Basket.prototype.removeOne = function(id, callback){
	this.remove(id, 1, callback);
};
Basket.prototype.removeAll = function(id, callback){
		$.post(this.url, 
		{
			sid: this.sid,
			remove: id,
			quantity: "all"
		}, 
		function(result){ callback(result); }
	);	
};

/**
 * Clears the content of the basket.
 */
Basket.prototype.clear = function(callback){
	$.post(this.url, 
		{ 
			sid: this.sid,
			clear: 1 
		}, 
		function(result){ callback(result); }
	);
};

/**
 * Resets the basket but does not clear the items.
 */
Basket.prototype.reset = function(callback){
	$.post(this.url,
		{
			sid: this.sid,
			reset: 1
		},
		function(result){ callback(result); }
	);
};
Basket.prototype.update = function(callback){
	$.post(this.url,
		{
			sid: this.sid,
			update: 1
		},
		function(result){ callback(result); }
	);
};
Basket.prototype.applyDiscount = function(discountId, productId, callback){
	$.post(this.url,
		{
			sid: this.sid,
			discount: discountId,
			product: productId			
		},
		function(result){ callback(result); }		
	);
};
Basket.prototype.disableDiscount = function(discountId, productId, callback){
	$.post(this.url,
		{
			sid: this.sid,
			disable: discountId,
			product: productId
		},
		function(result){ callback(result); }
	);	
};
Basket.prototype.getActiveDiscount = function(){
	return $.ajax({
		url: this.url,
		type: "POST",
		data: ({
			sid: this.sid,
			activediscount: 1
			}),
		async: false
	}).responseText;
};
