/* Tests and proposals for shop basket functionality */

var Basket = {
	
	/*	
		add(productId, Billed url, titel, teaser (kort tekst), antal, optionId, optionName, pris)
	*/

	/* main basket div */
	content_div: 'r_basket_content',
	
	/* product_count, total_price */
	html_basket_summary: '<span id="info">Indkøbskurv: <b>#product_count#</b> varer Samlet pris : <b>#total_price#</b></span><a class="r_basket_button_f7f7ef" href="/catalog/basket.php"><span><span><span><span>Gå til kassen &#187;</span></span></span></span></a>',

	/* */
	html_basket_empty: '',

	/* no variables */
	html_basket_loading:
		'<div class="r_basket_content_item" style="text-align: center;"><img src="/_img/loading.gif" width="16" height="16" style="border: none; float: none;"/></div>',

	/* product_id, product_ident, product_image, product_title, product_teaser, product_no, option_id, option_value_id, option_value_name, price, selects */
	html_basket_item:
		'<div class="r_basket_content_item"><span style="width:35px;float:left;margin:0;"><a href="/catalog/product.php?vid=2&pid=#product_id#"><img src="#product_image#" /></a></span>\n'
		+ '<a href="/catalog/product.php?vid=2&pid=#product_id#"><p class="r_basket_name"><strong>#product_title#</strong> #product_teaser#</p></a>\n'
		+ ' <b class="ellipsis ellipsis_f7f7ef"></b><p class="r_basket_amount">#product_no# stk</p><p class="r_basket_options">#option_value_name#</p>\n'
		+ ' <span><p class="r_basket_tools">\n'
		+ '<a href="#" onclick="#onclick_edit#" class="r_basket_tools_edit">ret</a> | <a href="#" onclick="#onclick_del#" class="r_basket_tools_delete">slet</a>\n'
		+ '</p><p class="r_basket_price">DKK #price#</p></span></div>\n'
		+ '<div class="r_basket_content_item_edit" id="r_edit_#product_ident#" style="display: none;"><p>#selects#</p><div>\n'
		+ '<a href="Annuller" onclick="#onclick_edit_cancel#">Annuller</a><b><a href="#" onclick="#onclick_edit_ok#">Ok</a></b></div></div>\n'
		+ '<div class="r_basket_content_item_delete" id="r_delete_#product_ident#" style="display: none;"><p>Vil du slette dette produkt?</p><div>\n'
		+ '<a href="Annuller" onclick="#onclick_del_cancel#">Annuller</a>\n'
		+ '<b><a href="#" onclick="#onclick_del_ok#">Ok</a></b></div></div><div class="clear"><br></div>\n',
//		+ '<hr />\n',

	
	global_discount: 0,
	
	freight: 0, // Freight price
	
	appeared: false, // Has the basket yet appeared
	
	products: [], // Array of products
	
	/*
		Adds a product (or updates existing product), and returns product object
		optionList: [[optionsId, "optionsName"], [[optionsValueId, "optionsValueName", priceAdd, selected], ... ]]
	*/
	add: function(id, erezId, title, teaser, no, price, optionList) {
		
		var product = new Basket.Product();
			
		product.id = id;
		product.erezId = erezId;
		product.title = title;
		product.teaser = teaser;
		product.no = no;
		product.price = price;
		product.optionList = optionList;
		product.image = ( product.erezId ? "http://erez.1px.com/erez4/erez?src=" +  product.erezId  + "&tmp=risteriet_basket" : "" );
		
		var option = product.getSelectedOption();
		
		var newProduct = true; // Is this a new product (or increase of existing product)
		
		for (var i=0; i < Basket.products.length; i++) {				
			
			var thisOption = Basket.products[i].getSelectedOption();
			
			if (newProduct && (Basket.products[i].id == id) && (thisOption.id == option.id) && (thisOption.valueId == option.valueId)) { // Adjust no. of existing product
				newProduct = false; // Not a new product anyway
				Basket.products[i].no = product.no;
				
				product = Basket.products[i]; // Return this product
			}
			
		}
		
		if (newProduct) {
			Basket.products.push(product);
		}
		
		return product;
	},
	
	// Put a product into the pasket (and initialize wait for server response)
	// Use visual effect, unless noEffect is set to true
	put: function(id, optionId, optionValueId, addNo, noEffect) {
		if (optionId == null) optionId = 0;
		if (optionValueId == null) optionValueId = '';
//		if (optionPrevValueId == null) optionPrevValueId = '';
		
		var basket = "r_basket";
		var basketPos = "r_basket_pos";
		var button = "r_product_page_link_" + id;
		var flyer = "r_basket_flyer_" + id;
		
		if (Basket.products.length==0)
		{

			$(Basket.content_div).innerHTML = Basket.html_basket_empty;
			if ($('order_totals')) $('order_totals').innerHTML = '';
//			$("r_basket").show();
		}
		
		if (!noEffect && !addNo) {
			// Start position flyer
			var x = $(button).offsetLeft;
			var y = $(button).offsetTop;
			
			if (document.all) { // IE Measure			
				var p = $(button).offsetParent;
				
				while (p) {
					x += p.offsetLeft;
					y += p.offsetTop;
				
					p = p.offsetParent;
				}			
			}
					
			// Destination position for flyer
			var destX = $(basketPos).offsetLeft;
			var destY = $(basketPos).offsetTop+20;
			
			if (document.all) {
				var p = $(basketPos).offsetParent;
				
				while (p) {
					destX += p.offsetLeft;
					destY += p.offsetTop;
				
					p = p.offsetParent;
				}
			}
			
			// Set flyer at correct start position
			$(flyer).style.left = (x + 3) + "px";
			$(flyer).style.top = (y - 4) + "px";
			
			// Disable button
//			$(button).onclick = function() {return false}; // remove action
//			$(button).style.cursor = "default"; // Set normal cursor
			
			// Display flyer
			$(flyer).style.visibility = "visible";
			
			// Dim down button
			new Effect.Opacity(button, {from: 1.0, to: 0.2, duration: 0.35});
			
			// Move flyer
			new Effect.Move(flyer, {x: destX, y: destY, mode: 'absolute', transition: Effect.Transitions.sinoidal, duration: 0.7, fps: 50, queue: {position: 'end', scope: flyer}});
			
			// Dim up flyer
			new Effect.Opacity(flyer, {from: 0.2, to: 1.0});
			
			// Size up flyer
			new Effect.Scale(flyer, 512, {scaleX: true, scaleY: false, scaleContent: false, duration: 0.7});
			
			// Dim out flyer (after moving has ended)
			new Effect.Opacity(flyer, {from: 1.0, to: 0.0, duration: 0.5, queue: {position: 'end', scope: flyer}});
		}

		// Hack: if addNo is null, the caller is a product button -> animate flyer and blindDown basket item
		if (addNo == null)
		{
			addNo = 1;
			var fromPage = true;
		}
		else
		{
			var fromPage = false;
		}
		
//		if (!noEffect) {
			Basket.insertProductWait(id, optionId, optionValueId, fromPage); // Insert wait placeholder for product to come
			
			if (!Basket.appeared) { // Make sure the whole of the basket only appears once
				Basket.appeared = true;
				
				var el = $(basket).hide();
				new Effect.BlindDown(basket, {delay: 0.7});
			}
//		}

		// Do ajax request
		new Ajax.Request('/catalog/ajax_basket.php?product_id=' + id + "&option_id=" + optionId + "&option_value_id=" + optionValueId + "&no="+addNo, {
		  method:'get',
		  onSuccess: function(transport){
		  	var json = transport.responseText.evalJSON();
		  	
		    if (json.error) { // Error reported by server
		    	alert(json.error);
		    }
		    else { // No error, insert product
		    	if (json.orderTotal!='' && $('order_totals')) { eval(json.orderTotal); } //$('order_totals').innerHTML = json.orderTotal; }
		    	var product = Basket.add(json.id, json.erezId, json.title, json.teaser, json.no, json.price, json.optionList); // Add product to basket
		    	Basket.insertProduct(product); // Draw product in basket
		    	Basket.updateInfo(); // Update info line
		    }
		  },
		  onFailure: function() {
		  	alert("Der skete desværre en fejl, og kurven kunne ikke opdateres.");
		  }
		});

	pageTracker._trackPageview("/checkout/basket");

	},
	
	// Called from change layer, on update/delete of product
	// If product is deleted, newNo will be 0
	updateProduct: function(id, optionId, optionValueId, newOptionValueId, newNo) {
		
		if (optionValueId==null) optionValueId = '';
		if (newOptionValueId==null) newOptionValueId = '';
		
		// Find out how many of this product is already in the basket - the old and new configuration
		var oldProductNo = 0;
		var newProductNo = 0;
		
		for (var i=0; i < Basket.products.length; i++) {				
			
			var thisOption = Basket.products[i].getSelectedOption();
			
			if ((Basket.products[i].id == id) && (thisOption.id == optionId) && (thisOption.valueId == optionValueId)) { // This is the product with the new configuration
				oldProductNo = Basket.products[i].no; // Remember how many there were of these
			}
			
//			if ((Basket.products[i].id == id) && (thisOption.id == optionId) && (thisOption.valueId == newOptionValueId)) { // This is the product with the new configuration
//				newProductNo = Basket.products[i].no; // Remember how many there were of these
//			}
		}
		
		if (optionValueId == newOptionValueId) { // New and old product are the same, just adjust the number on that
			var addNo = newNo - oldProductNo;
			Basket.put(id, optionId, optionValueId, addNo, true);
		}
		else { // Different products, adjust out both
			//var oldAddNo = 0 - oldProductNo; // How many should be added of the old product (i.e. really subtracted!)
			//var newAddNo = newNo - newProductNo; // How many should be added of the new product
			
			var addNo = newNo - oldProductNo;
			var productIdentifier = id; if (optionId>0) productIdentifier += "{"+optionId+"}" + optionValueId;
			var containerId = "r_basket_product_container_" + productIdentifier;
			//$(containerId).hide();
			new Effect.SlideUp(containerId, {duration: 0.3});
			Basket.put(id, optionId, newOptionValueId, newNo, false);
			setTimeout('Basket.put('+id+', '+optionId+', '+optionValueId+', '+(-oldProductNo)+', true);', 1000);
		}
	},
	
	// Draw all of basket (on page creation)
	draw: function() {
		for (var i=0; i<Basket.products.length; i++) {
			Basket.insertProduct(Basket.products[i]);
		}
		
		Basket.updateInfo();
		
		if (Basket.products.length>0)
		{
			$("r_basket").show();
			if ($("basket_submit_btn")) $("basket_submit_btn").show();
			Basket.appeared = true;
		}
		else if (Basket.html_basket_empty!='')
		{
			$(Basket.content_div).innerHTML = Basket.html_basket_empty;
			Basket.appeared = true;
		}
	},
	
	// Updates info line of basket
	updateInfo: function() {
		var totalPrice = 0;
		var productCount = 0;
		
		// Count product price
		for (var i=0; i<Basket.products.length; i++) {
			totalPrice += Basket.products[i].getPrice();
			productCount += Basket.products[i].no;
		}
		
		var html = Basket.html_basket_summary;   //'<span id="info">Indkøbskurv: <b>' + productCount +'</b> varer Samlet pris : <b>' + Basket.formatPrice(totalPrice) + '</b></span><a class="r_basket_button_f7f7ef" href="/catalog/basket.php"><span><span><span><span>Gå til kassen &#187;</span></span></span></span></a>';
		html = html.replace(/#product_count#/ig, productCount);
		html = html.replace(/#total_price#/ig, Basket.formatPrice(totalPrice));
		$("r_basket_total").innerHTML = html;
		
		if (totalPrice>=300) freight_teaser = 'Du får nu leveret gratis' + (Basket.global_discount>0?' og '+Math.round(Basket.global_discount*100)+'% fratrækkes ved køb':'');
		else freight_teaser = (Basket.global_discount>0?Math.round(Basket.global_discount*100)+'% fratrækkes ved køb. ':'') + 'Køb for over 300,- og få leveret gratis.';
		//freight_teaser = (Basket.global_discount>0?Math.round(Basket.global_discount*100)+'% fratrækkes ved køb. ':'') + 'Kampagne! FRI FRAGT i hele September måned.';
		if ($("free_freight_teaser")) $("free_freight_teaser").innerHTML = '<p class="r_basket_options">'+freight_teaser+'</p>';
	},
	
	// Insert waiter in place of product to come (and product placeholder). Later product is filled in upon ajax callback
	insertProductWait: function(productId, optionId, optionValueId, fromPage) {
		var html = Basket.html_basket_loading;
//		html += '<div class="r_basket_content_item" style="text-align: center;">';
//		html += '<img src="/_img/loading.gif" width="16" height="16" style="border: none; float: none;"/>';
//		html += '</div>';
		
		var containerId = "r_basket_product_container_" + productId;
		if (optionId>0) containerId += "{"+optionId+"}" + optionValueId;
		
		if ($(containerId))
		{
			// Product already added to basket
			var div = $(containerId)
			div.innerHTML = html;		
		}
		else
		{
			var div = document.createElement("DIV");
			div.id = containerId;
			div.style.display = (Basket.appeared ? "none" : "block"); // Prepare for effect if basked is visible
			div.innerHTML = html;
			$(Basket.content_div).appendChild(div);

			if (Basket.appeared) { // Only use effect if basket is visible
				if (fromPage) new Effect.BlindDown(containerId, {delay: 0.7});  // correct later -> only blind if products added to basket from page
				else $(containerId).show();
			}
		}
	},
	
	// Inserts product line into basket or updates existing product line
	insertProduct: function(product) {
		var html = Basket.html_basket_item;
		
//		product.image = "http://erez.1px.com/erez4/erez?src=" + ( product.erezId ? product.erezId : "Risteriet/Barista%20tools/ecmknockbox.tif" ) + "&tmp=risteriet_basket";

		var options = product.getSelectedOption();
		var productIdentifier = product.id;
		if (options.id>0) productIdentifier += "{"+options.id+"}" + options.valueId;
		
		var containerId = "r_basket_product_container_" + productIdentifier; // Id of div-container for the whole product line


		if (product.no == 0) { // Product should really be deleted, hide! -> fixed LM
			if ($(containerId)) {
				//new Effect.SlideUp(containerId, {duration: 0.3});
				$(containerId).parentNode.removeChild($(containerId));
				for (var i=0;i<Basket.products.length;i++)
				{
					var opt = Basket.products[i].getSelectedOption();
					if (productIdentifier == Basket.products[i].id + (opt.id>0 ? "{"+opt.id+"}" + opt.valueId : ""))
					{
						Basket.products.splice(i,1);
						break;
					}
				}
				
				if (Basket.products.length==0)
				{
					if ($("basket_submit_btn")) $("basket_submit_btn").hide();
					
					if (Basket.html_basket_empty!='') $(Basket.content_div).innerHTML = Basket.html_basket_empty;
					else $("r_basket").hide();
					
					Basket.appeared = false;
				}
			}
			return;
		}

		if ($("basket_submit_btn")) $("basket_submit_btn").show();

		// Build drop downs..
		var option_select = '\'\'';
		var html_select = '<select id="amount_' + productIdentifier + '">';
		for (var i=1; i<=10; i++) {
			html_select += '<option value="' + i + '"' + (product.no == i ? ' selected="selected"' : '') +'>' + i + ' stk.</option>';
		}
		html_select += '</select>';
		
		if (product.optionList.length>0)
		{
			option_select = '$(\'option_' + productIdentifier + '\').value';
			html_select += ' : <select id="option_' + productIdentifier + '">';
			for (var i=0; i<product.optionList[1].length; i++) {
				var optionValueId = product.optionList[1][i][0];
				var optionValueName = product.optionList[1][i][1];
				var optionPriceAdd = product.optionList[1][i][2];
				var optionSelected = product.optionList[1][i][3];
				html_select += '<option value="' + optionValueId +'"' + (optionSelected ? ' selected="selected"' : '') + '>' +  optionValueName + '</option>';
			}
			html_select += '</select>';
		}


		// onclick URLs..
		var onclick_edit = 'new Effect.toggle($(\'r_edit_' + productIdentifier + '\'),\'blind\', {duration:.3}) ;return false;';
		var onclick_del = 'new Effect.toggle($(\'r_delete_' + productIdentifier + '\'),\'blind\', {duration:.3}) ;return false;';
		var onclick_edit_ok = 'Basket.updateProduct(' + product.id + ',\'' + options.id + '\',\'' + options.valueId + '\',' + option_select + ',' + '$(\'amount_' + productIdentifier + '\').value); return false;';
		var onclick_edit_cancel = 'new Effect.toggle($(\'r_edit_' + productIdentifier + '\'),\'blind\', {duration:.3}) ;return false;';
		var onclick_del_ok = 'Basket.updateProduct(' + product.id + ',\'' + options.id + '\',\'' + options.valueId + '\',\'' + options.valueId + '\', 0); return false;';
		var onclick_del_cancel = 'new Effect.toggle($(\'r_delete_' + productIdentifier + '\'),\'blind\', {duration:.3}) ;return false;';

		
		// Main product line
		html = html.replace(/#product_id#/ig, product.id);
		html = html.replace(/#product_ident#/ig, productIdentifier);
		html = html.replace(/#product_image#/ig, product.image);
		html = html.replace(/#product_title#/ig, product.title);
		html = html.replace(/#product_teaser#/ig, product.teaser);
		html = html.replace(/#product_no#/ig, product.no);
		html = html.replace(/#option_id#/ig, options.id);
		html = html.replace(/#option_value_id#/ig, options.valueId);
		html = html.replace(/#option_value_name#/ig, product.getSelectedOption().valueName );
		html = html.replace(/#price#/ig, Basket.formatPrice(product.getPrice()) );
		html = html.replace(/#selects#/ig, html_select);

		html = html.replace(/#onclick_edit#/ig, onclick_edit);
		html = html.replace(/#onclick_del#/ig, onclick_del);
		html = html.replace(/#onclick_edit_ok#/ig, onclick_edit_ok);
		html = html.replace(/#onclick_edit_cancel#/ig, onclick_edit_cancel);
		html = html.replace(/#onclick_del_ok#/ig, onclick_del_ok);
		html = html.replace(/#onclick_del_cancel#/ig, onclick_del_cancel);

		if ($(containerId)) { // The product container is there, fill it in
			$(containerId).innerHTML = html;
		}
		else {
			var div = document.createElement("DIV");
			div.id = containerId;
			div.innerHTML = html;
			$(Basket.content_div).appendChild(div);
		}
	},
	
	// Return formatted version of price
	formatPrice: function(price) {
		var decPart = "-"; // Use line for decimal if zero
		
		// Decimal part
		if (price != parseInt(price)) { // Decimal part is not 0
			decPart = Math.round((price - parseInt(price)) * 100);
		}
		
		// Integer part
		var intPart = parseInt(price) + "";
		intPart = intPart.replace(new RegExp("\d\d\d$"), ".$1");
		
		// Add thousand separator
		if (typeof(intPart) != "undefined") {
			sep = ".";
			z = "";
		    // reverse the digits. regexp works from left to right.
		    for (i=intPart.length-1;i>=0;i--)
		      z += intPart.charAt(i);
		    // add seperators. but undo the trailing one, if there
		    z = z.replace(/(\d{3})/g, "$1" + sep);
		    if (z.slice(-sep.length) == sep)
		      z = z.slice(0, -sep.length);
		    intPart = "";
		    // reverse again to get back the number
		    for (i=z.length-1;i>=0;i--)
		      intPart += z.charAt(i);
		  }
		
		return intPart + "," + decPart;
	},
	
	// Class: Product
	Product: function() {
		
		// Return total price
		this.getPrice = function() {
			var price = this.price; // Base price
//			price += this.getSelectedOption().priceAdd; // Add extra for option
			price *= this.no; // Times selected items
			
			return price;
		},
		
		// Return 
		this.getSelectedOption = function() {
			var option = {
				id: 0,
				name: '',
				valueId: '',
				valueName: '',
				priceAdd: 0
			};
			
			if (this.optionList.length>0)
			{
				option.id = this.optionList[0][0];
				option.name = this.optionList[0][1];
				var options = this.optionList[1];
				
				for (var i=0; i<options.length; i++) {
					if (options[i][3]) { // Selected, take this value
						option.valueId = options[i][0];
						option.valueName = options[i][1];
						option.priceAdd = options[i][2];
					}
				}
			}
			
			return option;
		}
	}
	
};

function bumpPrice(obj, pid)
{
	var container = $('version_price_container_'+pid);
	var price = $('version_price_'+pid+'-'+(obj.selectedIndex+1));
	
	for (var i=0; i<container.childNodes.length;i++)
	{
		$(container.childNodes[i].id).hide();
	}
	price.show();
}
