function urlSafe(txt){ 
	return escape(txt).replace("+", "%2B"); 
}

function updatePuffBanner(){
	$("#step1_PuffArea").load("/cart/campaignHints.asp");
}

$(document).ready(function()
{
	//Init Puff Banner
	updatePuffBanner();
	
	// hide the cart "update button" region, that warns about inaccurate price.
	$("#update-cart-button").parent().hide();
	
	// find all articles and handle them.
	$("#lenses .article, #articles .article").each(enhanceArticleTable);
	
	// Apply a campaign to the order
	$("#campaigncode-apply").click(function()
	{
		if(campaignActive){
			var replaceCampaign = confirm("Du har redan en aktiv kampanj. Om du väljer att aktivera en ny kampanj kommer din tidigare kampanj tas bort. Vill du det?");
			if(replaceCampaign == false){
				return false;
			}
		}
		
		var value = encodeURIComponent($("#campaigncode").val());
		$.getJSON("update.asp", {"ajax": "1", "mode": "applyCampaign", "campaigncode": value}, function(data)
		{
			if(data.status)
				document.location.reload();
			else
			{
				var camp = $("#campaignerror");
				camp.fadeOut(1, function() { camp.html(data.message); });
				camp.fadeIn(125);
			}
		});
		return false;
	});
	
	// Adds an empty lens article
	$("#add-empty-lens").click(function()
	{
		$.get("update.asp", {"ajax": "1", "mode": "addEmptyArticle", "articleType": 0}, function(data)
		{
			$("#no-articles-in-cart").hide();
			$("#lenses").append(data);
			$("#lenses").find(".article").each(enhanceArticleTable);
		});
		return false;
	});
	
	// Adds an empty accessory article
	$("#add-empty-article").click(function()
	{
		$.get("update.asp", {"ajax": "1", "mode": "addEmptyArticle", "articleType": 1}, function(data)
		{
			$("#no-articles-in-cart").hide();
			$("#articles").append(data);
			$("#articles").find(".article").each(enhanceArticleTable);
		});
		return false;
	});
	
	previewBox._create();
});

var previewBox = 
{
	_element: null,
	_hidePending: false,
	_hideDelayed: false,
	_hideTimer: null,
	_create: function() 
	{
		if(previewBox._element!=null) return; 
		previewBox._element = $("<div id='image-preview-box' style='display: none; position: absolute; z-index: 1000; border: 1px solid #999; padding: 3px; background: #fff;'><img src='empty.gif' /></div>");
		document.body.appendChild(previewBox._element[0]);
		previewBox._element.hover(
			function(){ clearTimeout(previewBox._hideTimer); previewBox._hideDelayed = true; },
			function(){ clearTimeout(previewBox._hideTimer); previewBox._hideDelayed = false; if(previewBox._hidePending) previewBox.hide(); }
		);
	},
	show: function(target, src)
	{
		clearTimeout(previewBox._hideTimer);
		previewBox._create();
		var position = $(target).offset();
		var em = previewBox._element[0];
		em.style.top = position.top + "px";
		em.style.left = position.left + "px";
		em.style.display = "block";
		em.childNodes[0].src = src;
	},
	hide: function()
	{
		clearTimeout(previewBox._hideTimer);
		previewBox._hidePending = true;
		if(!previewBox._hideDelayed)
		{
			previewBox._hideTimer = setTimeout(function()
			{
				previewBox._create();
				previewBox._element[0].style.display = "none";
				previewBox._hidePending = false;
			},250);
		}
	}
}


/// Method: updateOrderInformation
///  Invokes an ajax request to get the latest information
///  about the order, to update the order summary (pricing, etc.)
function updateOrderInformation()
{
	/*
	{type: 'refresh', displayPrice: '1068', displayRebate: '0', displayTotalSum: '1068', 
		orderConsumationTime: '90', orderMassDiscount: '0', orderCampaignDiscount: '0', 
		orderHasCampaign: 'false', orderDeliveryTime: '10', orderShippingCost: '45'}
	*/
	$.getJSON("update.asp", {"ajax": "1", "mode": "refresh"}, function(data)
	{
		var frm = document.frmorder;
		$("#ORDERCONSUMATION").html(data.orderConsumationTime||"0"); // in days
		$("#showprice").html(data.displayPrice||"0");
		//$('showrebate').innerHTML = pl[1];
		$("#showtotalsum").html(data.displayTotalSum||"0");
		$("#basketTotalSum").html(data.displayTotalSum||"0");
		
		var campaignRebateRow = $("#campaignrebaterow");
		$("#showcamprebate").html((data.orderCampaignDiscount)||"0");
		$("#showmassrebate").html((data.orderMassDiscount)||"0");
		$("#showshippingcost").html(data.orderShippingCost||"0");
		
		$('#klarnaMonthlyCost').html(data.klarnaMonthlyCost);
		updatePuffBanner();
		
		/*
		if(data.orderHasCampaign=="true") { campaignRebateRow.fadeIn(200); } else { campaignRebateRow.fadeOut(200); }
		var minimumDeliveryTime = parseInt(data.orderDeliveryTime||"0");
		if(parseInt(frm.OrderSubscribe_DaysUntilDelivery.value)<minimumDeliveryTime)
			frm.OrderSubscribe_DaysUntilDelivery.value = minimumDeliveryTime;
		*/
	});
}


/// Method: articleWarning
///  Adds or removes a warning message on an article.
///  For example, positive strength attributes are given a warning message.
function articleWarning(tableCell, parameter, value)
{
	var helpStrings = $(tableCell).find("div.helpstrings");
	var help = helpStrings.find(["div.help-", parameter].join(""));
	if(!value)
	{
		if(help.length>0) help.html("");
	}
	else
	{
		if(help.length==0)
		{
			help = document.createElement("div");
			help.className = ["help-", parameter].join("")
			helpStrings.append(help);
		}
		$(help).html(value.replace(/\n/g,"<br />"));
	}
}


/// Method: runEmptyArticleCleanup
///  Scans the article tables (#lenses and #articles), to find rows without any articles in them.
///  If they aren't the last row, they are removed.
function runEmptyArticleCleanup()
{
	$("div#lenses > table, div#articles > table").each(function()
	{
		var row = $(this);
		if(row.find("table.completearticle").length==0)
		{
			if(row.next().length==0) return;
			row.remove();
		}
	});
}


/// Method: enhanceArticleTable
///  Adds auto-updating behavior to articles, to prevent the need for using update
///  submits to refresh articles and pricing.
function enhanceArticleTable()
{
	var tableCell = this;
	if(tableCell._enhanced) return;
	tableCell._enhanced = true;
	var jqCell = $(tableCell);
	
	//var errorRegion = jqCell.find(".validationtext");
	
	if(true || !jqCell.is(".stubarticle"))
	{	
		/*
		function onFail()
		{
			var found = false;
			var shown = errorRegion.find(".active-validation-error");
			shown.each(function()
			{
				if(found) { $(this).hide(); return; }
				$(this).show();
				found = true;
			});
		};
		
		//var settings = {region: errorRegion, failMessage: "Vänligen fyll i alla parametrar.", onfail: onFail};
		//var settings = { onfail: function(allowScolding) { if(allowScolding) $(this).addClass("error"); }, onsuccess: function() { $(this).removeClass("error"); } };
		*/
		
		//console.log(jqCell.find("select"));
		//console.log($('.paramsel'));
		jqCell.find("select").each(function(){
			$(this).rules("add", {	required:true, 
									messages:{required:"Vennligst fyll inn alle parametre."}});
		});
		//$('.paramsel').rules("add", {required:true, messages:{required:"Vänligen fyll i alla parametrar."}});
	}
	
	// hide refresh links (helpers for no-js users)
	jqCell.find("input.refresh-page").hide();
	
	// Ajax all 'update.asp' links
	jqCell.find('a[href^="update.asp"]').click(function(evt)
	{
		var node = jqCell.parent();
		$.get(this.href + "&ajax=1", function(data)
		{
			if(data=="")
			{
				node.remove();
			}
			else
			{
				node.html(data);
				node.find(".article").each(enhanceArticleTable);
			}
			updateOrderInformation();
			runEmptyArticleCleanup();
		});
		return false;
	});
	
	jqCell.find("img.nonarticle-remove").click(runEmptyArticleCleanup);
	
	jqCell.find("img.paramimage").hover(
	function() { if(this.src.indexOf("empty")==-1) previewBox.show(this, this.src.replace("NANOTHUMB","THUMB")); },
	function() { previewBox.hide(); });
	
	// Ajax all inputs and selects in the article
	jqCell.find("input, select").change(function(e) 
	{
		if(this.value=="") return false;
		
		// 'legacy', i guess.
		if(this.nodeName=="SELECT" && this.options[1].value=="")
			$(this.options[0]).html(this.options[this.selectedIndex].innerHTML);
		
		var info = this.name.match(/article(\d+)_p?(count|aid|\d+)/);
		if(info[1]=="0") info[1] = "-1";
		var positionIndex = jqCell.parent("div")[0].id.match(/^pp_(-?\d+)_(-?\d+)$/i);
		
		
		if(info[2]=="aid") // replace article
		{
			var node = jqCell.parent();
			node.load("update.asp", {"ajax": "1", "mode": "replaceArticle", "aid": info[1], "value": this.value, "row": positionIndex[1], "col": positionIndex[2] }, function()
			{
				node.find(".article").each(enhanceArticleTable);
				updateOrderInformation();
			});
		}
		else // change article parameter
		{
			function onComplete(data)
			{
				if(data.imageUrl) $(["#",info[1],"-",info[2],"-image"].join(""))[0].src = data.imageUrl;
				if(data.price) {
					updateOrderInformation();
					jqCell.find(".articleSubTotal").html(data.price);
				}
				articleWarning(tableCell, data.param, data.warning||"");
			}
			$.getJSON("update.asp", {"ajax": "1", "mode": "changeParam", "aid": info[1], "param": urlSafe(info[2]), "value": urlSafe(this.value), "row": positionIndex[1], "col": positionIndex[2] }, onComplete);
		}
	});
}

