// JavaScript Document
// Onload events
var $jQ = jQuery.noConflict();

$jQ(document).ready(function(){

// Replace value in search field
	$jQ('.replaceInput').each(function(){
		var thisVal = $jQ(this).attr('value');							
		$jQ(this).focus(function(){
			if($jQ(this).attr('value')==thisVal){
				$jQ(this).attr('value','');
			}
		}).blur(function(){
			if($jQ(this).attr('value')==''){
				$jQ(this).attr('value',thisVal);
			}
		});														
	});
	
//tabmenu settings
  //Get all the LI from the #TabMenu UL
  $jQ('#TabMenu > li').click(function(){
    
    //perform the actions when it's not selected
    if (!$jQ(this).hasClass('selected')) {    
           
		//remove the selected class from all LI    
		$jQ('#TabMenu > li').removeClass('selected');
		
		//Reassign the LI
		$jQ(this).addClass('selected');
		
		//Hide all the DIV in .boxBody
		$jQ('.BoxBody div.tabitem').hide();
		
		//Look for the right DIV in boxBody according to the Navigation UL index, therefore, the arrangement is very important.
		$jQ('.BoxBody div.tabitem:eq(' + $jQ('#TabMenu > li').index(this) + ')').fadeIn();
		//alert($jQ('#tabMenu > li').index(this));
	  }
    
  })

// Calendar
	$jQ(".CalendarEvent").click(function() {
		if(!$jQ(this).hasClass('Selected')) {
			$jQ(".CalendarEvent").removeClass('Selected');
			$jQ(".ReadMore").css("visibility","visible");
			$jQ(".CalendarEventMore").slideUp();
			$jQ(this).next(".CalendarEventMore").slideDown();
			$jQ(this).addClass('Selected');
			$jQ(".ReadMore",this).css("visibility","hidden");
		}
		else{
			$jQ(this).removeClass('Selected');
			$jQ(this).next(".CalendarEventMore").slideUp();
			$jQ(".ReadMore",this).css("visibility","visible");
		}
	});

// FAQ
	$jQ(".FAQQuestion").click(function() {
		if(!$jQ(this).hasClass('Open')) {
			$jQ(".FAQQuestion").removeClass('Open');
			$jQ(".FAQAnswer").slideUp();
			$jQ(this).next(".FAQAnswer").slideDown();
			$jQ(this).addClass('Open');
		}
		else{
			$jQ(this).removeClass('Open');
			$jQ(this).next(".FAQAnswer").slideUp();
		}
	});

// SEARCH
$jQ(".SearchResultGroup").click(function() {
	if(!$jQ(this).hasClass('Open')) {
		$jQ(".SearchResultGroup").removeClass('Open');
		$jQ(".SearchResultsContainer").slideUp();
		$jQ(this).next(".SearchResultsContainer").slideDown();
		$jQ(this).addClass('Open');
	}
	else{
		$jQ(this).removeClass('Open');
		$jQ(this).next(".SearchResultsContainer").slideUp();
	}
});

// Login
	$jQ("#LoginTab .CloseButton").click(function() {
		if($jQ("#LoginTab .CloseButton").hasClass("Open")){
			$jQ("#LoginTab").removeClass("Open");
			$jQ("#LoginTab .CloseButton").removeClass("Open");
			$jQ("#LostPassword").css("display","none");
			setCookie('LoginOpen','false',1);
		}
		else{
			$jQ("#LoginTab").addClass("Open");
			$jQ("#LoginTab .CloseButton").addClass("Open");
			$jQ("#LoginTab .Username").css("display","block");
			$jQ("#LoginTab .Password").css("display","block");
			$jQ("#LoginTab .Login").css("display","block");
			setCookie('LoginOpen','true',1);
		}
	});
	/*var cLogin = getCookie('LoginOpen');
	if(cLogin == 'true'){
		$jQ("#LoginTab").addClass("Open");
		$jQ("#LoginTab .CloseButton").addClass("Open");
		$jQ("#LoginTab .Username").css("display","block");
		$jQ("#LoginTab .Password").css("display","block");
		$jQ("#LoginTab .Login").css("display","block");
	}*/

// Mini Basket
	$jQ("#CartTab .CloseButton").click(function() {
		if($jQ("#CartTab .CloseButton").hasClass("Open")){
			$jQ("#CartTab .CloseButton").removeClass("Open");
			$jQ("#CartTab").removeClass("Open");
			setCookie('MiniBasketOpen','false',1);
		}
		else{
			$jQ("#CartTab .CloseButton").addClass("Open");
			$jQ("#CartTab").addClass("Open");
			$jQ(".CartMiniBasket").addClass("OpenMiniBasket");
			nzEcom_UpdateMiniBasket();
			setCookie('MiniBasketOpen','true',1);
		}
	});
	nzEcom_UpdateMiniBasket();
	/*var cMiniBasket = getCookie('MiniBasketOpen');
	if(cMiniBasket == 'true'){
		$jQ("#CartTab .CloseButton").addClass("Open");
		$jQ("#CartTab").addClass("Open");
		nzEcom_UpdateMiniBasket();
	}*/
	
//Søgning	
	$jQ("#nzSearchBox").nzautocomplete(
		"/layouts/MA/SearchHandler.ashx", 
	{ width:318, minChars: 2,queryParmName: 'nzQuery', cacheLength: 1, matchContains: 1, maxItemsToShow: 3, formatItem: renderItem, onItemSelect: executeItem, renderComplete: renderComplete });
	
});
//*********************************//
// End of document ready functions //
//*********************************//


//Hide Product Detail box if box is empty
function HideProductDetails(){
	if($jQ(".ProductDetailsInfo li").length == 0){
		$jQ(".ProductDetailsInfo").css("display","none");
		$jQ(".ProductDetailsInfoTop").css("display","none");
	}
}

//Hide product price box if price is displayed
function HidePriceBox(){
	if($jQ(".ProdPrice li").length == 0){
		$jQ(".ProdPrice").hide();
	}
}


//Hide Consultant box if user is logged in
function HideConsultantBox(){
	if($jQ("#LoginTab .centerText:contains('Velkommen')")){
		$jQ(".ProductItemConsultant:eq(1)").parent().hide();
		if($jQ(".ProdPrice li").length == 0){
			$jQ(".ProdPrice").hide();
		}
	}
}

function OpenMiniBasket(){
	if($jQ(".CartMiniBasket").hasClass("OpenMiniBasket")){
		$jQ(".CartMiniBasket").removeClass("OpenMiniBasket");
		$jQ(".CartMiniBasket").hide();
	}
	else{
		$jQ(".CartMiniBasket").addClass("OpenMiniBasket");
		$jQ(".CartMiniBasket").show();
	}
}

function requestPassword(){
	$jQ("#LoginTab .Username").css("display","none");
	$jQ("#LoginTab .Password").css("display","none");
	$jQ("#LoginTab .Login").css("display","none");
	$jQ("#LostPassword").css("display","block");
	$jQ(".LostPassword").css("display","none");
	$jQ("#LoginTab").addClass("Open");
	$jQ("#LoginTab .CloseButton").addClass("Open");
}

function activateTAF(){
	
	var Alignment = $jQ(".IconTip").position();
	$jQ("#Recomend").css("left",Alignment.left-177);
	$jQ("#Recomend").css("top",Alignment.top+6);
	$jQ("#Recomend").css("display","block");
	$jQ("#Recomend .CloseBtn").click(function() {
		$jQ("#Recomend").css("display","none");
	});
}

function activatePTAF(){
	var Alignment = $jQ(".IconTip").position();

	$jQ(".Product").css("left",Alignment.left-177);
	$jQ(".Product").css("top",Alignment.top+6);
	$jQ(".Product").show();
	$jQ(".Product .CloseBtn").click(function() {
		$jQ(".Product").hide();
	});
}

// Søgning

function nzSearch(txtElmId) {
	var query = document.getElementById(txtElmId).value;
	window.location.href = '/soegeresultater.aspx?nzQuery=' + encodeURI(query);
}

function renderItem(row) {
	var html = '';
	html += "<img class='ResultImg' src='" + row[4] + "&w=80'>";
	html += "<div class='ResultText'><h2>" + row[0] + "</h2>";
	html += "<span class='gray'>Varenr:" + row[1] + "</span><br />";
	html += row[2] + "</div>";
	return html;
}

function executeItem(li) {
	//Redirect to product url
	window.location.href = li.extra[2];
}

function renderComplete(result) {
	//inject this BEFORE searchresult
	result.prepend("<div class='LiveSearchTop'><h3>Produkter</h3></div>");				
	//inject this AFTER searchresult 
	result.append("<div class='LiveSearchBottom'><p>Se resultater for publikationer og sider..</p><a class='ShowAllResults' href='#' onclick='nzSearch(\"nzSearchBox\");'>Vis alle resultater</a></div>");
}

// Get URL Param
$jQ.extend({
  getUrlVars: function(){
    var vars = [], hash;
    var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
    for(var i = 0; i < hashes.length; i++)
    {
      hash = hashes[i].split('=');
      vars.push(hash[0]);
      vars[hash[0]] = hash[1];
    }
    return vars;
  },
  getUrlVar: function(name){
    return $jQ.getUrlVars()[name];
  }
});

//Adding items to cart and checking if they already exist in the cart
function itemAdded(val){

	if(val == '2'){
		$jQ.blockUI({ 
			message: $jQ('#AlreadyAddedToCartMessage'),
			css: {
				background: 'none',
				border: '0',
				textAlign: 'left',
				width: '276px',
				left: '45%'
				},
			showOverlay: true
		});
		setTimeout($jQ.unblockUI, 4500);
	}
	else if (val == '1') {
		$jQ.blockUI({ 
			message: $jQ('#AddToCartMessage'),
			css: {
				background: 'none',
				border: '0',
				textAlign: 'left',
				width: '276px',
				left: '45%'
				},
			showOverlay: true
		});
		setTimeout($jQ.unblockUI, 3000);
	}
}
// Remove item from cartItem cookie 
function itemRemoved(vnr,did){
	var cartItems = getCookie('cartItems');
	if(did!=''){
		vnr = vnr+"_"+did;
	}
	cartItems = cartItems.replace(vnr+'|','');
	setCookie('cartItems',cartItems,365);
}
function itemRemovedBasket(obj){
	var cartItems = getCookie('cartItems');
	var vnr = $jQ(obj).parent().children("div").text();
	var did = vnr.slice(vnr.indexOf('_'),vnr.length)
	//alert(did.length);
	if(did.length==1){
		vnr = vnr.replace('_','');
		//alert(vnr);
		cartItems = cartItems.replace(vnr+'|','');
	}
	else
	{
		cartItems = cartItems.replace(vnr+'|','');
	}
	setCookie('cartItems',cartItems,365);
}
function deleteCookie(){
	setCookie('cartItems','',-365);
}

//Check Out Alert
function alertConditions(){
	$jQ.fancybox('<h1>Godkend venligt handelsbetingelser</h1>Afkryds venligst at du har læst og indvilger i vores handelbetingelser.',
		{
			'width':			100,
			'height':			100
	});
}

// Accordion Content script: By Dynamic Drive, at http://www.dynamicdrive.com
var ddaccordion={
	
	contentclassname:{}, //object to store corresponding contentclass name based on headerclass

	expandone:function(headerclass, selected){ //PUBLIC function to expand a particular header
		this.toggleone(headerclass, selected, "expand")
	},

	collapseone:function(headerclass, selected){ //PUBLIC function to collapse a particular header
		this.toggleone(headerclass, selected, "collapse")
	},

	expandall:function(headerclass){ //PUBLIC function to expand all headers based on their shared CSS classname
		var $=$
		var $headers=$('.'+headerclass)
		$('.'+this.contentclassname[headerclass]+':hidden').each(function(){
			$headers.eq(parseInt($(this).attr('contentindex'))).trigger("evt_accordion")
		})
	},

	collapseall:function(headerclass){ //PUBLIC function to collapse all headers based on their shared CSS classname
		var $=$
		var $headers=$('.'+headerclass)
		$('.'+this.contentclassname[headerclass]+':visible').each(function(){
			$headers.eq(parseInt($(this).attr('contentindex'))).trigger("evt_accordion")
		})
	},

	toggleone:function(headerclass, selected, optstate){ //PUBLIC function to expand/ collapse a particular header
		var $=$
		var $targetHeader=$('.'+headerclass).eq(selected)
		var $subcontent=$('.'+this.contentclassname[headerclass]).eq(selected)
		if (typeof optstate=="undefined" || optstate=="expand" && $subcontent.is(":hidden") || optstate=="collapse" && $subcontent.is(":visible"))
			$targetHeader.trigger("evt_accordion")
	},

	expandit:function($targetHeader, $targetContent, config, useractivated){
		$targetContent.slideDown(config.animatespeed, function(){config.onopenclose($targetHeader.get(0), parseInt($targetHeader.attr('headerindex')), $targetContent.css('display'), useractivated)})
		this.transformHeader($targetHeader, config, "expand")
	},

	collapseit:function($targetHeader, $targetContent, config, isuseractivated){
		$targetContent.slideUp(config.animatespeed, function(){config.onopenclose($targetHeader.get(0), parseInt($targetHeader.attr('headerindex')), $targetContent.css('display'), isuseractivated)})
		this.transformHeader($targetHeader, config, "collapse")
	},

	transformHeader:function($targetHeader, config, state){
		$targetHeader.addClass((state=="expand")? config.cssclass.expand : config.cssclass.collapse) //alternate btw "expand" and "collapse" CSS classes
		.removeClass((state=="expand")? config.cssclass.collapse : config.cssclass.expand)
		if (config.htmlsetting.location=='src'){ //Change header image (assuming header is an image)?
			$targetHeader=($targetHeader.is("img"))? $targetHeader : $targetHeader.find('img').eq(0) //Set target to either header itself, or first image within header
			$targetHeader.attr('src', (state=="expand")? config.htmlsetting.expand : config.htmlsetting.collapse) //change header image
		}
		else if (config.htmlsetting.location=="prefix") //if change "prefix" HTML, locate dynamically added ".accordprefix" span tag and change it
			$targetHeader.find('.accordprefix').html((state=="expand")? config.htmlsetting.expand : config.htmlsetting.collapse)
		else if (config.htmlsetting.location=="suffix")
			$targetHeader.find('.accordsuffix').html((state=="expand")? config.htmlsetting.expand : config.htmlsetting.collapse)
	},

	urlparamselect:function(headerclass){
		var result=window.location.search.match(new RegExp(headerclass+"=((\\d+)(,(\\d+))*)", "i")) //check for "?headerclass=2,3,4" in URL
		if (result!=null)
			result=RegExp.$1.split(',')
		return result //returns null, [index], or [index1,index2,etc], where index are the desired selected header indices
	},

	getCookie:function(Name){ 
		var re=new RegExp(Name+"=[^;]+", "i") //construct RE to search for target name/value pair
		if (document.cookie.match(re)) //if cookie found
			return document.cookie.match(re)[0].split("=")[1] //return its value
		return null
	},

	setCookie:function(name, value){
		document.cookie = name + "=" + value + "; path=/"
	},

	init:function(config){
	document.write('<style type="text/css">\n')
	document.write('.'+config.contentclass+'{display: none}\n') //generate CSS to hide contents
	document.write('<\/style>')
	$jQ(document).ready(function($){
		ddaccordion.urlparamselect(config.headerclass)
		var persistedheaders=ddaccordion.getCookie(config.headerclass)
		ddaccordion.contentclassname[config.headerclass]=config.contentclass //remember contentclass name based on headerclass
		config.cssclass={collapse: config.toggleclass[0], expand: config.toggleclass[1]} //store expand and contract CSS classes as object properties
		config.revealtype=/^(click)|(mouseover)$/i.test(config.revealtype)? config.revealtype.replace(/mouseover/i, "mouseenter") : "click"
		config.htmlsetting={location: config.togglehtml[0], collapse: config.togglehtml[1], expand: config.togglehtml[2]} //store HTML settings as object properties
		config.oninit=(typeof config.oninit=="undefined")? function(){} : config.oninit //attach custom "oninit" event handler
		config.onopenclose=(typeof config.onopenclose=="undefined")? function(){} : config.onopenclose //attach custom "onopenclose" event handler
		var lastexpanded={} //object to hold reference to last expanded header and content ($ objects)
		var expandedindices=ddaccordion.urlparamselect(config.headerclass) || ((config.persiststate && persistedheaders!=null)? persistedheaders : config.defaultexpanded)
		if (typeof expandedindices=='string') //test for string value (exception is config.defaultexpanded, which is an array)
			expandedindices=expandedindices.replace(/c/ig, '').split(',') //transform string value to an array (ie: "c1,c2,c3" becomes [1,2,3]
		var $subcontents=$('.'+config["contentclass"])
		if (expandedindices.length==1 && expandedindices[0]=="-1") //check for expandedindices value of [-1], indicating persistence is on and no content expanded
			expandedindices=[]
		if (config["collapseprev"] && expandedindices.length>1) //only allow one content open?
			expandedindices=[expandedindices.pop()] //return last array element as an array (for sake of $.inArray())
		if (config["onemustopen"] && expandedindices.length==0) //if at least one content should be open at all times and none are, open 1st header
			expandedindices=[0]
		$('.'+config["headerclass"]).each(function(index){ //loop through all headers
			if (/(prefix)|(suffix)/i.test(config.htmlsetting.location) && $(this).html()!=""){ //add a SPAN element to header depending on user setting and if header is a container tag
				$('<span class="accordprefix"></span>').prependTo(this)
				$('<span class="accordsuffix"></span>').appendTo(this)
			}
			$(this).attr('headerindex', index+'h') //store position of this header relative to its peers
			$subcontents.eq(index).attr('contentindex', index+'c') //store position of this content relative to its peers
			var $subcontent=$subcontents.eq(index)
			var needle=(typeof expandedindices[0]=="number")? index : index+'' //check for data type within expandedindices array- index should match that type
			if ($.inArray(needle, expandedindices)!=-1){ //check for headers that should be expanded automatically (convert index to string first)
				if (config.animatedefault==false)
					$subcontent.show()
				ddaccordion.expandit($(this), $subcontent, config, false) //Last Boolean value sets 'isuseractivated' parameter
				lastexpanded={$header:$(this), $content:$subcontent}
			}  //end check
			else{
				$subcontent.hide()
				config.onopenclose($(this).get(0), parseInt($(this).attr('headerindex')), $subcontent.css('display'), false) //Last Boolean value sets 'isuseractivated' parameter
				ddaccordion.transformHeader($(this), config, "collapse")
			}
		})
		$('.'+config["headerclass"]).bind("evt_accordion", function(){ //assign custom event handler that expands/ contacts a header
				var $subcontent=$subcontents.eq(parseInt($(this).attr('headerindex'))) //get subcontent that should be expanded/collapsed
				if ($subcontent.css('display')=="none"){
					ddaccordion.expandit($(this), $subcontent, config, true) //Last Boolean value sets 'isuseractivated' parameter
					if (config["collapseprev"] && lastexpanded.$header && $(this).get(0)!=lastexpanded.$header.get(0)){ //collapse previous content?
						ddaccordion.collapseit(lastexpanded.$header, lastexpanded.$content, config, true) //Last Boolean value sets 'isuseractivated' parameter
					}
					lastexpanded={$header:$(this), $content:$subcontent}
				}
				else{
					ddaccordion.collapseit($(this), $subcontent, config, true) //Last Boolean value sets 'isuseractivated' parameter
				}
 		})
		$('.'+config["headerclass"]).bind(config.revealtype, function(){
			if (config.revealtype=="mouseenter"){
				ddaccordion.expandone(config["headerclass"], parseInt($(this).attr("headerindex")))
			}
			else{
				$(this).trigger("evt_accordion")
				return false //cancel default click behavior
			}
		})
		config.oninit($('.'+config["headerclass"]).get(), expandedindices)
		$(window).bind('unload', function(){ //clean up and persist on page unload
			$('.'+config["headerclass"]).unbind()
			var expandedindices=[]
			$('.'+config["contentclass"]+":visible").each(function(index){ //get indices of expanded headers
				expandedindices.push($(this).attr('contentindex'))
			})
			if (config.persiststate==true){ //persist state?
				expandedindices=(expandedindices.length==0)? '-1c' : expandedindices //No contents expanded, indicate that with dummy '-1c' value?
				ddaccordion.setCookie(config.headerclass, expandedindices)
			}
		})
	})
	}
}

//initialiser fold ud menu;
ddaccordion.init({
	headerclass: "expandable", //Shared CSS class name of headers group that are expandable
	contentclass: "categoryitems", //Shared CSS class name of contents group
	revealtype: "click", //Reveal content when user clicks or onmouseover the header? Valid value: "click" or "mouseover
	collapseprev: true, //Collapse previous content (so only one open at any time)? true/false 
	defaultexpanded: [0], //index of content(s) open by default [index1, index2, etc]. [] denotes no content
	onemustopen: true, //Specify whether at least one header should be open always (so never all headers closed)
	animatedefault: false, //Should contents open by default be animated into view?
	persiststate: false, //persist state of opened contents within browser session?
	toggleclass: ["", "openheader"], //Two CSS classes to be applied to the header when it's collapsed and expanded, respectively ["class1", "class2"]
	togglehtml: ["prefix", "", ""], //Additional HTML added to the header when it's collapsed and expanded, respectively  ["position", "html1", "html2"] (see docs)
	animatespeed: "fast", //speed of animation: "fast", "normal", or "slow"
oninit:function(headers, expandedindices){ //custom code to run when headers have initalized
	//do nothing
	//if($("#RightColumnContainer").height() > $("#Content").height()){
	//	$("#ParagraphContent").css("height", $("#ParagraphContent").height() + ($("#RightColumnContainer").height() - $("#Content").height()));
	//}
},
onopenclose:function(header, index, state, isuseractivated){ //custom code to run whenever a header is opened or closed
	//do nothing
}
})

// Cookie Set/Get function
function setCookie(c_name,value,expiredays) {
	var exdate=new Date();
	exdate.setDate(exdate.getDate()+expiredays);
	document.cookie=c_name+ "=" + escape(value) + ((expiredays==null) ? "" : "; expires="+exdate.toGMTString());
	//document.cookie=c_name+ "=" + escape(value) + ";expires=" + expires;
}
function getCookie(c_name) {
	if (document.cookie.length>0) {
		c_start=document.cookie.indexOf(c_name + "=");
		if (c_start!=-1) {
			c_start=c_start + c_name.length+1; 
			c_end=document.cookie.indexOf(";",c_start);
			if (c_end==-1) c_end=document.cookie.length;
			return unescape(document.cookie.substring(c_start,c_end));
		} 
	}
	return "";
}

// Open FAQ question if url contains #qxxxxxxxx
function openFAQItem() {
	var windowLocation = new String(window.location);
	if (windowLocation.indexOf('#') > -1) {
		var faqItem = windowLocation.substring(windowLocation.indexOf('#'));
		jQuery(faqItem).addClass("Open");
		jQuery(faqItem).next(".FAQAnswer").slideDown();
	}
}

