/// <reference path="jquery-vsdoc.js" />
var litium = {};

// Settings for all product colorboxes
var productColorBoxSettings = {
	transition: "elastic",
	scrolling: false,
	opacity: 0,
	close: ' ',
	width: "662px",
	initialWidth: "662px",
	onComplete: function() { litium.productlist.productLoaded(); },
	onClosed: function() { litium.productlist.productClosed(); }
};

litium.templates = {
	all: (function () {
		var that = {};

		that.init = function () {
			$("a").live("click", function () {
				if (pageTracker) {
					var type = $(this).parent().parent().children("input").val();
					if (type != null && type.indexOf("pdf") != -1) {
						var text = $(this).text();
						if (pageTracker)
							pageTracker._trackPageview("/downloads/" + text);
					}
				}
			});
		}

		that.showErrorMessage = function (target, errorMessage, autoHide) {
			var errorContainer = $(".add-to-cart-error");
			var position = $(target).offset();
			var width = Number($(target).width());

			$(errorContainer).text(errorMessage);

			var posLeft, posTop;
			posLeft = (Number(position.left) + (width / 2)) - (Number($(errorContainer).width()) / 2);
			posTop = (Number(position.top - 15)) - Number($(errorContainer).height());

			$(errorContainer).css("top", posTop + "px");
			$(errorContainer).css("left", posLeft + "px");
			$(errorContainer).fadeIn("normal");

			if (autoHide)
				setTimeout(function () { $(errorContainer).fadeOut("normal"); }, 2500);
		}

		return that;
	})(),

	quickorder: (function () {
		var that = {};

		that.timeout = null;
		that.quantityBox = null;

		that.init = function (quantityBoxId) {
			that.quantityBox = $("#" + quantityBoxId);
			$(document).click(
				function (e) {
					//if(e.target && !$(".search-result-container").has(e.target).length > 0)
					$(".search-result-container").hide();
				}
			);

			$(".search-result-container .footer").remove();

			var box = $("input[id$='m_textBoxArticleNr']");
			var searchFunc = function () {
				setTimeout(
											function () {
												if (that.timeout)
													clearTimeout(that.timeout);

												that.timeout = that.performSearch(box.val());
											},
											250);
			};

			box.keyup(searchFunc);
			box.click(searchFunc);
		},
		that.performSearch = function (searchString) {
			if (searchString) {
				// Search, parameters == search string, show article numer
				App_Code.Site.WebServices.SearchService.Search(searchString, true, -1,
					function (searchResult) {
						if (searchResult.Result.lenght == 0) {
							$(".search-result-container").hide();
							$(".search-result-container ul.result li").remove();
							return;
						}

						$(".search-result-container").show();
						$(".search-result-container ul.result li").remove();
						$("#searchResultItem").tmpl(searchResult.Result).appendTo(".search-result-container ul.result");

						// Collect all product link, add more selectors here to enable more links
						var productLinks = $(".search-result-container ul.result li");

						productLinks.hover(
						  function () {
						  	$(this).addClass("hover");
						  },
						  function () {
						  	$(this).removeClass("hover");
						  }
						)

						// Init colorbox on all productlinks
						if (productLinks.length > 0) {
							// Modify the href on each link element to enable colorbox to load product without framework
							productLinks.each(
								function () {
									$(this).click(
										function (e) {
											e.preventDefault();

											var box = $("input[id$='m_textBoxArticleNr']");
											box.val($(this).children(".number").text());
											$(that.quantityBox).focus();
										}
									);
								}
							);
						}
					}
				);
			}
			else {
				$(".search-result-container").hide();
				$(".search-result-container ul.result li").remove();
			}
		}

		return that;
	})(),
	search: (function () {
		var that = {};

		that.settings = { footerText: "Visa alla träffar" };
		that.timeout = null;

		that.init = function () {
			$(document).click(
				function (e) {
					//if(e.target && !$(".search-result-container").has(e.target).length > 0)
					$(".search-result-container").hide();
				}
			);

			if ($(".search-result-container .footer a").text().trim().length > 0)
				that.settings.footerText = $(".search-result-container .footer a").text();

			var box = $("input[id$='m_textBoxSearchString']");
			var searchFunc = function () {
				setTimeout(
											function () {
												if (that.timeout)
													clearTimeout(that.timeout);

												that.timeout = that.performSearch(box.val());
											},
											250);
			};

			box.keyup(searchFunc);
			box.click(searchFunc);
		},
		that.performSearch = function (searchString) {
			if (searchString && searchString.length >= 3) {
				// Search, parameters == search string, show article numer
				App_Code.Site.WebServices.SearchService.Search(searchString, false, 5,
					function (searchResult) {
						if (searchResult.Result.lenght == 0) {
							$(".search-result-container").hide();
							$(".search-result-container ul.result li").remove();
							return;
						}

						$(".search-result-container").show();
						$(".search-result-container ul.result li").remove();
						$("#searchResultItem").tmpl(searchResult.Result).appendTo(".search-result-container ul.result");

						$(".search-result-container .footer a").attr("href", searchResult.AllHitsLink);
						$(".search-result-container .footer a").text(that.settings.footerText + " (" + searchResult.HitCount + ")");

						// Collect all product link, add more selectors here to enable more links
						var productLinks = $(".search-result-container ul.result li div.name a");

						// Init colorbox on all productlinks
						if (productLinks.length > 0) {
							// Modify the href on each link element to enable colorbox to load product without framework
							productLinks.each(function () { $(this).attr("href", $(this).attr("href") + "?NoFramework=true"); })

							// Set onclick event on every product link to show a colorbox
							productLinks.colorbox(productColorBoxSettings);
						}
					}
				);
			}
			else {
				$(".search-result-container").hide();
				$(".search-result-container ul.result li").remove();
			}
		}

		return that;
	})(),

	include: (function () {
		var that = {};
		var defaults = { iframeHeight: '600px' };

		that.resize = function (iframe, iframeHeight) {
			try {
				iframe.style.height = iframe.contentWindow.document.body.scrollHeight + 'px';
			} catch (e) {
				iframe.style.height = iframeHeight;
			}
		};

		that.init = function (options) {
			///<summary>
			/// Initialises the resizing of iframes in the document.
			/// Parameters: options: { iframeHeight: height declaration, e.g. '600px' }
			///</summary>
			var i;
			var iframe;
			var iframes = document.getElementsByTagName('iframe');
			var settings = jQuery.extend({}, defaults, options);
			var onloadValue = 'litium.templates.include.resize(this, \'' + settings.iframeHeight + '\');'

			for (i = 0; iframe = iframes[i]; i++) {
				iframe.setAttribute('onload', onloadValue);
			}
		};

		return that;
	})(),

	registercustomer: (function () {
		var that = {};
		that.settings = {
			DLSchoolLevelID: "",
			DLCityID: "",
			CBSameAsAboveID: "#checkBoxSamAsAbove",
			LBSchoolsID: "",
			TBAdressID: "",
			TBCityID: "",
			TBPostalCodeID: "",
			TBDeliveryAdressID: "",
			TBDeliveryCityID: "",
			TBDeliveryPostalCodeID: "",
			TBSchoolID: "",
			HFCity: "",
			HFSchool: "",
			DefaultItemTextMissing: "Ej med, ange adress nedan"
		};

		that.CurrentSchools = {};

		that.init = function (options) {
			that.settings = $.extend(that.settings, options);

			// After postback, load city names
			var groupId = $(that.settings.DLSchoolLevelID).val();
			that.loadCityNames(groupId);

			$(options.CBSameAsAboveID).change(
				function () {
					if ($(options.CBSameAsAboveID).is(":checked"))
						that.fillDeliveryAdress();
					else
						that.removeDeliveryAdress();
				}
			);

			$(that.settings.DLSchoolLevelID).change(
				function () {
					var groupId = $(that.settings.DLSchoolLevelID).val();
					that.loadCityNames(groupId);
				}
			);

			$(that.settings.DLCityID).change(
				function () {
					var groupId = $(that.settings.DLSchoolLevelID).val();
					var city = $(that.settings.DLCityID).val();
					var cityName = $(that.settings.DLCityID).children(":selected").text();

					that.loadSchools(groupId, city);
					$(that.settings.HFCity).val(cityName);
				}
			);

			$(that.settings.LBSchoolsID).change(
				function () {
					var schoolId = $(that.settings.LBSchoolsID).val();
					that.loadSchoolAdress(schoolId);
				}
			);
		};

		that.fillDeliveryAdress = function () {
			$(that.settings.TBDeliveryAdressID).val($(that.settings.TBAdressID).val());
			$(that.settings.TBDeliveryCityID).val($(that.settings.TBCityID).val());
			$(that.settings.TBDeliveryPostalCodeID).val($(that.settings.TBPostalCodeID).val());
		};

		that.removeDeliveryAdress = function () {
			$(that.settings.TBDeliveryAdressID).val("");
			$(that.settings.TBDeliveryCityID).val("");
			$(that.settings.TBDeliveryPostalCodeID).val("");
		};

		that.removeAdress = function () {
			$(that.settings.TBAdressID).val("");
			$(that.settings.TBCityID).val("");
			$(that.settings.TBPostalCodeID).val("");
			$(that.settings.TBSchoolID).val("");
		};

		that.loadSchoolAdress = function (schoolId) {
			var loaded = false;
			for (var i = 0; i < that.CurrentSchools.length; i++) {
				if (that.CurrentSchools[i] != null && that.CurrentSchools[i].ID != null && that.CurrentSchools[i].ID == schoolId) {
					$(that.settings.TBAdressID).val(that.CurrentSchools[i].Adress);
					$(that.settings.TBCityID).val(that.CurrentSchools[i].City);
					$(that.settings.TBPostalCodeID).val(that.CurrentSchools[i].PostalCode);
					$(that.settings.TBSchoolID).val(that.CurrentSchools[i].SchoolName);

					$(that.settings.TBDeliveryAdressID).val(that.CurrentSchools[i].DeliveryAdress);
					$(that.settings.TBDeliveryCityID).val(that.CurrentSchools[i].DeliveryCity);
					$(that.settings.TBDeliveryPostalCodeID).val(that.CurrentSchools[i].DeliveryPostalCode);

					if ($(that.settings.CBSameAsAboveID).is(":checked"))
						that.fillDeliveryAdress();

					loaded = true;
				}
			}

			if (!loaded) {
				that.removeAdress();
				that.removeDeliveryAdress();
			}
		};

		that.loadCityNames = function (groupId) {
			if (groupId != "0") {
				App_Code.Site.WebServices.RelationsService.GetUniqueCityNames(groupId,
					function (data) {
						var selectedCity = $(that.settings.HFCity).val();

						$(that.settings.DLCityID).children().remove();
						$(that.settings.DLCityID).append("<option value='0'>" + that.settings.DefaultItemTextMissing + "</option>");
						for (var i = 0; i < data.length; i++) {
							if (selectedCity != null && selectedCity == data[i])
								$(that.settings.DLCityID).append("<option selected='selected'>" + data[i] + "</option>");
							else
								$(that.settings.DLCityID).append("<option>" + data[i] + "</option>");
						}

						// After postback, load schoolnames
						var groupId = $(that.settings.DLSchoolLevelID).val();
						var cityName = $(that.settings.DLCityID).children(":selected").text();
						if (cityName == selectedCity)
							that.loadSchools(groupId, cityName);
					}
				);
			}
			else {
				$(that.settings.DLCityID).children().remove();
				$(that.settings.DLCityID).append("<option value='0'>" + that.settings.DefaultItemTextMissing + "</option>");
			}
		};

		that.loadSchools = function (groupId, city) {
			$(that.settings.LBSchoolsID).children().remove();

			if (groupId != "0") {
				App_Code.Site.WebServices.RelationsService.GetSchoolsByGroupAndCity(groupId, city,
					function (data) {
						that.CurrentSchools = data;
						$(that.settings.LBSchoolsID).append("<option value='0'>" + that.settings.DefaultItemTextMissing + "</option>");
						for (var i = 0; i < data.length; i++) {
							$(that.settings.LBSchoolsID).append("<option value='" + data[i].ID + "'>" + data[i].SchoolName + "</option>");
						}
					}
				);
			}
		};

		return that;
	})(),

	orderHistory: (function () {
		var that = {};

		that.init = function (openedText, closedText) {
			$('.rowlink span').click(function () {
				var $link = $(this);
				$(this).parent().next().slideToggle(200, function () {
					$link.text($(this).is(":visible") ? openedText : closedText);
				});
			});
		};

		return that;
	})()
};

litium.productlist = (function () {
	var that = {};
	var defaults = { title: '' };
	var tabsSettings = { effect: 'fade', fadeOutSpeed: "fast", rotate: true, event: 'dblclick' };
	var slideShowSettings = { autoplay: true, interval: 4500, clickable: false };

	that.settings = defaults;

	/// <summary>
	/// Prepares the product pages functions
	/// </summary>
	that.init = function (options) {
		that.settings = $.extend(options, that.settings);

		// Store title to be able to reset when product closes
		that.settings.title = document.title;

		// set the text in black bar from a hidden input field
		var blackListText = $("input[id*='m_filterTitle']").val();
		if (blackListText != null && blackListText != "") {
			$(".current-filter h1").text(blackListText);
		}
		else {
			blackListText = $("#currentProductBlackListContent").html();
			$(".current-filter").html(blackListText);

			blackListText = $("#companyDescription").html();
			$(".company-description").html(blackListText);
		}

		// Set the onclick event on all add to cart-buttons
		$(".add-to-cart-controls img.button").live('click', function (event) { litium.productlist.showAddToCartBubble(event, this); });

		$(".add-to-cart-error").click(function () { $(this).fadeOut("normal"); });
		$(".add-to-cart-controls .bubble .field-group input").click(function () { $(".add-to-cart-error").fadeOut("normal"); });
		$(".add-to-cart-controls .bubble .field-group input").live("click", function () { $(".add-to-cart-error").fadeOut("normal"); });

		// Set on click on the add to cart-button
		$(".add-to-cart-controls .bubble button").click(
				function (event) {
					event.stopPropagation();
					litium.productlist.addProductToCart(event, this);
					return false;
				}
			);

		var packageBox = $(".add-to-cart-controls .bubble").find("div[id*='m_panelPackage']").find("input");
		var singleBox = $(".add-to-cart-controls .bubble").find("div[id*='m_panelSingle']").find("input");
		packageBox.live("keydown", that.bubbleFieldKeyDown, packageBox);
		singleBox.live("keydown", that.bubbleFieldKeyDown, singleBox);

		// Set on click on main-div to hide any open add to cart-bubbles
		$("#main").click(function () { litium.productlist.hideBubbles(); });

		// Collect all product link, add more selectors here to enable more links
		var productLinks = $(".product-list li .content .content-container .name a").add(".product-list li .image a").add(".top-list a").add(".product-list-large .slide .content h2 a").add(".product-list-large .slide .content .text .readmore a").add(".product-list-large .slide .image a");

		// Init colorbox on all productlinks
		if (productLinks.length > 0) {
			// Modify the href on each link element to enable colorbox to load product without framework
			productLinks.each(function () { $(this).attr("href", $(this).attr("href") + "?NoFramework=true"); })

			// Set onclick event on every product link to show a colorbox
			productLinks.colorbox(productColorBoxSettings);
		}

		// Open current product
		litium.productlist.openProductOnProductPage();

		$.tools.tabs.addEffect("subjectAid", function (tabIndex, done) {
			// hide all panes and show the one that is clicked
			var panes = this.getPanes();
			panes.hide(1,
				function () {
					panes.eq(tabIndex).fadeIn(500);
				}
			);

			// the supplied callback must be called after the effect has finished its job
			done.call();
		});

		// Initialize the slideshow
		$(".slidetabs").tabs(".slideshow .slide", tabsSettings).slideshow(slideShowSettings);
	};

	/// <summary>
	/// When visiting directly on a product page the product will reside in element with id #product, open that in a colorbox.
	/// </summary>
	that.openProductOnProductPage = function () {
		var product = $("#product");
		if (product != null && product.length > 0) {
			var button = $("<button />");
			var settings = { inline: true, href: "#product" };
			$.extend(settings, productColorBoxSettings);

			$(button).colorbox(settings);
			button.click();
		}
	}

	/// <summary>
	/// Calls the webservice to add specified amount of provided prodct
	/// </summary>
	that.addProductToCart = function (event, sender) {
		var container = $(sender).parent();

		// Find boxes with specified amounts
		var packageBox = $(container).find("div[id*='m_panelPackage']").find("input");
		var singleBox = $(container).find("div[id*='m_panelSingle']").find("input");
		var errorContainer = $(".add-to-cart-error");
		var message = $(container).find(".message.loading");
		var messageDone = $(container).find(".message.done");

		var packageAmount = Number(0);
		if (packageBox != null && packageBox.val() != null && packageBox.val() != "")
			packageAmount = Number(packageBox.val());

		// if package amount is 0, set single amount to 1 so 1 product is added if nothing is written i singleBox
		var singleAmount = Number(packageAmount == 0 ? 1 : 0);
		if (singleBox != null && singleBox.val() != null && singleBox.val() != "")
			singleAmount = Number(singleBox.val());

		// Get product id
		var id = $(container).children("input[type='hidden']").val();

		// show loading image
		$(message).fadeIn("normal");

		// Call webservice to att products in cart
		App_Code.Site.WebServices.ECommerceService.AddProductToCart(id, singleAmount, packageAmount,
				function (result) {
					if (result.Successful) {
						// Add was successfull, update number of items in cart
						$(".cart .container .nrarticles").text(result.TotalItemsInCart);
						// fade out the loading image
						setTimeout(
							function () {
								$(message).fadeOut("normal",
									function () {
										$(messageDone).fadeIn("normal");

										var fadeOutElement = $(container);
										if (fadeOutElement.parent().parent().hasClass("addshare"))
											fadeOutElement = $(messageDone);

										setTimeout(function () {
											fadeOutElement.fadeOut("normal", function () {
												$(messageDone).hide();
												$(packageBox).val("");
												$(singleBox).val("");
											});
										}, 2500);
									}
								);

							},
							1000
						);
					}
					else {
						$(message).fadeOut("normal");

						if (!result.AmountValid) {
							litium.templates.all.showErrorMessage(singleBox, result.ErrorMessage, true);
						}
						else {
							litium.templates.all.showErrorMessage(packageBox, result.ErrorMessage, true);
						}
					}
				},
				function (error) { if (console) console.log(error); }
			);
	}

	/// <summary>
	/// Displays the add to cart-bubble that belongs to specified product
	/// </summary>
	that.showAddToCartBubble = function (event, sender) {
		litium.productlist.hideBubbles();

		event.stopPropagation();

		var bubble = $(sender).parent().children(".bubble:first");

		// To prevent bubble from being closed when clicked, run stopPropagation on click
		bubble.click(function (event2) { event2.stopPropagation(); });

		// Calculates the position of the bubble
		var height = bubble.height();
		var width = bubble.width();
		var buttonHeight = $(sender).height();
		var buttonWidth = $(sender).width();

		var position = $(sender).position();

		var top = position.top - height - (buttonHeight - 3); // Last number is some fine tuning of position
		var left = position.left - (width / 2) - 2;

		var packageBox = $(bubble).find("div[id*='m_panelPackage']").find("input");
		var singleBox = $(bubble).find("div[id*='m_panelSingle']").find("input");
		packageBox.keydown(that.bubbleFieldKeyDown, packageBox);
		singleBox.keydown(that.bubbleFieldKeyDown, singleBox);

		bubble.css({ "top": top + "px", "left": left + "px" });
		bubble.show();

		return false;
	}

	that.bubbleFieldKeyDown = function (e) {
		if (!e) e = window.event;
		var code = (e.keyCode) ? e.keyCode : e.which;
		if (code == 13 || code == 3) {
			var bubble = $(e.target).parent().parent();
			var button = bubble.find("button");
			that.addProductToCart(e, button);
			return false;
		}
		else
			return true;
	}

	/// <summary>
	/// Callback method executed when colorbox finished loaded a product
	/// </summary>
	that.productLoaded = function (stuff) {
		var items = $("#product .recommend ul li");
		if (items.length < 1)
			$("#product .recommend").hide();

		$("#product .bubble button").click(
			function (event) {
				event.stopPropagation();
				litium.productlist.addProductToCart(event, this);
				return false;
			}
		);

		document.title = $("#product h1").text();

		that.initAddThis($("#productUrl").val(), $("#product h1").text());
	}

	that.productClosed = function () {
		document.title = litium.productlist.settings.title;
		$("#addthisToolbox").remove();
		$("#product").remove();
	}

	that.initAddThis = function (url, title) {
		var toolBox = $("#addthisToolbox");

		toolBox.append('<a class="addthis_button_compact" addthis:url="' + url + '" addthis:title="' + title + '">Share</a>');
		toolBox.append('<span class="addthis_separator">|</span>');

		// add more services here is needed
		var services = { facebook: "", twitter: "", email: "", favourites: "" };
		for (var s in services) {
			toolBox.append('<a class="addthis_button_' + s + '" addthis:url="' + url + '" addthis:title="' + title + '"></a>');
		}

		toolBox.append('<a class="addthis_button_print"></a>');

		setTimeout(function () { addthis.toolbox("#addthisToolbox"); }, 10);
	}

	that.hideBubbles = function () {
		$(".add-to-cart .add-to-cart-controls .bubble").hide();
		$(".add-to-cart-error").hide();
	}

	return that;
})()
