var specificationFilter = new SpecificationFilter();


/**
 * SpecificationFilter
 * @extends Page
 * @constructor
 */
function SpecificationFilter()
{
	// Call the prototype's constructor
	Page.call(this);

	// Private
	var self					= this,
		dom						= new DOM(),
		selectedProducts		= (controller.getCookie("selectedProducts") != undefined ? json.parse(unescape(controller.getCookie("selectedProducts"))) : {}),
		selectedProductsCount	= (controller.getCookie("selectedProductsCount") != undefined ? controller.getCookie("selectedProductsCount") : 0);

	// Public
	this.compare							= compare;
	this.showSpecificationFilterInformation	= showSpecificationFilterInformation;

	// Constructor
	self.addEventListener(Page.LOADED, applySelect, false);
	self.addEventListener(Page.LOADED, applyProductSelection, false);
	self.addEventListener(Page.LOADED, showSpecificationFilterInformation, false);



	/**
	 * Apply an instance of Select to the "items per page" list
	 */
	function applySelect()
	{
		var itemsPerPage = new Select(
			new ListSelectTarget(dom.getById("specifation_results_paging_top").getFirstByTagName("ul"))
		);

		itemsPerPage.addEventListener(
			Select.CHANGED,
			function(event)
			{
				self.queryString.pagesize = event.target.getValue();

				self.setQueryString();
			},
			false
		);
	}

	/**
	 * Defines selectable products and adds onclick actions
	 */
	function applyProductSelection()
	{
		var selectableProducts = dom.getById("specification_results").getByClassName("selection", "div");

		for (var i = 0; i < selectableProducts.length; i++)
		{
			var checkbox = selectableProducts[i].getFirstByTagName("input");

			if (checkbox != null)
			{
				var productId	= selectableProducts[i].id.substr(8),
					productName	= selectableProducts[i].getByClassName("name", "a")[0].firstChild.nodeValue;

				if (productId in selectedProducts)
				{
					selectProduct(productId, productName);
				}

				checkbox.onclick = (function(selectableProduct, checkbox, productId, productName)
				{
					return function(event)
					{
						if (event == undefined)
						{
							event = window.event;
						}

						if (event.target == undefined)
						{
							event.target = event.srcElement;
						}

						if (checkbox.checked == true)
						{
							if (selectedProductsCount < 3)
							{
								selectProduct(productId, productName);
							}
							else
							{
								// IE6 doesn't respond to just a return false, so explicitly set it to false
								checkbox.checked = false;

								notifyMaxSelection(event, productId, productName);

								return false;
							}
						}
						else
						{
							deselectProduct(productId);
						}

						return null;
					}
				})(selectableProducts[i], checkbox, productId, productName);

				selectableProducts[i].onclick = (function(selectableProduct, checkbox, productId, productName)
				{
					return function(event)
					{
						if (event == undefined)
						{
							event = window.event;
						}

						if (event.target == undefined)
						{
							event.target = event.srcElement;
						}

						if (event.target == selectableProduct)
						{
							checkbox.checked = !checkbox.checked;

							if (checkbox.checked == true)
							{
								if (selectedProductsCount < 3)
								{
									selectProduct(productId, productName);
								}
								else
								{
									checkbox.checked = !checkbox.checked;

									notifyMaxSelection(event, productId, productName);

									return false;
								}
							}
							else
							{
								deselectProduct(productId);
							}
						}

						return null;
					}
				})(selectableProducts[i], checkbox, productId, productName);
			}

			listSelectedProducts();
		}

		/**
		 * Apply rules on selection and add cookie
		 * @param {Number} productId the id of the product
		 * @param {String} productName the productname
		 */
		function selectProduct(productId, productName)
		{
			var product = dom.getById("product_" + productId);

			if (product != null)
			{
				product.addClass("selected");

				var checkBox = product.getFirstByTagName("input")

				if (checkbox != null)
				{
					checkBox.checked = true;
				}
			}

			if (productId in selectedProducts == false)
			{
				selectedProducts[productId] = productName;
				selectedProductsCount++;

				controller.setCookie("selectedProducts", json.stringify(selectedProducts));
				controller.setCookie("selectedProductsCount", selectedProductsCount);

				listSelectedProducts();
			}
		}

		/**
		 * Deselects a product
		 * @param {Number} productId the id of the product
		 */
		function deselectProduct(productId)
		{
			var product	= dom.getById("product_" + productId);

			if (product != null)
			{
				product.removeClass("selected");

				var checkBox = product.getFirstByTagName("input")

				if (checkbox != null)
				{
					checkBox.checked = false;
				}
			}

			if (productId in selectedProducts)
			{
				delete selectedProducts[productId];
				selectedProductsCount--;

				controller.setCookie("selectedProducts", json.stringify(selectedProducts));
				controller.setCookie("selectedProductsCount", selectedProductsCount);

				listSelectedProducts();
			}
		}

		/**
		 * Builds a list with selected products
		 */
		function listSelectedProducts()
		{
			if (dom.getById("specification_results_comparison_selectedproducts", true) != null)
			{
				dom.getById("specification_results_comparison_selectedproducts").remove();
			}

			if (selectedProductsCount > 0)
			{
				var selectedProductsList = dom.create("ul");

				for (var productId in selectedProducts)
				{
					selectedProductsList.appendChild(
						dom.create(
							"li",
							null,
							[
								dom.create(
									"a",
									{
										href	: "#",
										onclick	: (function(productId)
										{
											return function()
											{
												deselectProduct(productId);

												return false;
											}
										})(productId)
									},
									[
										selectedProducts[productId]
									]
								)
							]
						)
					);
				}

				var selectedProductsContainer = dom.create(
					"div",
					{
						id : "specification_results_comparison_selectedproducts"
					},
					[
						dom.create(
							"h4",
							null,
							[
								"Te vergelijken producten ",
								dom.create(
									"span",
									null,
									[
										"(maximaal 3)"
									]
								)
							]
						),
						selectedProductsList
					]
				);

				dom.getById("specification_results_comparison_bottom").appendChild(selectedProductsContainer);
			}
		}

		/**
		 * Notifies the user about a max selection
		 * @param {Object} event The event that triggered this function.
	 	 * @param {Number} selectedProductId the selected product id
	 	 * @param {String} selectedProductName the selected productnam.
		 */
		function notifyMaxSelection(event, selectedProductId, selectedProductName)
		{
			var selectedProductsList	= dom.create("ul"),
				actionBox				= null;

			for (var productId in selectedProducts)
			{
				selectedProductsList.appendChild(
					dom.create(
						"li",
						null,
						[
							dom.create(
								"a",
								{
									href	: "#",
									onclick	: (function(productId, selectedProductId)
									{
										return function()
										{
											deselectProduct(productId);

											selectProduct(selectedProductId, selectedProductName);

											actionBox.close();

											return false;
										}
									})(productId, selectedProductId, selectedProductName)
								},
								[
									selectedProducts[productId]
								]
							)
						]
					)
				);
			}

			actionBox = new ActionBox(
				"Waarschuwing",
				[
					dom.create(
						"p",
						null,
						[
							getVousOuTu("U", "je") + " kunt maximaal 3 producten vergelijken. Om dit product te selecteren, dien" + getVousOuTu("t u", " je") + " eerst een ander product uit " + getVousOuTu("uw", "je") + " selectie te verwijderen."
						]
					),
					selectedProductsList
				],
				true
			);

			actionBox.show(event.target);
			actionBox.setPosition((event.pageX ? event.pageX : event.clientX + document.documentElement.scrollLeft + document.body.scrollLeft), (event.pageY ? event.pageY : event.clientY + document.documentElement.scrollTop + document.body.scrollTop));
		}
	}

	/**
	 * Function for comparison of mulitple products
	 */
	function compare(specificationProfileShopId)
	{
		var url = "/vergelijken/?";

		for (var productId in selectedProducts)
		{
			url += "product[]=" + productId + "&";
		}
		url += "specificationprofileshopid="+specificationProfileShopId;

		location.href = url;
	}

	/**
	 * show the specification description in an actionbox and the specificationlink in an infobox
	 */

	function showSpecificationFilterInformation()
	{
		if (!dom.getById("specification_filter"))
		{
			return false;
		}

		var informationIcons = dom.getById("specification_filter").getElementsByTagName("img");

		var socket					= new Socket(),
			requestResult		 	= null,
			actionBox				= null,
			infoBox					= null;

		for (var i = 0; i < informationIcons.length ;i++)
		{
			var informationIcon = dom.extend(informationIcons[i]);
			if (informationIcon.title != "" )
			{
				informationIcon.title = "";
			}

			if (informationIcon.hasClass("info")) //informationicons
			{
				var aSpecificationFilterDescriptions = informationIcon.parentNode.id.split("_");
				if(aSpecificationFilterDescriptions.length > 2)
				{
					var specificationFilterId = aSpecificationFilterDescriptions[1];
					var specificationProfileId = aSpecificationFilterDescriptions[2];

					informationIcon.onclick = (function(specificationFilterId,specificationProfileId) {
							return function(event) 
							{
		if (event == undefined)
		{
			event = window.event;
		}

		if (event.target == undefined)
		{
			event.target = event.srcElement;
		}

								actionBox = new ActionBox(
			"Even geduld " + getVousOuTu("alstublieft", "alsjeblieft") + "...",
			[
				dom.create(
					"div",
					{
												className : "actionbox_content_loading"
					},
					[
						"Wordt geladen..."
					]
				)
			],
									true
		);

		socket.addEventListener(Socket.LOADED, function(event)
		{
			if (socket.getStatus() == 200)
			{
				// Evaluate the response
				try
				{
					eval(event.target.getResponseText());
				}
				catch(error)
				{
											actionBox.setTitle("De informatie kon niet worden geladen");
											actionBox.setContent([
												dom.create(
													"div",
													{
														className : "actionbox_content_loading_error"
													},
													[
														"Helaas kon de informatie niet worden geladen. Onze excuses voor het ongemak."
													]
												)
											], true);
				}

				requestResult = result;
										actionBox.setTitle(requestResult.title);
										actionBox.setContent(requestResult.content);
			}
			else
			{
										actionBox.setTitle("De informatie kon niet worden geladen");
										actionBox.setContent([
					dom.create(
						"div",
						{
													className : "actionbox_content_loading_error"
						},
						[
							"Helaas kon de informatie niet worden geladen. Onze excuses voor het ongemak."
						]
					)
				], true);
			}

			return null;
		});

		if (specificationProfileId)
		{
			socket.request(
										"/keuzehulp/"+specificationProfileId+"/?specificationid=" + specificationFilterId,
				{
											actionbox : (new Date()).getTime()
				}
			);
		}
		else
		{
			socket.request(
										"/keuzehulp/?specificationid=" + specificationFilterId,
				{
											actionbox : (new Date()).getTime()
				}
			);
		}

								actionBox.show(event.target);
								actionBox.setPosition((event.pageX ? event.pageX : event.clientX + document.documentElement.scrollLeft + document.body.scrollLeft), (event.pageY ? event.pageY : event.clientY + document.documentElement.scrollTop + document.body.scrollTop));
								return false;
	}
						}
					)(specificationFilterId,specificationProfileId);
				}
			}
		}
	}
}
// Inheritance
SpecificationFilter.prototype = new Page();
controller.setPageObject(specificationFilter);
