/**
 * configuration
 */

		/** basket: 'BlokkerB2C/static/dummy/basket.xml' **/
		/** handler: basket modified and basketDelete added by IBM (DCOL)  **/
var BLOKKER = {
	copy : {
		addRecipient : 'Nog een ontvanger',
		closeTab : 'Sluiten'
	},
	handler : {
		basket : 'AjaxBasketView?storeId=10001',
		basketDelete : 'OrderItemDelete'
	},
	swf : {
		avenirLTSTD65Medium : portDomainPath + "/webapp/wcs/stores/BlokkerB2C/static/swf/avenirltstd65medium.swf",
		avenirLTSTD35Light : portDomainPath + "/webapp/wcs/stores/BlokkerB2C/static/swf/avenirltstd35light.swf"
	}
};

/**
 * application
 */

$(function() {
	$("body").addClass("js_active");
	window.isIE6 = /msie 6/i.test(navigator.userAgent)? true:false;
	BLOKKER.initTools();
	BLOKKER.initHelpPopups();
	BLOKKER.sifr.pageload();
	BLOKKER.initPrices();
	BLOKKER.button.init();
	BLOKKER.enhanceTables();
	BLOKKER.splitLists();
	BLOKKER.enhanceFaqs();
	BLOKKER.enhanceForms();
	window.setTimeout(function() { BLOKKER.enhanceProducts(); }, 1000);
	window.setTimeout(function() { BLOKKER.equalizeBoxes(); }, 100);
	BLOKKER.component('thumb', 'basket');
	BLOKKER.component('order_frame', 'order');
	BLOKKER.component('send_to_friend', 'sendToFriend');
	BLOKKER.component('comparison_legend', 'compare');
	BLOKKER.component('faqlist', 'faqFeedback');
	BLOKKER.component('product_added_to_basket', 'crossSalesBasket');
	BLOKKER.component('PD_image', 'imageViewer');
	BLOKKER.activeLabels.init();
	BLOKKER.productOptions();
	BLOKKER.hoverable();
	BLOKKER.gardenSelection();
	BLOKKER.buttonForClang.init();
});

// initialise component by id
BLOKKER.component = function (id, obj) {
	id = document.getElementById(id);
	if (id) {
		BLOKKER[obj].init(id);
	}
};

// replace (submit) buttons
BLOKKER.button = {
	init : function () {
		$("input.custom[type=submit], input.custom[type=reset]").each(function () {
			BLOKKER.button.replace($(this));
		});
	},
	replace : function (origin) {
		var toAnch = "";
		if ( origin.attr("toAnch") != undefined ) {
			toAnch = origin.attr("toAnch");
		}
		var replacement = jQuery('<a href="#'+ toAnch +'"><span><span>' + origin.val() + '</span></span></a>');
		replacement.attr({
			title: origin.attr("title"),
			className: origin.attr("class")
		});
		if (origin.attr("name") != undefined) {// Add submit name/value pair to rel attribute
			replacement.attr("rel", origin.attr("name")+'|'+origin.attr("value"));
		}
		origin.css({ display: 'none' });
		origin.after(replacement);
		if(origin.attr("type") == "submit") {
			if (origin.attr("onclick") != undefined) {// Add submit name/value pair to rel attribute
				
				
				/**
					IE and Firefox seem not support element.attr("onclick"). It is giving a function for IE and a string for Firefox.
					So .length gives a different result too ( 0 for the function, something for the string).
				**/
				if(origin.attr("onclick").length != 0) {

					replacement.attr("onclick", origin.attr("onclick"));
				} else {
				
					replacement.bind("click", origin.attr("onclick"));
				} 
			}
			else {
				replacement.click(function(e) {
	
					/*
					if ($(this).attr("rel") != undefined) {
						var pair = $(this).attr("rel").toString().split("|");
						$(this).parents("form").append('<input type="hidden" name="'+ pair[0] +'" value="'+ pair[1] +'"></input>');
					}
					*/ 
					BLOKKER.button.submitClick(this);
					$(this).parents("form").submit();
					e.preventDefault();
				});
			}
			origin.remove();
		} else {
			replacement.click(function(e) {
				$(this).parents("form").reset();
				e.preventDefault();
			});
		}
		return true;
	},
	submitClick : function (el) {
		el = $(el);
		if (el.attr("rel") != undefined) {
			var pair = el.attr("rel").toString().split("|");
			el.parents("form").append('<input type="hidden" name="'+ pair[0] +'" value="'+ pair[1] +'"></input>');
		}
	}
};


// replace (submit) buttons
BLOKKER.buttonForClang = {
	init : function () {
		$("input.clangSubmitButton[type=submit]").each(function () {
			BLOKKER.buttonForClang.replace($(this));
		});
	},
	replace : function (origin) {
		origin.mouseover(function(){
			origin.addClass("clangButtonOver");
		});
		origin.mouseout(function() {
			origin.removeClass("clangButtonOver");
		});
		
		
	}
};


// page tools (print, send, etcetera)
BLOKKER.initTools = function() {
	// fix the H1 when top-right floated tools are present
	var t = $("#main_content .actionlist.floating");
	if(t.get(0)) $("h1" ,t.parent()).css({ marginRight: "6.3em" });
	// print button
	$("a.icon.print").click(function(e) {
		window.print();
		e.preventDefault();
	});
}

BLOKKER.gardenSelection = function() {
	var self = this;
	this.classNamesGarden = ["", "garden_collection_m", "garden_collection_l", "garden_collection_xl", "garden_collection_xxl", "garden_collection_xxxl"];
	this.menuGarden = $("#garden_selector select");
	this.updateGarden = function() { 
		var index = this.menuGarden.attr("selectedIndex") || 0;
		var indicator = $(".garden_collection", this.menuGarden.parent());
		indicator.attr({ className: "garden_collection " + self.classNamesGarden[index] });
		var checkbox = $(".garden_selector_checkbox");
		checkbox.attr("value", this.menuGarden.attr("value"));
	}
	this.menuGarden.change(function() { self.updateGarden(); });
	this.updateGarden();
}

// help popups (TODO: iframe behind it, for IE6 versus flash, SELECT elements and the like...
BLOKKER.initHelpPopups = function(root) {
	var self = this;
	if(!root) root = $(document);
	this.targetPopup = null;
	this.underlay = jQuery('<iframe id="underlay" border="0" frameborder="0" src="javascript:false;" ></iframe>');
	$("body").append(this.underlay);
	this.open = function(sourceLink) {

		
		this.sourceLink = sourceLink;
		this.targetPopup = $("#" + sourceLink.attr("href").split("#")[1]);
		this.targetPopup.css({ top: sourceLink.offset().top + "px", left: sourceLink.offset().left + sourceLink.width()/2 + "px" });
		this.underlay.css({ top: sourceLink.offset().top  + "px", left: sourceLink.offset().left + sourceLink.width()/2 + "px" });
		this.arrow = $(".arrow", this.targetPopup);
		this.updatePosition();
		$(window).bind("scroll", this.updatePosition);
	};
	this.close = function() {
		var self = this;
		if(!this.targetPopup) return;
		this.targetPopup.css({ left: "-3000em" });
		this.underlay.css({ left: "-3000em" });
		this.targetPopup = null;
		$(window).unbind("scroll", this.updatePosition);
	};
	this.updatePosition = function() {
		//DC fix to lift up the popup a little bit
		var topOffset = this.sourceLink.offset().top;
		topOffset = topOffset - 37;
		//end DC fix
		var popupHeight = this.targetPopup.get(0).offsetHeight;
		var arrowHeight = this.arrow.get(0).offsetHeight;
		var canvasBottom = (document.documentElement.scrollTop || document.body.scrollTop) + document.documentElement.clientHeight;
		var popupBottom = topOffset + popupHeight;
		var offset = (popupBottom > canvasBottom) ? (popupBottom - canvasBottom) : 0;
		if(offset > popupHeight - arrowHeight) offset = popupHeight - arrowHeight;
		this.targetPopup.css({ top: topOffset - offset + "px" });
		this.underlay.css({ top: topOffset - offset + "px" });
		this.underlay.height(this.targetPopup.get(0).offsetHeight).width(this.targetPopup.get(0).offsetWidth);
		this.arrow.css({ top: offset + "px" });
	};
	$("a.help", root).focus(function(e) {
		self.close();
		self.open($(this));
		//e.preventDefault();
	}).blur(function() { self.close(); }).each(function() {
		$("select, input, textarea", $(this).parent()).focus(function() {
			self.open($("a.help", $(this).parent()));
		}).blur(function() { self.close(); });
	}).click(function(e) {
		$(this).focus();
		e.preventDefault();
	});
}

// replace prices with nice graphics
BLOKKER.initPrices = function() {
	$("div.price .customprice, div.price.customprice").each(function() {
		var number = $("span", $(this)).text() || $(this).text();
		number = number.replace(/(^\s+|\s+$)/g, ""); // remove whitespace
		if(! isNaN(parseInt(number))) {
			var container = jQuery('<span class="price_rendered"></span>');
			var fraction = false;
			for(var i = 0; i < number.length; i++) {
				var digit = number.charAt(i);
				if(digit == "-") var className = "pdash";
				else if(digit == "." || digit == ",") {
					fraction = true;
					container.append('<span class="dot"></span>');
					continue;
				}
				else className = "p" + digit + (fraction ? "b" : "");
				container.append('<span class="' + className + '"></span>');
			}
			if($(this).get(0).tagName == "DEL") container.append('<span class="strike"></span>');
			$(this).append(container);
		}
	});
};

// enhance tables
BLOKKER.enhanceTables = function(root) {
	if(!root) root = $(document);
	$("table.enhanced", root).each(function() {
		$("td:first-child, th:first-child", $(this)).addClass("first");
		$("td:last-child, th:last-child", $(this)).addClass("last");
		// hover state on rows
		$("tbody tr", $(this)).hover(
			function() {
				$(this).addClass("hover");
				$(".button", $(this)).addClass("ie6sux"); // anti-traumatize IE6
			},
			function() {
				$(this).removeClass("hover");
				$(".button", $(this)).removeClass("ie6sux"); // anti-traumatize IE6
			}
		);
	});
	$(".striped tr:odd").addClass("odd");
};

// enhance products photo view
BLOKKER.enhanceProducts = function() {
	$(".product").hover(
		function() { $(this).addClass("hover"); },
		function() { $(this).removeClass("hover"); }
	);
};

// split designated lists into multiple ones
BLOKKER.splitLists = function(root) {
	var self = this;
	if(!root) root = $(document);
	var numberOfColumns = 3;
	$(".splittedlist", root).each(function() {
		var items = $(this).children();
		var itemCount = 0;
		var itemsPerColumn = Math.floor(items.length/numberOfColumns);
		var itemSpares = items.length % numberOfColumns;
		var columns = jQuery('<div class="columns"></div>');
		for(var i = 0; i < numberOfColumns; i++) {
			if($(this).get(0).tagName == "OL")
				columns.append('<ol class="column" start="' + (itemCount + 1) + '"></ol');
				else columns.append('<ul class="column"></ul>');
			for(var j = 0; j < itemsPerColumn; j++) {
				columns.children().eq(i).append(items.eq(itemCount));
				itemCount++;
			}
			if(itemSpares > 0) {
				columns.children().eq(i).append(items.eq(itemCount));
				itemCount++;
				itemSpares--;
			}
		}
		$(this).replaceWith(columns);
	});
};

// equalize boxes in a collection of elements
BLOKKER.equalizeBoxes = function(root) {
	var self = this;
	if(!root) root = $(document);
	this.setHeight = function(obj) {
		var h = 0;
		obj.each(function() { h = Math.max(h, $(this).get(0).offsetHeight); });
		obj.each(function() {
			var p = parseInt($(this).css("paddingTop")) + parseInt($(this).css("paddingBottom"));
			$(this).css({ minHeight: (h - p) + "px" });
			// compensate for stubborn IE6
			if(window.isIE6) $(this).css({ height: (h - p) + "px" });
		});
		// tickle DOM, for some browser
		$("body").addClass("tickled");
	};
	$(".equalize", root).each(function() {
		self.setHeight($(".equal", $(this)));
	});
};

// make product detail images and video appear in page
BLOKKER.imageViewer = {
	init : function () {
	
		var flashvars = {
			autostart:"true"
		}
		var params = {
			allowFullScreen: "true"
		};
		var attributes = {
			name: "flvplayer"
		};
		
		swfobject.embedSWF("BlokkerB2C/static/swf/player.swf", "flvplayer", 440, 440, "7.0.0", false, flashvars, params, attributes);	
		var player = document.getElementById("flvplayer");
		var playerContainer = document.getElementById("flvplayerContainer");
		playerContainer.style.display = "none";
		var hasFlash = swfobject.hasFlashPlayerVersion("9.0.28");

		$("#PD_visual a[rel='product-thumb']").click(function (e) {
		
			var gallery = $("#PD_visual");
			var thumbs = $("a[rel=product-thumb]", gallery);
			thumbs.removeClass("selected");
			$(this).addClass("selected");
			if(thumbs.get(0) == this)  {
				gallery.removeClass("no_overlays"); 
			} else  { gallery.addClass("no_overlays"); }

			if ($(this).attr("lb:videohref")) {
				if (hasFlash) {
					if (player  && playerContainer.style.display == "none") {
						while(playerContainer.style.display != "block" ) {
							playerContainer.style.display = "block";
						}
					setTimeout("document.getElementById('flvplayer').sendEvent('LOAD', '"+$(this).attr('lb:videohref')+"')",500);
					 }
				}
			} else {
				$("#PD_image").attr("src", this.href);
				if (hasFlash) {
					if (player && playerContainer.style.display == "block") {
						setTimeout("document.getElementById('flvplayer').sendEvent('STOP')",200);
						 setTimeout("document.getElementById('flvplayerContainer').style.display = 'none'",600);
					}
				}
			}			
			e.preventDefault();
		});
	}
};

// enhance lists of frequently asked questions
BLOKKER.enhanceFaqs = function() {
	var hash = document.location.hash;
	$("ul.faqlist li").each(function() {
		if(hash != "#" + $(this).attr("id")) $(this).addClass("closed");
		$("a.question", $(this)).click(function(e) {
			$(this).parents("li").toggleClass("closed");
			e.preventDefault();
		});
	});
};

// various small form enhancements
BLOKKER.enhanceForms = function(root) {
	var self = this;
	if(!root) root = $(document);
	// pre-labeled form elements (inside the element)
	$("input.labeled, textarea.labeled", root).each(function() {
		var label = $(this).attr("title") || "";
		if($(this).get(0).tagName == "INPUT") {
			if($(this).val() == "" || $(this).val() == $(this).attr("title")) $(this).val($(this).attr("title")).addClass("unfocused");
			$(this).focus(function() {
				if($(this).val() == $(this).attr("title")) $(this).val("").removeClass("unfocused");
			});
			$(this).blur(function() {
				if($(this).val() == "" || $(this).val() == $(this).attr("title")) $(this).val($(this).attr("title")).addClass("unfocused");
			});
		} else {
			if($(this).html() == "" || $(this).html() == $(this).attr("title")) $(this).html($(this).attr("title"));
			$(this).focus(function() {
				if($(this).html() == $(this).attr("title")) $(this).html("").removeClass("unfocused");
			});
			$(this).blur(function() {
				if($(this).html() == "" || $(this).html() == $(this).attr("title")) $(this).html($(this).attr("title")).addClass("unfocused");
			});
		}
	});

	// toggle sections in forms through checkboxes and radios
	if (window.navigator.userAgent.indexOf("MSIE 6.0") == -1) {
		var processedGroups = {};
		$("input.toggle_switch", root).each(function() {
			if($(this).attr("type") == "radio") {
				var groupName = $(this).attr("name");
				if (!(processedGroups[groupName])) {
					processedGroups[groupName] = true;
					$("input[name='"+groupName+"']").each(function () {
						var target = $(this).attr("lb:target");
						if (this.checked == true && (this.className.indexOf("toggle_switch") == -1)) $("#" + target).hide();//CHeck initial state
						$(this).click(function () {
							if (this.checked == true && (this.className.indexOf("toggle_switch") != -1)) {
								$("#" + target).slideDown();
							} else {
								$("#" + target).slideUp();
							}
						});
					});
				}
				return;
			} else {
				$(this).click(function() {
					var target = $(this).attr("lb:target");
					if(!this.checked) $("#" + target).slideUp(); else $("#" + target).slideDown();
				});
			}
			var target = $(this).attr("lb:target");
			if(!this.checked) $("#" + target).hide();
		});
	}
}

// sIFR is unbundled because updated page fragments need it
BLOKKER.sifr = {
	type : {
		medium : BLOKKER.swf.avenirLTSTD65Medium,
		light  : BLOKKER.swf.avenirLTSTD35Light
	},
	write : function () {
		if (typeof sIFR == "function") {
			for (var i = 0, l = arguments.length; i < l; i++) {
				BLOKKER.sifr.rule(arguments[i]);
			}
		}
	},
	rule : function (conf) {
		sIFR.replaceElement(named({
			sSelector: conf.selector,
			sFlashSrc: BLOKKER.sifr.type[conf.weight] || BLOKKER.sifr.type.medium,
			sColor: conf.color || '#1f1f1f',
			sLinkColor: conf.link || null,
			sHoverColor: conf.hover || null,
			sWmode: "transparent",
			nPaddingBottom: 1
		}));
	},
	pageload : function () {
		BLOKKER.sifr.write(
			{
				selector : ".outcry h2 .sifr",
				color : '#f58220'
			},
			{
				selector : "#discounts h2 .sifr",
				color : '#ffffff'
			},
			{
				selector : "h2 .sifr",
				link : '#1f1f1f'
			},
			{
				selector : ".sifr",
				weight : 'light',
				link : "#00aeef",
				hover : "#ec008c"
			}
		);
	}
};

/**
 * components
 */

// shopping basket
BLOKKER.basket = {
	xhr : {
		handler : BLOKKER.handler.basket,
		handlerDelete : BLOKKER.handler.basketDelete,
		container : null,
		content : null
	},
	total : null,
	count : null,
	timer : null,
	init : function (id) {
		this.total = document.getElementById('basket_total');
		this.count = document.getElementById('basket_count');
		this.xhr.container = id.appendChild(document.createElement('DIV'));
		this.xhr.container.className = 'xhr-container';
		this.xhr.content = this.xhr.container.appendChild(document.createElement('DIV'));
		this.xhr.content.className = 'xhr-content';
		$('div#thumb .bottom').before($(this.xhr.container));
		this.update();
		$(id).bind('mouseover', this.show);
		$(id).bind('mouseout',  this.hide);
	},
	update : function (data) {
		var url = BLOKKER.basket.xhr.handler;

		// If Added by IBM (DCOL)	
		if(data != null) { 
			url = BLOKKER.basket.xhr.handlerDelete;
		}

		$.post(
			url,
			data,
			function (xml) {
				BLOKKER.basket.total.innerHTML = xml.getElementsByTagName('total')[0].firstChild.nodeValue;
				BLOKKER.basket.count.innerHTML = xml.getElementsByTagName('count')[0].firstChild.nodeValue;
				var el = BLOKKER.basket.xhr.content, li, l, added, frac;
				var content = xml.getElementsByTagName('content');
				if (content.length) {
					content = content[0].childNodes, l = content.length;
					while (l--) {
						if (4 === content[l].nodeType) {
							el.innerHTML = content[l].nodeValue;
							$('#thumb tbody tr').each(
								function (i) {
									$(this).hover(
										function() { $(this).addClass("hover"); },
										function() { $(this).removeClass("hover"); }
									);
									$(this).find('a.remove').bind('click', BLOKKER.basket.remove);
								}
							);
							return true;
						}
					}
				}
				return false;
			},
			'xml'
		); // $.post
	},
	hilite : function (e) {
		var el = $(this), cl = 'hilite';;
		el.hasClass(cl) ? el.removeClass(cl) : el.addClass(cl);
	},
	remove : function (e) {
		var param = $(this).attr('href').split('#')[1];
		var parent = $(this).parents("tr:first");
		parent.fadeOut(
			500,
			function () {
				BLOKKER.basket.update(param);
			}
		);
		return false;
	},
	show : function () {
		BLOKKER.basket.clearTimer();
		BLOKKER.basket.timer = window.setTimeout(BLOKKER.basket.showHandler, 200);
	},
	hide : function () {
		BLOKKER.basket.clearTimer();
		BLOKKER.basket.timer = window.setTimeout(BLOKKER.basket.hideHandler, 300);
	},
	showHandler : function (callback) {
		$(BLOKKER.basket.xhr.container).slideDown(200, callback);
	},
	hideHandler : function () {
		$(BLOKKER.basket.xhr.container).slideUp(200);
	},
	clearTimer : function () {
		if ('undefined' !== typeof BLOKKER.basket.timer) {
			window.clearTimeout(BLOKKER.basket.timer);
		}
	}
};
// show basket on cross sales page
BLOKKER.crossSalesBasket = {
	init : function () {
		BLOKKER.basket.showHandler();
	}
};

// product comparison in photo and list view
BLOKKER.compare = {
	form : null,
	msg : {
		title           : 'Vergelijk de geselecteerde producten met elkaar',
		compare         : 'Vergelijken',
		select          : 'Selecteer meerdere producten om te vergelijken',
		compareSelected : 'Vergelijk de geselecteerde producten'
	},
	product : {},
	selected : [],
	init : function () {
		var legend = $('#comparison_legend');
		this.form = legend.parents('form');
		var that = this;
		$('fieldset.selection').each(
			function () {
				var check = $(this).find('input')[0];
				$(check).bind('click', BLOKKER.compare.checkButton);
				var refButton = $('#comparison_legend input.submit');
				var	nameValue = (refButton.attr('name') || refButton.attr('id')) + '|' + refButton.val();
				var button = $(
					'<a href="#" title="' + that.msg.title + '" class="button" rel="' +
					nameValue + '"><span><span>' + that.msg.compare + '</span></span></a>'
				);
				$(check).parents('fieldset').append(button);
				button.bind('click', that.submit);
				button.css({display:'none'});
				// the jQuery way is the silly way  :)
				var msg = $('<span class="message">' + that.msg.compare + '</span>');
				$(check).parents('label').append(msg);
				that.product[check.name || check.id] = {
					container : $(this).parents('.product-selection-box'),
					check : check,
					button : button,
					messageBox : msg
				};
			}
		); // $('fieldset.selection').each
		this.setCount();
	},
	submit : function (e) {
		var keyVal = $(e.target).parents('a.button').attr('rel').split('|');
		BLOKKER.compare.form.append(
			$('<input name="' + keyVal[0] + '" id="' + keyVal[0] + '" value="' + keyVal[1] + '">')
		);
		BLOKKER.compare.form.submit();
	},
	setCount : function () {
		var that = BLOKKER.compare,
			product;
		for (var i in that.product) {
			if (that.product.hasOwnProperty(i)) {
				product = that.product[i];
				if (product.check.checked) {
					//product.container.addClass('keep');
					that.selected.push(i);
				}
			}
		}
		that.toggleStatus();
	},
	checkButton : function () {
		var that = BLOKKER.compare;
		var name = this.name || this.id;
		var msg = that.product[name].messageBox;
		var block = that.product[name].container;
		if (that.selected.length == 3 && this.checked) {
			return false;
		}
		if (this.checked) {
			//block.addClass('keep');
			that.selected.push(name);
		} else {
			//block.removeClass('keep');
			that.remove(name);
		}
		that.toggleStatus();
	},
	remove : function (val) {
		var that = BLOKKER.compare, selected = that.selected, result = [];
		for (var i = 0, l = selected.length; i < l; i++) {
			if (selected[i] !== val) {
				result[result.length] = selected[i];
			}
		}
		that.selected = result;
	},
	toggleStatus : function () {
		var that = BLOKKER.compare, l = that.selected.length;
		if (0 === l) {
			that.loop(function (item) {
				item.messageBox.text(that.msg.compare);
				item.button.css({display:'none'});
			});
		} else if (1 === l) {
			that.loop(function (item, i) {
				item.messageBox.text(BLOKKER.inArray(that.selected, i) ? that.msg.select : that.msg.compare);
				item.button.css({display:'none'});
			});
		} else {
			that.loop(function (item, i) {
				if (BLOKKER.inArray(that.selected, i)) {
					item.messageBox.text(that.msg.compareSelected);
					item.button.css({display:''});
				} else {
					item.messageBox.text(that.msg.compare);
					item.button.hide();
					item.button.css({display:'none'});
				}
			});
		}
	},
	loop : function (callback) {
		var product = BLOKKER.compare.product, i, item;
		for (i in product) {
			if (product.hasOwnProperty(i)) {
				item = product[i];
				callback(item, i);
			}
		}
	}
};

BLOKKER.hoverable = function() {
	$(".hoverable").children().hover(
		function() {
			$(this).addClass("hover");
		},
		function() {
			$(this).removeClass("hover");
		}
	);
};

// single page feedback form per faq item
BLOKKER.faqFeedback = {
	init : function (id) {
		$(id).find('.faq-feedback a').each(
			function () {
				$(this).click(BLOKKER.faqFeedback.get);
			}
		);
	},
	get : function (e) {
		var uriRef = this.href;;
		var that = $(this);
		var parent = that.parents('div.faq-feedback');
		parent.load(
			uriRef,
			function () {
				BLOKKER.button.replace(parent.find('input.submit'));
				that.parents('ul').hide();
				var form = parent.find('form');
				if (form.length) {
					form.submit(
						function () {
							parent.load(
								uriRef,
								function () {
									BLOKKER.button.replace(parent.find('input.submit'));
								}
							);
							return false;
						}
					);
				}
			}
		);
		return false;
	}
};

// filter products in photo and list view
BLOKKER.activeLabels = {
	init : function () {
		var self = this;
		$('.active_labels li').each(
			function () {
				var inp = $(this).find('input[type=checkbox], input[type=radio]').get(0);
				if (inp.checked) $(this).addClass("active");
				$(this).bind('click', self.toggle);	
			}
		).hover(
			function() {
				$(this).addClass("hover");
			},
			function() {
				$(this).removeClass("hover");
			}
		);
	},
	toggle : function (e) {
		var target = $(e.target);
		if (e.target.nodeName == "IMG") target = $("input[type=radio], input[type=checkbox]", target.parents("label:first")).eq(0);
		if (target.attr("type") == "radio") {
			// find all sibling radios within the form
			$("input[name=" + target.attr("name") + "]", target.parents("form:first")).each(function() {
				var obj = $(this).parents("li:first");
				obj.removeClass("active");
			});
			target.attr({ checked: "checked" });
			$(this).addClass("active");
		} else if (target.attr("type") == "checkbox") {
			var obj = $(this);
			obj.hasClass("active") ? obj.removeClass("active") : obj.addClass("active");
			if (e.target.nodeName != "INPUT") {
				var inp = $(this).find('input[type=checkbox], input[type=radio]').get(0);
				inp.checked = inp.checked ? false : true;
				e.preventDefault();
			}
		}
	}
};

// single page order process step 1
BLOKKER.order = {
	container : null,
	form : null,
	init : function () {
		this.form = $('#main_content form').get(0);
		var couponButton = $('#order_frame a[rel|=get_coupon]');
		couponButton.unbind('click');
		// @note jQuery's bind method breaks Dialogs here
		var a = document.getElementById('order_frame').getElementsByTagName('A'), l = a.length;
		while (l--) {
			if (-1 !== a[l].rel.indexOf('get_coupon')) {
				a[l].onclick = function (e) {
					BLOKKER.button.submitClick(this);
					BLOKKER.order.update();
					return false;
				};
			}
		}
		// @end
		$('#order_frame a[rel=order delete]').each(
			function () {
				$(this).bind(
					'click',
					function (e) {
						BLOKKER.order.update(this.href);
						return false;
					}
				);
			}
		);
		$('#order_frame fieldset.amount select').each(
			function () {
				$(this).bind(
					'change',
					function (e) {
						BLOKKER.order.update();
						return false;
					}
				);
			}
		);
	},
	update : function (uriRef) {
		var data = uriRef ? null : BLOKKER.form.data(BLOKKER.order.form).object;
		$('#order_frame').load(
			uriRef || BLOKKER.order.form.action,
			data,
			function () {
				$('#order_frame input.button').each(
					function () {
						BLOKKER.button.replace($(this));
					}
				);
				BLOKKER.initPrices();
				BLOKKER.order.init();
			}
		);
	}
};

// creates the container for dialog-http
BLOKKER.productOptions = function () {
	$(document.body).append(
		$([
			'<div id="dialog-http" class="dialog">',
			'<div id="dialog_container"></div>',
			'<a href="#" id="dialog-close" rel="dialog-close">',
			'<img src="' + portDomainPath + '/webapp/wcs/stores/BlokkerB2C/static/images/icons/close.gif" alt="Verwijder" />',
			'</a>',
			'</div>'
		].join(''))
	);
};

// single page send to friend
BLOKKER.sendToFriend = {
	trigger : null,
	container : null,
	parent : null,
	tabClass : 'tab',
	addRowTrigger : null,
	form : null,
	msgBox : null,
	ms : null,
	init : function (id) {
		this.trigger = id;
		this.parent = id.parentNode;
		this.container = document.getElementById('main_content').appendChild(document.createElement('DIV'));
		this.container.id = 'sendtofriend';
		$(this.container).load(
			this.trigger.href + " #main_content form",
			function () {
				var obj = BLOKKER.sendToFriend;
				obj.msgBox = $('<div class="message-box"></div>');
				var msgToolbar = $('<fieldset class="buttons"></fieldset>');
				var msgClose = $('<a class="button" href="#"><span><span>' + BLOKKER.copy.closeTab + '</span></span></a>');
				obj.msg = $('<div></div>');
				$(BLOKKER.sendToFriend.container).append(obj.msgBox);
				obj.msgBox.append(obj.msg);
				obj.msgBox.append(msgToolbar);
				msgToolbar.append(msgClose);
				$('#sendtofriend input.button').each(
					function () {
						BLOKKER.button.replace($(this));
					}
				);
				$('#sendtofriend fieldset.buttons a.actionlink').click(BLOKKER.sendToFriend.toggle);
				var recipient = document.getElementById('stf_recipient');
				var link = recipient.parentNode.appendChild(document.createElement('A'));
				link.href = '#';
				link.className = 'forwardlink';
				link.appendChild(document.createTextNode(BLOKKER.copy.addRecipient));
				$(link).bind('click', BLOKKER.sendToFriend.addRecipient);
				BLOKKER.sendToFriend.addRowTrigger = link;
				BLOKKER.sendToFriend.recipient = recipient;
				obj.form = $('#sendtofriend form');
				msgClose.click(BLOKKER.sendToFriend.toggle);
				obj.form.submit(
					function () {
						$.post(
							obj.form.attr('action'),
							BLOKKER.form.data(this).object,
							function (data) {
								obj.msg.append(data);
								obj.msgBox.slideDown(200);
								obj.form.slideUp(100);
							}
						);
						return false;
					}
				);
			}
		); // $(this.container).load
		$(this.trigger).click(this.toggle);
	},
	toggle : function (form, msgBox, msg) {
		var obj = BLOKKER.sendToFriend, tab = $(obj.parent), cn = obj.tabClass, show = obj.container.style;
		if ('block' === show.display) {
			$(obj.container).slideUp(
				300,
				function () {
					tab.removeClass(cn);
					if ('none' === obj.form.css('display')) {
						obj.form.show();
						obj.msgBox.hide();
						obj.msg.empty();
					}
				}
			);
		} else {
			tab.addClass(cn);
			$(obj.container).slideDown(300);
			//BLOKKER.sifr.write({ selector : '#sendtofriend h2 .sifr' });
		}
		return false;
	},
	addRecipient : function () {
		var stf = BLOKKER.sendToFriend, row = stf.recipient.cloneNode(true);
		stf.recipient.parentNode.insertBefore(row, stf.addRowTrigger);
		row.id = '';
		var rows = stf.recipient.parentNode.getElementsByTagName('FIELDSET').length;
		var fields = row.getElementsByTagName('INPUT'), l = fields.length, node;
		while (l--) {
			node = fields[l];
			stf.reIndex(node, 'id', rows);
			stf.reIndex(node, 'name', rows);
		}
		return false;
	},
	reIndex : function (el, att, i) {
		if (el[att]) {
			el[att] = el[att].replace(/^([^\d]+)\d+([^\d]+)?$/, '$1' + (i - 1) + '$2');
		}
	}
};

/**
 * helper functions
 */

// collect form data
BLOKKER.form = {
	fields : [
		'input',
		'textarea',
		'select' //, 'button' is evil
	],
	elements : null,
	data : function (form) {
		var fields = BLOKKER.form.elements = form.elements, l = fields.length, field, obj = {}, data = '', name, val;
		for (var i = 0; i < l; i++) {
			field = fields[i];
			if (BLOKKER.inArray(BLOKKER.form.fields, field.nodeName.toLowerCase())) {
				name = field.name || field.id;
				if (name && !obj[name]) {
					val = this.value(name);
					obj[name] = val;
					data += (name + '=' + val + '&');
				}
			}
		}
		BLOKKER.form.elements = null;
		return {
			object : obj,
			string : data.substr(0, (data.length - 1))
		};
	},
	value : function (el) {
		el = BLOKKER.form.elements[el];
		if (el && el.length && !el.options) {
			var l = el.length;
			while (l--) {
				if (el[l].checked) {
					return el[l].value;
				}
			}
			return false;
		}
		if (el && el.type && ('checkbox' === el.type.toLowerCase())) {
			if (el.checked) {
				return el.value;
			}
			return false;
		}
		return el && el.value;
	}
};

BLOKKER.inArray = function (arr, val) {
	var l = arr.length;
	while (l--) {
		if (arr[l] === val) {
			return true;
		}
	}
	return false;
};

