jQuery(document).ready(function(){
	// equalize box heights	
//        var maxHeight = 0;
//	if ( $(".itemsRow .item").length > 1 ) {
//            $(".itemsRow").each(function() {
//                    var rowHeight = $(this).height();
//                    maxHeight = (rowHeight > maxHeight) ? rowHeight : maxHeight;
//            });
//            
//            maxHeight = maxHeight - 20;
//            $(".itemsRow").each(function() {
//                $(this).find(".itemContent").height(maxHeight);
//            });
//	}
	WordLidBorderFix();
	startTekstGedrag.init('Zoek...', jQuery('#s'));
	startTekstGedrag.init('Merknaam en type (bijvoorbeeld Miele W 5844)', jQuery('#search_text'));
	startTekstGedrag.init('Uw postcode...', jQuery('.formTop .postcode'));
	startTekstGedrag.init('Plak de YouTube link in dit tekstveld', jQuery('.addLink #addLink'));
 	yellowFade.init();
 	inklapGedrag.init();
 	HoeWijTestenFix();
 	FilterHover();
 	VideoMaskSmallInit();
 	DWREngine.setTimeout(10000);
 	dwr.engine.setErrorHandler(function() {});
	initBasket();
 	//footerMenuFix(); 	
	initDropdown();
	initFoldOuts();
        initBannerLoginLink();
 	
 	$('#onsAdvies .resultaatBox .hover').mouseenter(function() {
 		$(this).css('background', 'url("/app-static/productvergelijker/images/bg-hover-ro.png") no-repeat 0 bottom');
 	});
 	$('#onsAdvies .resultaatBox .hover').mouseleave(function() {
 		$(this).css('background', 'none'); 		
 	});
	fixCufonts();
        setThemeNavigationState();
});


var
	Misc =
	{
		redraw : function(element)
		{
			element = $(element);
		    var n = document.createTextNode(' ');
		    element.append(n);
		    n.parentNode.removeChild(n);
		}
	};


var yellowFade = {
		overlay: null,
		intime: 0,
		outtime: 850,
		init : function(){
			/*$('.columnRight .vergelijkBox').bind('click', yellowFade.fade);*/
		},
		fade : function() {
			if ($('.columnRight #vergelijkenSidebar').length > 0) {
				var vergelijkBox = $('.columnRight #vergelijkenSidebar');
				yellowFade.overlay = $('<div id="fadeOverlay"><div>&nbsp;</div></div>');
				yellowFade.wrapper = $('.columnRight #vergelijkenSidebar .fotosproduct');
				yellowFade.wrapper2 = $('.columnRight #vergelijkenSidebar .box');
				yellowFade.overlay.width($(vergelijkBox).width());
				yellowFade.overlay.height($(vergelijkBox).height() - 8);

				$(vergelijkBox).prepend(yellowFade.overlay);

				yellowFade.wrapper2.css({"background-color" : "#ADD2E9", "border-left-color" : "#ADD2E9", "border-left-style" : "solid", "border-left-width" : "1px", "border-right-color" : "#ADD2E9", "border-right-style" : "solid", "border-right-width" : "1px"});
				yellowFade.wrapper.css({"background-color" : "#ADD2E9"});
				yellowFade.overlay.css({ "opacity" : ".3", "-ms-filter" : "alpha (opacity=30)", "filter" : "alpha (opacity=30)"});
				$(".fadeOverlay").css({ "opacity" : ".3", "-ms-filter" : "alpha (opacity=30)", "filter" : "alpha (opacity=30)"});

				yellowFade.overlay.animate({opacity: 0},yellowFade.outtime, yellowFade.dropOverlay);
				yellowFade.wrapper.animate({ backgroundColor: "#F2F9FF"}, yellowFade.outtime);
				yellowFade.wrapper2.animate({ backgroundColor: "#F2F9FF", borderLeftColor: "#C9E1F0", borderRightColor: "#C9E1F0" }, yellowFade.outtime);
			}
		},
		dropOverlay : function() {
			$("#fadeOverlay").remove();
		}
};


var startTekstGedrag = {
	init : function(text, obj) {
		if ((obj.val() == '') || (obj.val() == text)) {
			obj.val(text).attr('style', 'color: #999999')
			.bind('focus', function(){
				startTekstGedrag.release(obj);
			})
			.addClass("noFocus");
		}
	},
	release: function(obj){
		obj.val('').attr('style', '').unbind('focus').removeClass("noFocus");
	}
};

var inklapGedrag = {
	setNo: 1,
	subSet: 1,

	/**
	 * Initialize the different classes, expendable and subexpandable
	 * by added number identifier and click events.
	 */
	init : function (initBase, toggleFunc, subToggleFunc)
	{
	// set the functions properly if they aren't specified
	if (initBase === undefined)	initBase = $(".specificaties table tr");
	if (toggleFunc === undefined) toggleFunc = inklapGedrag.addToggleBehavior;
	if (subToggleFunc === undefined) subToggleFunc = inklapGedrag.addSubToggleBehavior;

	//$('.accordionBox').height($('.accordionBox').height());
	$(".specificaties table tr").each(
		function ()
		{
			if ($("th", $(this)).length > 0)
				return;

			if ($(this).hasClass('expandable'))
			{
				inklapGedrag.setNo++;
				inklapGedrag.subSet++;
				toggleFunc(this);
			}
			else if ($(this).hasClass('subexpandable'))
			{
				inklapGedrag.subSet++;
				subToggleFunc(this);
				$(this).addClass(inklapGedrag.getToggleClass());
			}
                        else if ($(this).hasClass('subnotexpandable'))
                        {
				inklapGedrag.subSet++;
				$(this).addClass(inklapGedrag.getToggleClass());
                        }
			else
			{
				var toggleClass = inklapGedrag.getToggleClass();
				$(this).addClass(toggleClass).addClass(inklapGedrag.getToggleSubClass());
			}
		}
	);
	},

	/**
	 * Return a unique identifier for an 'expandable' class element
	 */
	getToggleClass: function(){
		return "setNo" + inklapGedrag.setNo;
	},

	/**
	 *	Return a unique identifier for a 'subexpendable' class element
	 */
	getToggleSubClass: function(){
		return "subSetNo" + inklapGedrag.subSet;
	},

	/**
	 * Toggle a certain class by adding the `invisible` class
	 */
	toggle : function(toggleClass){
		$(toggleClass).toggleClass('invisible');
	},

	/**
	 * Initialize toggle behaviour for an 'expandable' class
	 */
	addToggleBehavior : function (obj)
	{
		var toggleClass = '.' + inklapGedrag.getToggleClass();
		$('.level1', $(obj)).click(
			function()
			{
				$(toggleClass).toggleClass('collapsed');
			})
		.prepend($('<span class="toggle">&nbsp;</span>'))
		.click(function(){
			$(obj).toggleClass('toggle_in');

			//force rerender in ie 6;
			$('span', $(obj)).attr('style','zoom:1');
		});
	},

	/**
	 * Initialize toggle behaviour for a `subexpandable` class
	 */
	addSubToggleBehavior : function (obj)
	{
		var toggleClass = '.' + inklapGedrag.getToggleSubClass();
		$('.level3',$(obj)).click(
			function(){
				$(toggleClass).toggleClass('subcollapsed');
		})
		.prepend($('<span class="subtoggle">&nbsp;</span>'))
		.click(function(){
			$(obj).toggleClass('subtoggle_in');

			//force rerender in ie 6;
			$('span', $(obj)).attr('style','zoom:1');
		});
	}
};

function WordLidBorderFix() {
	if (jQuery('td div.bannerContainer')){
		var banner = jQuery('td div.bannerContainer');
		if ((banner.width()+255) < banner.parent().width()){
			banner.parent()
			.attr('colspan', banner.parent().attr('colspan')-1);
			banner.parent().after(jQuery('<td class="lastColumn"></td>'));
		}
	}
}



/* toon /verberg voorwaarden in stelEenVraag popup */

jQuery(document).ready(function(){
	$("a.showHideVoorwaarden").toggle(
			function()
			{
				$(this).addClass("open");
				$(".expandable", $(this).parent()).slideDown(100);
			},
		   	function()
		   	{
				$(this).removeClass("open");
		    	$(".expandable", $(this).parent()).slideUp(100);
		   	}
		);
});


/**
 * Expand the answer blocks that are within the element
 * specified in `mainElement`
 *
 * @param mainElement
 * @return
 */
function expandAnswerElement(qa)
{
	$(".answerBox", qa).removeClass("hidden");

	$("span.linkText", qa).parent().addClass("open");
	$(".bottomCrumbs", qa).removeClass("hidden");
	$("span.linkText", qa).html("Verberg");
	$(".displayNumber", qa).removeClass("hidden");

}

/**
 * Hide the answer blocks inside `mainElement`
 *
 * @param mainElement
 * @return
 */
function contractAnswerElement(qa)
{
	$(".answerBox", qa).addClass("hidden");

	$("span.linkText", qa).parent().removeClass("open");
	$(".bottomCrumbs", qa).addClass("hidden");
	$("span.linkText", qa).html("Bekijk");
	$(".displayNumber", qa).addClass("hidden");
}


/**
 * Determine whether the main element already has answers
 * that are visible. If this is true, the answers will be contracted
 * and the state of the classes are changed. Otherwise they
 * are expanded.
 *
 * @param mainElement	Element to start looking for answers at.
 * @return
 */
function determineToggleAction(qa)
{
	if ($(".answerBox", qa).hasClass("answers_toggled"))
	{
		$(".answerBox", qa).removeClass("answers_toggled");
		contractAnswerElement(qa);
	}
	else
	{
		$(".answerBox", qa).addClass("answers_toggled");
		expandAnswerElement(qa);
	}
}


function findQABox(node)
{
	while (node != null)
	{
		if (node.hasClass("qa"))
			return node;

		node = node.parent();
	}
	return null;
}


/* hover on submit buttons */
jQuery(document).ready(function(){
	$(".submit").mouseover(function(){
		$(this).addClass("hover");
	 }).mouseout(function(){
		$(this).removeClass("hover");
	});
});



/**
 * Change the number in a certain container to represent
 * the number of characters in the textarea element specified
 * in `element`.
 *
 * @param element
 * @param id
 * @return
 */
function changeTextareaCount(element, id)
{
	$("#" + id).html(
			$(element).val().length
		);
}

function limitLength(element, length)
{
	// longer than desired?
	if ($(element).val().length >= length)
	{
		$(element).val(
					$(element).val().substr(0, length - 1) 	// get first n chars
				);
	}
}

function questionPopupSubmit()
{
	if ($("#questionArea").val().length > 0)
	{
		$("#stelEenVraagPopupForm").submit();
		return;
	}

	alert("Kan geen lege vraag versturen");
	$('.input').each(
			function(){
				this.disabled = false;
			}
	);
}

function answerPopupSubmit()
{
	if ($("#answerArea").val().length > 0)
	{
		$("#beantwoordEenVraagPopupForm").submit();
		return;
	}

	alert("Kan geen leeg antwoord versturen");
	$(".input").each(
			function(){
				this.disabled = false;
			}
	);
}

function printPage(url) {
	if(window.frames['printFrame'] != null) {
		document.body.removeChild(document.getElementById('printFrame'));
	}

	var iframeHandler = document.createElement('iframe');
	iframeHandler.id = 'printFrame';
	iframeHandler.name = 'printFrame';
	iframeHandler.src= url;
	iframeHandler.scrolling= 'no';
	iframeHandler.frameborder= '0';
	iframeHandler.style.position= 'absolute';
	iframeHandler.style.top= '0';
	iframeHandler.style.left= '0';
	iframeHandler.style.width = '100%';
	iframeHandler.style.height = '0';
	iframeHandler.style.border = '0';
	document.body.appendChild(iframeHandler);
}

//add breadcrumb tooltip
$(document).ready(
		function()
		{
			// move some attributes around
			$(".tooLong").each(
					function()
					{
						$(this).attr("tooltip_title", $(this).attr("title"));
						$(this).removeAttr("title");
					}
				);

			// if hovering over ... element; initialize and showtooltip
			$(".tooLong").mouseover(
						function(e)	{
							Tooltip.init("breadcrumbTooltipPopup");
							$("#breadcrumbTooltipPopup .bcContent").html($(this).attr("tooltip_title"));

							// show at mouse position
							Tooltip.showAtPos(
								this,
								e.pageX + 15,
								e.pageY + 15,
								200
							);
						}
					);
					
			// if hovering over shorten text element; initialize and showtooltip
			$(".shortenText").mouseover(
						function(e)	{
							Tooltip.init("shortenTextTooltipPopup");
							$("#shortenTextTooltipPopup .shortenTextContent").html($(this).attr("title"));

							// show at mouse position
							Tooltip.showAtMousePosition(
								this,
								0,
								0,
								200
							);
						}
					);

			$(".productscoreInfo").mouseover(
					function()
					{
						Tooltip.init("productscoreTooltipPopup");
						//$("#productscoreTooltipPopup h4").html($(this).attr("tooltip_title"));

						// show at link at position
						Tooltip.showAt(this, -300, 30);
					}
				);
						
			bindPredicateHandler($('#onsAdvies .hover .imgProd'));
			bindPredicateHandler($('.splitSection .imgProd'));
			bindPredicateHandler($('.productPicture'));
			bindPredicateHandler($('.imageFrameResult .imglink'));
			bindPredicateHandler($('.imageFrame'));
			bindPredicateHandler($(".besteUitTest"));
			bindPredicateHandler($(".bestKoop"));
			bindPredicateHandler($(".besteKoop"));
			bindPredicateHandler($(".afrader"));
			bindPredicateHandler($(".voordeligsteKeus"));
		}
	);

function setProductCode(node, code)
{
	node.attr("product_code", code);
}

function bindPredicateHandler(nodes)
{
	nodes.mouseenter(
			function() {				
				if (typeof($(this).attr('product_code')) != 'undefined') {
					predikaatTooltipEvent($(this), $(this).attr("product_code"));
				}
			}
		);

	nodes.mouseleave(function() {
		Tooltip.stillOpen(false);
	});
}

function HoeWijTestenFix() {
	$('.columnRight .hoeTestenWij .richText, .columnLeft .hoeTestenWij .richText').each(function() {
		if($('ul', $(this)).length > 0 && $('img.float', $(this)).length > 0) {
			$('img.float', $(this)).prependTo($('ul li:last', $(this)));
		}
	});
}
function FilterHover() {
	$('#filterPreference .filterItem').hover(
		function() {
			$(this).removeClass('filterItem');
			$(this).addClass('filterItemHover');
		},
		function() {
			$(this).removeClass('filterItemHover');
			$(this).addClass('filterItem');
		}
	);
}
function VideoMaskSmallInit() {
	$('div.maskSmall:not(.maskDisabled)').each(function() {
		var mask = $(this)

		$('.imgVideo', mask.parent()).hover(
			function() {addVideoMaskSmall(mask);},
			function() {removeVideoMaskSmall(mask);}
		);

		mask.hover(
			function() {addVideoMaskSmall(mask);},
			function() {removeVideoMaskSmall(mask);}
		);
	});
}
function addVideoMaskSmall(el) {
	el.removeClass('maskSmall');
	el.addClass('maskSmallHover');
}
function removeVideoMaskSmall(el) {
	el.removeClass('maskSmallHover');
	el.addClass('maskSmall');
}

function shorten(text, maxLength) {

	if (text.length > maxLength) {
		return text.substring(0, maxLength - 1) + "...";
	}	
	
	return text;
}

/**
 * Sets a calculated width and floats on the ul and li elements. This fixes incorrect zooming in IE7. 
 */
function footerMenuFix() {
	var width = 0;
	
	for (var i = 0; i < $('.topFooter ul li').length; i++) {
		width += $('.topFooter ul li').eq(i).outerWidth();
	}

	$('.topFooter ul').css({'width' : width, 'margin' : '0 auto'});
	$('.topFooter ul li').css({'float' : 'left'});
}

function initBasket() {
// Register a click handler for the basket
    $('#basket').click(function() {
            // Submit the form
            $('form', this).submit();
    });
}

function showLoginBox() {
    tb_show(null, 'TB_inline?height=657&amp;width=605&amp;inlineId=loginPopup', false, true, false, 'TB_login'); setLoginFocus();
}

function initDropdown(){
	$('.mainNav .category').each(function(){
		//set width for white overlay span
		if($(this).hasClass("last")){
			$(this).find('.fill').css({'width': $(this).width()-3});		
		} else {
			$(this).find('.fill').css({'width': $(this).width()-1});
		}
		
		//set direction for popup
		var position = $(this).position();
		if(position.left < 500){
			$(this).addClass("right");
		} else {
			$(this).addClass("left");
		}
	});
	
	//init HoverInent
	$('.mainNav .category').hoverIntent({
	interval: 100,
	over: showSubnav,
	sensitivity: 4,
	timeout: 100,
	out: hideSubnav
	});
}
	
function showSubnav() {
	$(this).addClass("open").next().addClass('next');
	$(this).find('.fill').css({'display':'block'});
}

function hideSubnav() {
	$(this).removeClass("open").next().removeClass('next');
	$(this).find('.fill').css({'display':'none'});
}

function initFoldOuts(){
	listFoldOutSingle('.category .foldout', $(".category .blueBulletSmall.collapsible").height(), 3.6);	
	listFoldOutDouble('.dossierRow .foldout', $(".dossierRow .blueBulletSmall.collapsible").height(), 1);
	doorwayFoldOut('.collapsibleFooter .foldout', $(".doorways.collapsible .innerdoorways").height(), 0);
        
        var foldOuts = $(".overview .collapsibleFooter .foldout");
        
        foldOuts.each(function() {
            var height = 0;
            var list = $(this).parent().siblings(".itemContent").children("ul");
            var currentlyVisible = list.is(":visible");
            if (list.children("li").size() > 5) {
                if (!currentlyVisible) {
                    list.parents(".tabsContent").removeClass("closed");
                }

                for (i = 1; i <= 5; i++) {
                    height += list.find("li:nth-child(" + i + ")").outerHeight();
                }
                list.height(height);

                if (!currentlyVisible) {
                    list.parents(".tabsContent").addClass("closed");
                }
                
                dossierHomepageFoldOut($(this), height);
            }
        });

}

function listFoldOutSingle(classSelector, initialHeight, heightMultiplier){
	$(classSelector).mousedown(function(){
		var foldOutList = $(this).siblings("ul").toggleClass("open");
		if(foldOutList.hasClass("open")){
			var height = foldOutList.children().size() * (foldOutList.children().height() + heightMultiplier);
			foldOutList.animate({height:height}, 300);
			$(this).html($(this).html().replace("Meer", "Minder"));
		} else {
			foldOutList.animate({height:initialHeight}, 300);
			$(this).html($(this).html().replace("Minder", "Meer"));
		}
		$(this).toggleClass("open");
		return false;
	});
}

function listFoldOutDouble(classSelector, initialHeight, heightMultiplier){
	$(classSelector).mousedown(function(){
		var foldOutList = $(this).siblings("ul").toggleClass("open");
		if(foldOutList.hasClass("open")){
			var height = (Math.ceil(foldOutList.children().size() / 2)) * (foldOutList.children().height() + heightMultiplier);
			foldOutList.animate({height:height}, 300);
			$(this).html($(this).html().replace("Meer", "Minder"));
		} else {
			foldOutList.animate({height:initialHeight}, 300);
			$(this).html($(this).html().replace("Minder", "Meer"));
		}
		$(this).toggleClass("open");
		return false;
	});
}

function doorwayFoldOut(classSelector, initialHeight, heightMultiplier){
	$(classSelector).mousedown(function(){
		var foldOutDoorway = $(this).parent().siblings().find(".innerdoorways").toggleClass("open");
		if(foldOutDoorway.hasClass("open")){
			var height = foldOutDoorway.children(".doorway").size() * (foldOutDoorway.children(".doorway").outerHeight() + heightMultiplier);
			foldOutDoorway.animate({height:height}, 300);
			$(this).html($(this).html().replace("Meer", "Minder"));
		} else {
			foldOutDoorway.animate({height:initialHeight}, 300);
			$(this).html($(this).html().replace("Minder", "Meer"));
		}
		$(this).toggleClass("open");
		return false;
	});
}

function dossierHomepageFoldOut(foldout, initialHeight){
	foldout.mousedown(function(){
		var foldOutList = $(this).parent().siblings(".itemContent").children("ul").toggleClass("open");
		if(foldOutList.hasClass("open")){
                    var height = 0;
                    for (i = 1; i <= foldOutList.children("li").size(); i++) {
                        height += foldOutList.find("li:nth-child(" + i + ")").outerHeight();
                    }
                    foldOutList.animate({height:height}, 300);
                    $(this).html($(this).html().replace("Meer", "Minder"));
                    $(this).addClass("open");
		} else {
                    foldOutList.animate({height:initialHeight}, 300);
                    $(this).html($(this).html().replace("Minder", "Meer"));
                    $(this).removeClass("open");
                }

		return false;
	});
}
function fixCufonts(){
	Cufon.replace('h1.pageTitle', { fontFamily: 'Myriad Pro Italic' });
	Cufon.replace('.greenTitle2', { fontFamily: 'Myriad Pro Italic' });
	Cufon.replace('.greenTitle3', { fontFamily: 'Myriad Pro Italic' });
	Cufon.replace('.blockTitle1', { fontFamily: 'Myriad Pro Italic' });
	Cufon.replace('.blockTitle3', { fontFamily: 'Myriad Pro Italic' });
	Cufon.replace('.greyTitle', { fontFamily: 'Myriad Pro Italic' });
	Cufon.replace('.blueText2', { fontFamily: 'Myriad Pro Italic' });
	Cufon.replace('.footerColumn blockquote', { fontFamily: 'Myriad Pro Italic' });
	Cufon.replace('.blueTitle', { fontFamily: 'Myriad Pro Semibold Italic' });
	Cufon.replace('.blueTitle2', { fontFamily: 'Myriad Pro Italic' });
	Cufon.replace('.blueTitle3', { fontFamily: 'Myriad Pro Regular' });
	Cufon.replace('.blueText', { fontFamily: 'Myriad Pro Italic' });
	Cufon.replace('.green2', { fontFamily: 'Myriad Pro Italic' });
        Cufon.replace('div.selectieEmptyHeader', {fontFamily: 'Myriad Pro Regular'});
	Cufon.replace('.greenTitleContent2', { fontFamily: 'Myriad Pro Regular' });
	Cufon.replace('.mainGreenTitle', {fontFamily: 'Myriad Pro Italic'});
	Cufon.replace('.introBlock .mainGreenTitle', {fontFamily: 'Myriad Pro Italic'});
	Cufon.replace('.pageTitle', {fontFamily: 'Myriad Pro Italic'});
	Cufon.replace('.overview .columnRight h2', {fontFamily: 'Myriad Pro Italic'});

	Cufon.replace('.overview .columnRight .tabsNav h2.tabBlockTitle', {fontFamily: 'Myriad Pro Regular'});
	Cufon.replace('.cfaWizard ul li h3', {fontFamily: 'Myriad Pro Regular'});

	Cufon.replace('.cfaWizard ul li h3 span', {fontFamily: 'Myriad Pro Bold'});

	Cufon.replace('.loginTitle', { fontFamily: 'Myriad Pro Italic' });		
	Cufon.replace('h2.greenTitle2', { fontFamily: 'Myriad Pro Italic' });
	Cufon.replace('h2.blockTitleEI a', { fontFamily: 'Myriad Pro Regular' });
}

function initBannerLoginLink(){
    $(".bannerDescription a").click(function(){
       window.location="#";
       showLoginBox();
       return false;
    });
}
