/* Shopping cart logic */

//Take care of IE flicker
if (navigator.appName == "Microsoft Internet Explorer")
	document.execCommand("BackgroundImageCache", false, true);

var ShoppingCart = function() {
	// -------------------------
	// *** Private variables ***
	// -------------------------
	var _editpageUrl;	
	var _dropdown;
	var _dealerdropdowns;
	var _dealerinitialvalues;
	var _optionCheckboxes;
	var _dealerLevelDropdown;
	var _itemsInCartText;
	
	// -----------------------
	// *** Private methods ***
	// -----------------------

	var initDropdown = function(dd) {
		_dealerdropdowns.push(dd);
		_dealerinitialvalues.push(dd.options[0].text);
		
		// Hookup change event
		$(dd).change(function() {
			var args = new Object();
			for(var j = 0; j < _dealerdropdowns.length; j++) {
				args[_dealerdropdowns[j].id] = _dealerdropdowns[j].value;
				if(_dealerdropdowns[j] == this)
					break;
			}
			args["ajax"] = "dealerlocations";

			$.ajax({
				cache: true,
				type: "GET",
				url: location.pathname + location.search,				
				data: args,
				dataType: "json",
				success: function(result) {
					if(result.ID) {
						$("#dealerlist").hide();
						$("#nextbutton").attr("disabled", true);
						// Got more locations
						for(var j = 0; j < _dealerdropdowns.length; j++) {
							if(_dealerdropdowns[j].id == result.ID) {
								populateDropdown(j, result.Values);
								
								for(var k = j + 1; k < _dealerdropdowns.length; k++)
									clearDropdown(k);
									
								break;
							}
						}
					}
					else
						showDealers();
				}
			});
		});
	}

	var clearDropdown = function(index) {
		var dd = $(_dealerdropdowns[index]);
		dd.empty();
		dd.append("<option>" + _dealerinitialvalues[index] + "</option>");
		dd.attr("disabled", true);
	};

	var populateDropdown = function(index, values) {
		clearDropdown(index);
		if(values.length == 0)
			return;

		var dd = $(_dealerdropdowns[index]);
		for(var i = 0; i < values.length; i++)
			dd.append('<option value="' + values[i] + '">' + values[i] + '</option>');
		
		dd.attr("disabled", false);
		_dealerdropdowns[index].selectedIndex = 0;
	};

	var showDealers = function() {
		var args = new Object();
		var selectedOptions = new Array();
		
		for(var j = 0; j < _dealerdropdowns.length; j++) {
			args[_dealerdropdowns[j].id] = _dealerdropdowns[j].value;
		}
		args["ajax"] = "dealers";
		
		for (var i = 0; i < _optionCheckboxes.length; i++)
			if (_optionCheckboxes[i].checked)
				selectedOptions.push(_optionCheckboxes[i].value);
		
		if (_optionCheckboxes.length > 0)
			args["dealerOptions"] = selectedOptions.join();
		
		if (_dealerLevelDropdown != null)
			args["dealerLevel"] = _dealerLevelDropdown.value;
		
		var dealerlist = $("#dealerlist");
		//dealerlist.slideUp("normal");
		dealerlist.hide();
		$.ajax({
			cache: true,
			type: "GET",
			url: location.pathname + location.search,			
			data: args,
			dataType: "json",
			success: function(result) {
				dealerlist.empty();
				if(result && result.length > 0) {
					$.each(result, function(i, item) {
						var html =	'<div class="dealer">' +
									'<input type="radio" name="dealer" value="' + item.ID + '" id="dealer' + item.ID + '"/>' +
									'<label class="DealerLabel" for="dealer' + item.ID + '">' +
									'<div class="dealerstorename">' + item.StoreName + '</div>' +
									'<div class="dealerinfo">' + item.StreetAddress + '<br/>' +
									item.ZipCode + ' ' + item.City + '</div>' +
									'</label>' +
									'</div>';
						dealerlist.append(html);
					});
					//dealerlist.slideDown("slow");
					
//					$("div.dealer", dealerlist).click(function() {
//						
//					});
					$(":radio", dealerlist).click(function() {
						$("#nextbutton").attr("disabled", false);
					});
					
					dealerlist.show();
				}
			}
		});
	}

	var updateCart = function() {
		if(!_dropdown) return;
		
		$.ajax({
			cache: false,
			type: "GET",
			url: location.pathname + location.search,			
			data: { ajax: "getcart" },
			dataType: "json",
			success: function(result, status) {
				if(result && result.length > 0) {
					var totalitems = 0;
					_dropdown.empty();
					$.each(result, function(i, item) {
						_dropdown.append("<option>" + item.Quantity + " X " + item.Remark + "</option>");
						totalitems += item.Quantity;
					});
					var totaltext = '';
					if(_itemsInCartText)
					    totaltext = _itemsInCartText.replace(/%n%/, totalitems);
					else
					    totaltext = totalitems + " item(s) in cart";
					    
					_dropdown.prepend("<option>" + totaltext + "</option>");
					
					if (_dropdown.get(0))
						_dropdown.get(0).selectedIndex = 0;
				}
				_dropdown.attr("disabled", false);
			},
			error: function(request, status, error) {
				_dropdown.empty();
				_dropdown.attr("disabled", true);
			}
		});
		
	};
	
	var findBubble = function(button) {
		var b = $(button);
		var bubble = b.parent().prev().children("div.AddToCartBubble");
		
		if (bubble.length == 0)
			bubble = b.prev().children("div.AddToCartBubble");
		
		return bubble;
	};

	return {
	// -----------------------
	// *** Public methods ***
	// -----------------------

	add : function(id) {
		$.ajax({
			cache: false,
			type: "GET",
			url: _editpageUrl,
			data: { ajax: "addtocart", id: id, q: 1 },
			dataType: "text",
			success: function(result) {
				if(result == "OK")
					updateCart();
				else
					alert("Failed to add to cart. ");
			}
		});
	},
	
	addPimArticle : function(publicationprogid, nodeid, productid, showRelated, relationShoppingCartNode, button) {
		$.ajax({
			cache: false,
			type: "GET",
			url: _editpageUrl,
			data: { ajax: "addPimArticle", pubid: publicationprogid, nodeid: nodeid, productid: productid, q: 1 },
			dataType: "text",
			success: function(result) {
				if(result == "OK") {
					if (showRelated) {
						ShoppingCart.submitToRelation(publicationprogid, productid, relationShoppingCartNode);
					}
					else {
						updateCart();
					}
					
					var bubble = findBubble(button);
					bubble.fadeIn(350);
					bubble.attr("visible", "true");
					setTimeout("$(\"div.AddToCartBubble[@visible='true']\").fadeOut(1100);", 1100);
				}
				else {
					alert("Failed to add to cart. ");
				}
			}
		});
	},

	init : function(itemsInCartText) {
	    _itemsInCartText = itemsInCartText;
		$().ajaxError(function(evt, request, options, error) {
			if (request.status != 0)
				alert("Unexpected error: " + request.status + " " + request.statusText + " " + error);
		});

		_dropdown = $("div#shoppingcart select");
		if(_dropdown.length > 0)
			updateCart();
	},

	initDealerSelector : function() {
		$("#nextbutton").attr("disabled", "true");
		_dealerdropdowns = new Array();
		_dealerinitialvalues = new Array();
		_optionCheckboxes = new Array();
		_dealerLevelDropdown = document.getElementById("dealerLevel");
		
		if (_dealerLevelDropdown) _dealerLevelDropdown.onchange = showDealers;
		
		var ch = document.getElementsByName("dealerOption");
		
		for (var i = 0; i < ch.length; i++) {
			ch[i].onclick = showDealers;
			_optionCheckboxes.push(ch[i]);
		}
		
		for(var i = 0; i < 3; i++) {
			var dd = document.getElementById("sccd_l" + i);
			if(dd) {
				initDropdown(dd);
			}
		}
	},

	print : function() {
		makePrintPage("shoppingcartCheckout", 800, 600, "$(':input').remove();");
	},

	remove : function(btn, artno) {
		var orderline = $(btn).parents("tr:first");
		orderline.hide();
		//_removedarticles.push(artno);

		$.ajax({
			cache: false,
			type: "GET",
			url: location.pathname + location.search,
			data: { ajax: "removefromcart", artno: artno },
			dataType: "text",
			success: function(result) {
				var tbl = orderline.parents("table:first");
				tbl.find("td.totalprice").text(result);
				orderline.remove();
				updateCart();
				
				tbl.children("tbody").children("tr:even").attr("class", "row");
				tbl.children("tbody").children("tr:odd").attr("class", "rowAlt");
				tbl.children("tbody").children("tr:last").attr("class", "");
			}
		});
	},
	
	setEditPage : function(url) {
		_editpageUrl = url;
	},
	
	setRelationPage : function(url) {
		_relationpageUrl = url;
	},
	
	update : function(textbox, artno) {
		var tb = $(textbox);
		var qty = tb.val();
		
		$.ajax({
			cache: false,
			type: "GET",
			url: location.pathname + location.search,
			data: { ajax: "editqty", artno: artno, qty: qty },
			dataType: "json",
			success: function(result) {
				if (parseInt(result.Quantity) != -1) tb.val(result.Quantity);
				
				var orderline = tb.parents("tr:first");
				orderline.find("td.itemprice").text(result.Price);
				orderline.parents("table:first").find("td.totalprice").text(result.TotalPrice);
				
				updateCart();
			}
		});
	},
	
	submitToRelation : function(publicationprogid, productid, relationshoppingcartnode){
	    if(relationshoppingcartnode != null && relationshoppingcartnode.length > 0){
	        $.ajax({
			    cache: false,
			    type: "GET",
			    url: relationshoppingcartnode,
			    data: { ajax: "checkPimRelations", pubid: publicationprogid, productid: productid },
			    dataType: "text",
			    success: function(result) {
				    if(result == "OK"){
						window.location = relationshoppingcartnode + "?pimproductid=" + productid + "&previousPage=" + encodeURIComponent(document.URL);
				    }
				    else {
						updateCart();
				    }
			    }
		    });	        
	    }	    
	}
	
// ShoppingCart end	
}}();
