﻿/*
INCLUDES
**********************************************/
// specify which javascripts to include on the webpage
js('/files/javascript/jquery.colorbox-min.js');
js('/files/javascript/jquery.autocomplete.min.js');
js('/files/javascript/jquery.cycle.all.min.js');
js('/files/javascript/jquery.checkbox.min.js');
js('/files/javascript/jquery.rating.js');
js('/files/javascript/cufon.js');
js('/files/javascript/Max.font.js');
js('/files/javascript/jquery.easing.1.3.js');
js('/files/javascript/jquery.backgroundPosition.js');
js('/files/javascript/flowplayer-3.2.4.min.js');
js('/files/javascript/jquery.scrollTo-1.4.2-min.js');
//js('/files/javascript/jquery.ba-bbq.min.js');

// groupsmenu ajax funktionality
// version: 1.0 - 2010-05-12
(function ($) {

	$.fn.groupsmenuAjax = function (options) {

		// create the options object with data from the default options and the user specified options
		var opts = $.extend({}, $.fn.groupsmenuAjax.defaults, options);

		// activate the script for each instans found in the selector
		return this.each(function () {

			// build element specific options
			var o = $.metadata ? $.extend({}, opts, $(this).metadata()) : opts;

			// add the correct classes based on which submenus are open and closed when the plugin is called
			$(this).find('ul.' + o.closedClass).prev().addClass(o.closedClass);
			$(this).find('ul.' + o.openClass).prev().addClass(o.openClass);

			// dynamisk aktivering af klik på elementerne
			$(this).find('.' + o.hasSubmenuClass + ' > a').live('click', function (e) {

				var $this = $(this);

				if ($this.next().size() > 0) {
					// there is already a submenu, so lets just work with that

					if ($this.hasClass('closed')) {
						// when the item is closed, open it and close all the other open menus
						$this.removeClass(o.closedClass).addClass(o.openClass).next().slideDown('fast').parent().siblings().find('ul').slideUp().prev().removeClass(o.openClass).addClass(o.closedClass);
					}
					else {
						// when the item is open, close it
						$this.removeClass(o.openClass).addClass(o.closedClass).next().slideUp('fast');
					}
				}
				else {
					// there is not a submenu yet, so fetch the correct submenu with Ajax

					// give feedback to the user, that we are working on getting the submenu
					$('<img class="preloader" src="' + o.preloaderImage + '" alt=""/>').insertAfter($this).fadeIn('fast');

					// fetch the submenu
					$.ajax({
						url: '/dynamic.aspx?data=groups&template=groupsmenu_ajax&ajaxmode=1',
						data: {
							key: $this.metadata().menuid
						},
						success: function (data) {
							// add a "open" class to the link, remove the preloader image and insert the new list of menuitems after the link

							$this.addClass(o.openClass).next('img').fadeOut('fast', function () {
								$(this).remove();
							}).end().after(data).next().slideDown('fast');
						}
					});
				}

				// remove focus from the clicked link and cancel the normal click event
				$this.blur();
				e.preventDefault();

			});
		});
	}

	// default values for the options
	$.fn.groupsmenuAjax.defaults = {
		hasSubmenuClass: 'hasSubmenu',
		openClass: 'open',
		closedClass: 'closed',
		preloaderImage: '/images/preload_16x16.gif'
	};

})(jQuery);



// horizontal main menu - suckerfish style drop down
// version: 1.0 - 2010-05-14
(function ($) {

	$.fn.menuFades = function (options) {

		// activate the script for each instans found in the selector
		return this.each(function () {

			$(this).find('li').hoverIntent(function () {
				// on mouseover
				$('ul:first', this).fadeIn('fast');
			}, function () {
				// on mouseout
				$('ul:first', this).fadeOut('fast');
			});

		});
	}

})(jQuery);



// add and subtract quantity fields.
// version: 1.1 - 2010-07-22
(function ($) {

	$.fn.quantityAddSubtract = function (options) {

		// create the options object with data from the default options and the user specified options
		var opts = $.extend({}, $.fn.quantityAddSubtract.defaults, options);

		// activate the script for each instans found in the selector
		return this.each(function () {
			var $this = $(this);
			// build element specific options
			var o = $.metadata ? $.extend({}, opts, $this.metadata()) : opts;

			if ($this.hasClass('quantityButtonsAttached') == false) {

				$this.addClass('quantityButtonsAttached');

				// insert a - (subtract) button
				$('<img/>', {
					'class': o.subtractClass,
					'src': o.subtractImage,
					'alt': '',
					click: function () {
						var floatValue = round_float($this.val(), 2);
						var floatNewVal = floatValue - o.step;
						var floatMinVal = round_float($this.closest('form').find('input[name="min_quantity"]').val(), 2);

						if (floatNewVal < floatMinVal) {
							$this.val(floatMinVal);
						}
						else if (floatNewVal < o.step) {
							$this.val(o.step);
						}
						else {
							$this.val(floatNewVal);
						}
					}
				}).insertBefore($this);

				// insert a + (add) button
				$('<img/>', {
					'class': o.addClass,
					'src': o.addImage,
					'alt': '',
					click: function () {
						var floatValue = round_float($this.val(), 2);
						var floatNewVal = floatValue + o.step;
						$this.val(floatNewVal);
					}
				}).insertAfter($this);

				// when the user removes the focus from the field, check the content
				$this.blur(function () {
					var qtycolli = parseFloat(o.step);
					var quantity = parseFloat($this.val().toString().replace(',', '.'));

					// check if colliMessage is defined. If it is, give the user this message, else give the standard danish message 
					var messageText = (typeof colliMessage != 'undefined') ? colliMessage : 'Antallet passer ikke med en hel pakning og er blevet justeret.';

					if (isNaN(quantity)) {
						$this.val('');
					}
					else {
						$this.val(quantity);
					}

					// show a message to the user
					if (qtycolli > 1 && quantity > 0 && round_float(quantity % qtycolli, 2) > 0) {
						$this.val(round_float(Math.ceil(quantity / qtycolli) * qtycolli, 2));
						$this.after('<div class="' + o.messageClass + '"><div>' + messageText + '</div></div>');
						$this.parent().find('.' + o.messageClass).fadeIn('slow', function () {
							window.setTimeout("$('." + o.messageClass + "').fadeOut('slow',function(){ $(this).remove(); })", 5000);
						});
					}
				});

			}
		});
	}

	// default values for the options
	$.fn.quantityAddSubtract.defaults = {
		addClass: 'jsQuantityAdd',
		addImage: '/images/btn_plus.gif',
		subtractClass: 'jsQuantitySubtract',
		subtractImage: '/images/btn_minus.gif',
		step: 1,
		messageClass: 'jsMessage'
	};

})(jQuery);



// jQuery plugin to replace the text in input fields on focus/blur or replace entire password field
// version: 1.0 - 2010-05-14 
(function ($) {
	$.fn.toggleInputText = function (options) {

		// create the options object with data from the default options and the user specified options
		var opts = $.extend({}, $.fn.toggleInputText.defaults, options);

		return ($(this).each(function () {
			var $this = $(this);
			title = $this.attr('title');

			// build element specific options
			var o = $.metadata ? $.extend({}, opts, $this.metadata()) : opts;

			if ($this.attr('type') == 'password') {
				// password field specific replacement

				var fakePassword = $('<input/>', {
					'class': $this.attr('class') + ' fakePassword',
					'value': $this.attr('title'),
					'type': 'text',
					css: {
						display: 'none'
					},
					focus: function () {
						$(this).hide();
						$this.show().focus();
					}
				});

				$this.after(fakePassword).blur(function () {
					if ($this.val() == "") {
						$this.hide().next('.fakePassword').show();
					};
				});

				if ($this.val() == "") {
					$this.hide().next('.fakePassword').show();
				};
			}
			else {
				// toggle values
				if ($this.val() == "") {
					$this.val(title);
				};
				$this.focus(function () {
					if ($this.val() == $this.attr('title')) {
						$this.val("");
					};
				}).blur(function () {
					if ($this.val() == "") {
						$this.val($this.attr('title'));
					};
				});
			}

			// hide the labels if the option is set to true
			if (o.hideLabels && $this.attr('id') != '') {
				$this.closest('form').find('label[for="' + $this.attr('id') + '"]').hide();
			}

		}));
	};

	// default values for the options
	$.fn.toggleInputText.defaults = {
		hideLabels: true
	};

})(jQuery);



// show the item specified in the href and hide what is specified in the options 
// version: 1.0 - 2010-05-12
(function ($) {

	$.fn.setActiveBox = function (options) {

		// create the options object with data from the default options and the user specified options
		var opts = $.extend({}, $.fn.setActiveBox.defaults, options);

		// activate the script for each instans found in the selector
		return this.each(function () {
			var $this = $(this);
			// build element specific options
			var o = $.metadata ? $.extend({}, opts, $this.metadata()) : opts;

			$this.click(function () {
				// show the specified element
				$($this.attr('href')).show();

				// if hideSelector is set, hide the elements in the selector
				if (o.hideSelector != null) {
					$(o.hideSelector).hide();
				}

				// stop the click on the link
				return false;
			})
		});
	}

	// default values for the options
	$.fn.setActiveBox.defaults = {
		hideSelector: null
	};

})(jQuery);



// beskrivelse
// version: 1.0 - 2010-05-12
(function ($) {

	$.fn.sendAjaxPost = function (options) {

		// create the options object with data from the default options and the user specified options
		var opts = $.extend({}, $.fn.sendAjaxPost.defaults, options);

		// activate the script for each instans found in the selector
		return this.each(function () {
			var $this = $(this);
			// build element specific options
			var o = $.metadata ? $.extend({}, opts, $this.metadata()) : opts;

			$this.click(function () {
				$.ajax({
					url: '/post.aspx?ajaxmode=1',
					type: 'post',
					data: o.data
				});

				if (o.after) {
					o.after($this);
				}


				return false;

			});
		});
	}

	// default values for the options
	$.fn.sendAjaxPost.defaults = {
		data: null,
		after: null
	};

})(jQuery);



// use history.back if the history is present, else fallback to the link.
// version: 1.0 - 2010-05-27
(function ($) {

	$.fn.historyBack = function (options) {

		// create the options object with data from the default options and the user specified options
		var opts = $.extend({}, $.fn.historyBack.defaults, options);

		// activate the script for each instans found in the selector
		return this.each(function () {
			var $this = $(this);
			// build element specific options
			var o = $.metadata ? $.extend({}, opts, $this.metadata()) : opts;

			$this.click(function () {
				if (history.length > 1) {
					// there is a history in the browser
					history.back();
					return false;
				}
				else {
					// there is not a history in the browser
					// let the link work as a normal link
				}
			});

		});
	}

	// default values for the options
	$.fn.historyBack.defaults = {
		option: 'value'
	};

})(jQuery);



// check if the specified logininfo actually returns a user
// version: 1.0 - 2010-05-28
(function ($) {

	$.fn.checkLogin = function (options) {

		// create the options object with data from the default options and the user specified options
		var opts = $.extend({}, $.fn.checkLogin.defaults, options);

		// activate the script for each instans found in the selector
		return this.each(function () {
			var $this = $(this);
			// build element specific options
			var o = $.metadata ? $.extend({}, opts, $this.metadata()) : opts;

			// check if a user exists with the specified login. If not, throw an error 
			$this.bind('submit.checklogin', function () {
				var strEmail = $('input[name="Email"]', this).val(),
						strPass = $('input[name="Password"]', this).val();

				// create the data object and fill it with data
				var objData = new Object();

				if (o.ajaxData) {
					// ajaxData contains data, so we fill it into the objData object
					objData = o.ajaxData;
				}
				else {
					// ajaxData is null, so we fill objData with as good data as possible from the visible text/password fields in the form
					$this.find(':text:visible[name],:password:visible[name]').each(function () {
						objData[$(this).attr('name')] = $(this).val();
					});
				}

				$.ajax({
					url: '/dynamic.aspx?data=checklogin&ajaxmode=1',
					data: objData,
					success: function (data) {
						if (data == '||') {
							// there's no login with those info, so we alert the user and stops the login form
							$this.find('.error').show();
							return false
						}
						else {
							// hide the error, if it's shown and remove the checklogin check (this one) and submit the form normally
							$this.find('.error').hide().end().unbind('submit.checklogin').submit();
						}
					}
				});

				// cancel the regular submit function
				return false;
			});
		});
	}

	// default values for the options
	$.fn.checkLogin.defaults = {
		ajaxData: null
	};

})(jQuery);



// activate paging on productlistpaging via ajax
// eva specific function 
// version: 1.0 - 2010-09-09
(function ($) {
	// global variables for all functions
	var $container;

	$.fn.ajaxProductlistpagingEva = function (options) {

		// create the options object with data from the default options and the user specified options
		var opts = $.extend({}, $.fn.ajaxProductlistpagingEva.defaults, options);

		// activate the script for each instans found in the selector
		return this.each(function () {
			var $this = $(this);

			// build element specific options
			var o = $.metadata ? $.extend({}, opts, $this.metadata()) : opts;

			// find out which page we are on
			var strActivePage = '1';
			if (location.href.match(o.curpageRegExMatch)) {
				strActivePage = location.href.match(o.curpageRegExMatch)[1];
			}

			// wrap the "current page" productlist and actions in a container, a track and a page container
			$this.find(o.productlistGroupSelector)
				.wrapAll('<div class="' + o.containerId + '"/>')
				.wrapAll('<div class="' + o.trackId + '"/>')
				.wrapAll('<div class="' + o.pageIdPrefix + strActivePage + ' ' + o.pageClass + '"/>');

			$container = $('.' + o.containerId, $this);

			// give the container some styles, so the pages can move inside this as on a "track"
			$container.css({
				position: 'relative',
				width: $container.width() + 'px',
				height: $container.height() + 'px',
				overflow: 'hidden'
			});

			$('.' + o.pageIdPrefix + strActivePage, $this).css({
				position: 'absolute',
				top: 0,
				left: $container.width() * (parseInt(strActivePage) - 1) + 'px',
				width: $container.width() + 'px',
				height: $container.height() + 'px'
			});

			$('.' + o.trackId, $this).css({
				position: 'absolute',
				top: 0,
				left: '-' + $container.width() * (parseInt(strActivePage) - 1) + 'px'
			});

			$this.find(o.pagingLinkSelector).live('click', function () {
				// make a new url
				var strUrl = $(this).attr('href').replace(/\+&\+/gi, '+%26+')  // replace & in the series
						.replace(/æ/gi, '%C3%A6').replace(/ø/gi, '%C3%B8').replace(/å/gi, '%C3%A5')  // æøåÆØÅ (all becomes lowercase versions)
						.replace(/©/gi, '%C2%A9').replace(/®/gi, '%C2%AE');  //©® 

				//var strUrl = $(this).attr('href').replace('+&+', '+%26+').replace('æ','%C3%A6').replace('ø','%C3%B8').replace('å','%C3%A5').replace('Æ','%C3%86').replace('Ø','%C3%98').replace('Å','%C3%85');
				var objCurPage = strUrl.match(o.curpageRegExMatch); // find the current page in the HREF

				var strCurpage = '1';
				if (objCurPage) {
					strCurpage = objCurPage[1];
				}

				if ($('.' + o.pageIdPrefix + strCurpage, $this).size() > 0) {
					// the page already exists


					$('.' + o.trackId, $this).animate({
						left: ($('.' + o.pageIdPrefix + strCurpage, $this).position().left * -1) + 'px'
					}, 'slow');

				} else {
					// the page did not exist 

					// decide which key/value to use (searchtext or key)
					var strKeyset2, strKeyset3, strDynamicurl;

					if (strUrl.match(o.searchtextRegExMatch)) {
						// find the search parameter in the HREF eg. "test" in /productlistpaging/?searchtext=test&paging=1&curpage=2

						strKeyset3 = strUrl.split('?')[1];
						strDynamicurl = '/dynamic.aspx?data=products&' + strKeyset3;
					} else {
						// find the second parameter in the HREF eg. "test group" in /productlistpaging/test group/?paging=1&curpage=2

						strKeyset2 = strUrl.match(o.keyRegExMatch)[1];
						strKeyset3 = strUrl.split('?')[1];

						var strKeyVal = typeof strKeyset2.split('/')[1] != 'undefined' ? strKeyset2.split('/')[1] : '';
						strDynamicurl = '/dynamic.aspx?data=products&collection=' + strKeyset2.split('/')[0] + '&key=' + strKeyVal + '&' + strKeyset3;
					}

					activatePagePreloader();
					getPage(strDynamicurl, strCurpage, o, $this);
				}

				// cancel the normal click event
				return false;
			});

		});
	}

	function getPage(strUrl, strPageId, o, pageContainer) {
		$.get(strUrl, function (data) {
			// find the body element  
			var startCut = data.indexOf('<body');
			var endCut = data.indexOf('</body>') + 7;

			// if the new page has content, insert it and scroll to it
			if ($(data.substring(startCut, endCut)).find(o.productlistGroupSelector).size() > 1) {
				$('.' + o.trackId, pageContainer).append('<div class="' + o.pageIdPrefix + strPageId + ' ' + o.pageClass + '"/>');

				$('.' + o.pageIdPrefix + strPageId, pageContainer).css({
					position: 'absolute',
					left: ($container.width() * (strPageId - 1)) + 'px',
					top: 0,
					width: $container.width() + 'px',
					height: $container.height() + 'px',
					overflow: 'hidden'
				}).html($(data.substring(startCut, endCut)).find(o.productlistGroupSelector));

				if (o.beforeAjaxAnimation) {
					o.beforeAjaxAnimation();
				}

				// hide the page preloader
				deActivatePagePreloader();

				$('.' + o.trackId, pageContainer).animate({
					left: ($('.' + o.pageIdPrefix + strPageId, pageContainer).position().left * -1) + 'px'
				}, 'slow');

				if (o.afterAjaxAnimation) {
					o.afterAjaxAnimation();
				}

			}
		});
	}

	// default values for the options
	$.fn.ajaxProductlistpagingEva.defaults = {
		containerId: 'productlistpaging-ajax-container',
		trackId: 'productlistpaging-ajax-track',
		pageIdPrefix: 'productlistpaging-ajax-page',
		pageClass: 'productlistpaging-ajax-page',
		hashPrefix: 'page',
		productlistGroupSelector: '.productlistActions,.productlist',
		pagingLinkSelector: '.productlistPaging a',
		curpageRegExMatch: /page=(\d+)/i,
		keyRegExMatch: /\/products\/(.+)\//i,
		searchtextRegExMatch: /searchtext=([^&]+)/i,
		beforeAjaxAnimation: null,
		afterAjaxAnimation: null
	};
})(jQuery);



// GLS lookup
// version: 1.0 - 2010-06-09
(function ($) {

	$.fn.glsLookup = function (options) {

		// create the options object with data from the default options and the user specified options
		var opts = $.extend({}, $.fn.glsLookup.defaults, options);

		// activate the script for each instance found in the selector
		return this.each(function () {
			var $this = $(this);
			// build element specific options
			var o = $.metadata ? $.extend({}, opts, $this.metadata()) : opts;

			// when selecting a GLS shop, update the input values
			$(o.glsContainer + ' :radio').live('click', function () {
				$(o.glsShopName).val($(this).metadata().name);
				$(o.glsShopAddress).val($(this).metadata().address);
			});

			// when selecting a shippingtype, toggle the glsData depending on whether useGLS is set or not
			$(o.shippingtypesContainer + ' :radio').click(function () {

				if ($(this).metadata().useGLS == true) {
					$(o.glsContainer).fadeIn();
				} else {
					$(o.glsContainer).fadeOut();
				}
			});

			// set basic values for street postalcode and country
			var strStreet = $(o.street).val();
			var strPostalcode = $(o.postalcode).val();
			var strCountry = $(o.country).val();

			// if an alternate delivery address is chosen, replace the previous values with these 
			if ($(o.postalcode2).size() > 0 && $(o.postalcode2).val() != '') {
				strStreet = $(o.street2).val();
				strPostalcode = $(o.postalcode2).val();
				strCountry = $(o.country2).val();
			}

			// do an ajax request to the server
			if (strPostalcode != '') {
				$.ajax({
					url: "/dynamic.aspx?data=glsdelivery&ajaxmode=1",
					data: {
						street: strStreet,
						postalcode: strPostalcode,
						country: strCountry
					},
					success: function (data) {
						if (data != '') {
							// replace the old GLS data with new
							$(o.glsContainer).html(data);
						}
						else {
							$(o.glsContainer).empty('');
						}

						// click the checked radiobutton so it saves data
						$(o.glsContainer).find(':radio:checked').click();
					}
				});
			}
		});
	}


	// default values for the options
	$.fn.glsLookup.defaults = {
		glsContainer: '#jsGlsdata',
		postalcode: '#addrPostalcode',
		street: '#addrStreet',
		country: '#addrCountry',
		postalcode2: '#addrPostalcode2',
		street2: '#addrStreet2',
		country2: '#addrCountry2',
		glsShopName: '#glsShopName',
		glsShopAddress: '#glsShopAddress',
		shippingtypesContainer: '#shippingtypes'
	};

})(jQuery);
// read out RSS and Atom feeds
// dependent on the jQuery plugin getFeed
// version: 1.0 - 2010-07-28
(function ($) {

	$.fn.readFeed = function (options) {

		// create the options object with data from the default options and the user specified options
		var opts = $.extend({}, $.fn.readFeed.defaults, options);

		// activate the script for each instans found in the selector
		return this.each(function () {
			var $this = $(this)
			// build element specific options
			var o = $.metadata ? $.extend({}, opts, $this.metadata()) : opts;

			if (o.feed) {

				if (o.feed.match('http://') == null) {
					o.feed = 'http://' + o.feed;
				}
				o.feed = '/proxy.aspx?datatype=xml&url=' + o.feed;

				$.getFeed({
					url: o.feed,
					success: function (feed) {
						if (feed.image) {
							$this.append('<a href="' + feed.image.link + '"><img src="' + feed.image.url + '" alt="' + feed.image.title + '"/></a>');
						}
						$this.append('<h2><a href="' + feed.link + '">' + feed.title + '</a></h2><h3>' + feed.description + '</h3>');
						var html = '';
						for (var i = 0; i < feed.items.length && i < 5; i++) {
							var item = feed.items[i];
							html += '<h3><a href="' + item.link + '">' + item.title + '</a></h3>';
							html += '<div class="updated">' + item.updated + '</div>';
							html += '<div class="description">' + item.description + '</div>';
						}
						$this.append(html);
					}
				});

			}

		});
	}

	// default values for the options
	$.fn.readFeed.defaults = {
		feed: false
	};

})(jQuery);

// round floats up / down
function round_float(x, n) {
	if (!parseInt(n)) var n = 0;
	if (!parseFloat(x))
		return false;
	return Math.round(x * Math.pow(10, n)) / Math.pow(10, n);
}


// activate ajax shopping
function activateAjaxShopping_NEW(objArg) {

	/* 
	* ajaxMode (default = false)             : defines whether or not ajaxMode is being used in the querystring
	* target (default = '.basketpreview')    : selector string to the element which should be replaced with the content
	* find (default = '.basketpreview')      : selector string to find a specific element inside the collected data
	*
	* if no arguments are passed, default values are set
	*/
	objArg = (typeof objArg == 'undefined') ? new Object : objArg;
	objArg.ajaxMode = (typeof objArg.ajaxMode == 'undefined') ? false : objArg.ajaxMode;
	objArg.target = (typeof objArg.target == 'undefined') ? '.basketpreview' : objArg.target;
	objArg.find = (typeof objArg.find == 'undefined') ? '.basketpreview' : objArg.find;

	var strAjaxMode = '';
	if (objArg.ajaxMode) {
		strAjaxMode = '&ajaxmode=1'; // call the page with ajaxmode = 1 
	}

	// remove products from basket and update basket preview
	$('.basketpreview .deleteBasketItem, .basketpreview .updateBasketItem').live('click', function (e) {
		e.preventDefault();
		$(this).closest('form').submit(function () {
			$.post('/post.aspx', {
				_Function: this._Function.value,
				_ReturnTo: '/dynamic.aspx?data=basket&template=basketpreview' + strAjaxMode,
				productid: this.productid.value,
				quantity: this.quantity.value,
				pkid: this.pkid.value
			}, function (data) {

				var $content = '';

				if (objArg.ajaxMode) {

					$content = $(data).filter(objArg.find);

				}
				else {

					// find the body element  
					var startCut = data.indexOf('<body');
					var endCut = data.indexOf('</body>') + 7;

					$content = $(data.substring(startCut, endCut));

				}

				// replace the target with the new content
				$(objArg.target).replaceWith($content);

				// only show the basketpreview if it still contains products
				if ($content.eq(1).filter(':empty').size() == 0) {
					$('#siteBasketpreviewLink').click();
				}

			}, 'html');

			// cancel the normal form submit
			return false;
		}).submit();
	});

	$('.basketpreview .updateBasketQuantity').live('submit', function (e) {
		$.post('/post.aspx', {
			_Function: this._Function.value,
			_ReturnTo: '/dynamic.aspx?data=basket&template=basketpreview' + strAjaxMode,
			productid: this.productid.value,
			quantity: this.quantity.value,
			pkid: this.pkid.value
		}, function (data) {

			var $content = '';

			if (objArg.ajaxMode) {

				$content = $(data).filter(objArg.find);

			}
			else {

				// find the body element  
				var startCut = data.indexOf('<body');
				var endCut = data.indexOf('</body>') + 7;

				$content = $(data.substring(startCut, endCut));

			}

			// replace the target with the new content
			$(objArg.target).replaceWith($content);

			// only show the basketpreview if it still contains products
			if ($content.eq(1).filter(':empty').size() == 0) {
				$('#siteBasketpreviewLink').click();
			}

		}, 'html');

		// cancel the normal form submit
		return false;
	});

	// add products to basket and update basketpreview
	$('form.jsUpdateBasket').live('submit', function () {
		var strAlert;

		// cancel the Ajax call, if some values are missing
		if (this.productid.value == '' || this.quantity.value == '') {

			strAlert = (typeof strErrorFieldRequired == 'undefined') ? 'Udfyld alle n\u00F8dvendige felter' : strErrorFieldRequired;

			modalAlert(strAlert);
			return false;
		}

		// cancel the Ajax call, if the quantity is less than minimum quantity
		if (parseInt(this.min_quantity.value) > parseInt(this.quantity.value)) {

			strAlert = (typeof strErrorOrderMinimum == 'undefined') ? 'Du skal bestille minimum' : strErrorOrderMinimum;
			var strAlertPcs = (typeof strErrorOrderMinimumPcs == 'undefined') ? 'stk.' : strErrorOrderMinimumPcs;

			modalAlert(strAlert + ' ' + this.min_quantity.value + ' ' + strAlertPcs);
			return false;
		}


		$.post("/post.aspx", {
			_Function: this._Function.value,
			_ReturnTo: '/dynamic.aspx?data=basket&template=basketpreview' + strAjaxMode,
			productid: this.productid.value,
			quantity: this.quantity.value
		}, function (data) {

			var $content = '';

			if (objArg.ajaxMode) {
				$content = $(data).filter(objArg.find);
			}
			else {

				// find the body element  
				var startCut = data.indexOf('<body');
				var endCut = data.indexOf('</body>') + 7;

				$content = $(data.substring(startCut, endCut));

			}
			// replace the target with the new content
			$(objArg.target).replaceWith($content);
			$('#siteBasketpreviewLink').click();
			window.basketpreview = setTimeout("$('#siteBasketpreviewLink').click()", 7000);
		}, 'html');


		// this is used to show that the form have been sent to the server and the basket have been updated  
		$('.added', this).fadeIn(100, function (a) {
			setTimeout(function () {
				$('.added').fadeOut('slow');
			}, 2000)
		});

		// cancel the normal form submit
		return false;
	});

	// hack to make Internet Explorer respect the live event on the forms (it could otherwise just use the browser default action)
	$('form.jsUpdateBasket :submit').live('click', function () {
		$(this).closest('form').submit();
		return false;
	});
}


// client captcha
// add captcha functionality to a form containing specific image and textinput
// version: 1.0 - 2010-12-22
(function ($) {

	$.fn.clientCaptcha = function (options) {

		// create the options object with data from the default options and the user specified options
		var opts = $.extend({}, $.fn.clientCaptcha.defaults, options);

		// activate the script for each instans found in the selector
		return this.each(function () {
			var $this = $(this)
			// build element specific options
			var o = $.metadata ? $.extend({}, opts, $this.metadata()) : opts;

			var $image = $this.find(o.captchaImage).eq(0);
			var $input = $this.find(o.captchaText).eq(0);

			var arrCaptchaImages = [
				['34jkljkl', 'together going'],
				['bcv789b79', 'according force'],
				['eqw98e78q', 'auction force'],
				['h12jg3j', 'crowd sunday'],
				['jk56k5334', 'watch except']
			]

			var intImageId = parseInt(Math.random() * arrCaptchaImages.length, 10);
			var strCaptchaUrl = arrCaptchaImages[intImageId][0];
			var strCaptchaText = arrCaptchaImages[intImageId][1];

			$image.attr('src', o.imageUrlPre + strCaptchaUrl + o.imageUrlPost).data(o.imageDataAttr, strCaptchaText);

			// form submit 
			$this.submit(function () {

				if ($input.val().toLowerCase() == $image.data(o.imageDataAttr)) {
					$this.find(o.controlInput).val(o.controlInputValue);
					return true;
				}
				else {
					window.location.href = window.location.href;
					return false;
				}

			});

		});
	}

	// default values for the options
	$.fn.clientCaptcha.defaults = {
		captchaImage: '.captchaImage',
		captchaText: '.captchaText',
		imageDataAttr: 'captchaText',
		imageUrlPre: '/images/captcha_',
		imageUrlPost: '.jpg',
		controlInput: '.validateAccess',
		controlInputValue: 'truest'
	};

})(jQuery);


/*
ON LOAD
*********************************************/
// jQuery 'onReady' script - runs when the document have been loaded, but before images

$(function () {

	//validateForms();

	activateAjaxShopping_NEW({
		ajaxMode: true,
		target: '#siteBasketpreviewLink, .basketpreview',
		find: '#siteBasketpreviewLink, .basketpreview'
	});

	$('form').formvalidation();

	autocompletePostalCode3('#tDelivery #addrPostalcode', '#tDelivery #addrCity', '#tDelivery #addrCountry');
	autocompletePostalCode3('#tDelivery #addrPostalcode2', '#tDelivery #addrCity2', '#tDelivery #addrCountry2');
	autocompletePostalCode3('#tCreatecustomer #customerPostalcode', '#tCreatecustomer #customerCity', '#tCreatecustomer #customerCountry');

	productlistImage();
	postPolls();
	quizWizzard();
	tracktrace();
	changeProductImage();
	flashLoad();
	openPopups();

	MenuStructuring();

	$('.tProducts').ajaxProductlistpagingEva();


	$('.jsQuantity').quantityAddSubtract();
	$('.jsInput').toggleInputText({
		hideLabels: false
	});
	$('.jsShowForgotPwd, .jsShowLogin').setActiveBox();
	$('.jsGoBack').historyBack();
	$('#menuLoginForm form, #siteLoginForm form').checkLogin();
	$('#tPayment').glsLookup();
	$('.rssFeed').readFeed();


	// toggle optional delivery address
	$('.deliveryForm').find(':radio[name="optionaldelivery"]').click(function () {
		if (this.value == 1) {
			$('#tDelivery').find('.secondaryAddress .secondaryAddresinput').removeAttr('disabled');
			$('#tDelivery').find('.secondaryAddress').show();
		} else {
			$('#tDelivery').find('.secondaryAddress .secondaryAddresinput').attr('disabled', 'disabled');
			$('#tDelivery').find('.secondaryAddress').hide();
		}
	});
	$('#tDelivery').find('.secondaryAddress:hidden .secondaryAddresinput').attr('disabled', 'disabled');


	// tests if the terms are accepted on the orderstatus page before going on
	$('#tOrderstatus').find('form').submit(function () {
		if ($('#TermsAccepted').is(':checked') == false) {
			var strAlert = typeof strAcceptTermsError == 'undefined' ? 'Du skal acceptere handelsbetingelserne' : strAcceptTermsError;
			alert(strAlert);
			return false;
		}
	});


	// show/hide the menuLogin container, based on the class
	$('#menuLogin>a').click(function () {
		$(this).blur().parent().toggleClass('itemLoginActive');
		return false;
	});

	// add/remove product to/from wishlist
	$('.productLinkwishlist').not('.productLinkwishlistRemove').sendAjaxPost({
		after: function () { $('.productLinkwishlist').toggle(); }
	});
	$('.productLinkwishlistRemove').sendAjaxPost({
		after: function () { $('.productLinkwishlist').toggle(); }
	});

	// add/remove product to/from favorites
	$('.productLinkfavorites').not('.productLinkfavoritesRemove').sendAjaxPost({
		after: function () { $('.productLinkfavorites').toggle(); }
	});
	$('.productLinkfavoritesRemove').sendAjaxPost({
		after: function () { $('.productLinkfavorites').toggle(); }
	});

	// add lightbox/colorbox functionality to shoppinglist links
	$('.productLinkshoppinglist').colorbox({
		onComplete: function () {
			$('#tUpdateshoppinglist .jsQuantity').quantityAddSubtract();
			$('#tUpdateshoppinglist .jsInput').toggleInputText();
			$('#tUpdateshoppinglist').find('form').ajaxForm({
				success: function (data) {
					$(document).one('cbox_closed', function () {
						$.fn.colorbox({
							html: data
						});
					});
					$.fn.colorbox.close();
				}
			})
		}
	});



	// add lightbox/colorbox functionality to tip a friend links
	$('.productLinktipafriend').colorbox({
		onComplete: function () {
			$('#tTipafriend .jsInput').toggleInputText();
			$.fn.colorbox.resize();
			$('#tTipafriend').find('form').formvalidation().ajaxForm({
				beforeSubmit: function (formData, jqForm, options) {
					if (jqForm.data('allOk') == 0) {
						return false;
					}
				},
				success: function (data) {
					$(document).one('cbox_closed', function () {
						$.fn.colorbox({
							html: data
						});
					});
					$.fn.colorbox.close();
				}
			})
		}
	});

	// add lightbox/colorbox functionality to print links
	$('.productLinkprint').colorbox({
		iframe: true,
		width: 700,
		height: '80%'
	});




	// standard lightbox feature for productinfo page - building the container
	updateProductImagesLightbox();

	// standard lightbox feature for productinfo page - activating the overlay
	$('#productImages a').colorbox({
		inline: true,
		href: '#productImagesLightbox',
		onOpen: function () {
			$('#productImagesLightbox').find('.imageContainer img[src$="' + escape($(this).attr('href')) + '"]:first').show().siblings('img').hide();
			$('#productImagesLightbox').find('.productImageActions').html($('#productAdditions').children().clone(true));
		},
		onComplete: function () {
			$('#productImagesLightbox').find('.imageContainer').css({
				height: $('#productImagesLightbox').find('.imageContainer').height()
			});

			if ($('#productImagesLightbox').find('.imageContainer img').size() > 1) {
				updateLightboxButtons();

				$('#productImagesLightbox').find('.imageContainer .lightboxNavigation').click(function () {
					$this = $(this);
					$img = $this.siblings('img:visible');

					if ($img.siblings('img').size() > 0) {
						if ($img.next('img').size() > 0 && $this.hasClass('next')) {
							$img.fadeOut('fast', function () {
								$img.next('img').fadeIn('slow');
								updateLightboxButtons();
							});
						}
						else if ($img.prev('img').size() > 0 && $this.hasClass('prev')) {
							$img.fadeOut('fast', function () {
								$img.prev('img').fadeIn('slow');
								updateLightboxButtons();
							});
						}
					}
				});
			}
			else {
				$('#productImagesLightbox').find('.imageContainer .lightboxNavigation').hide();
			}
		}
	});



	// delete from basket
	$('#tBasket').find('.jsDelete').live('click', function () {
		$($(this).attr('href')).ajaxSubmit({
			beforeSubmit: activatePagePreloader,
			success: function (data) {
				// find the body element  
				var startCut = data.indexOf('<body');
				var endCut = data.indexOf('</body>') + 7;

				var $content = $(data.substring(startCut, endCut));
				$('#tBasket').replaceWith($content);

			}
		});
		return false;
	});

	// update quantity in basket
	$('#tBasket').find('.quantity input').live('change', function () {
		var strPkid = $(this).attr('name').replace('quantity', ''),
				intValue = $(this).val();

		$('#update' + strPkid).get(0).quantity.value = intValue;

		$('#update' + strPkid).ajaxSubmit({
			beforeSubmit: activatePagePreloader,
			success: function (data) {
				// find the body element  
				var startCut = data.indexOf('<body');
				var endCut = data.indexOf('</body>') + 7;

				var $content = $(data.substring(startCut, endCut));
				$('#tBasket').replaceWith($content);

			}
		});
		return false;
	});

	$('#tBasket').find('#basketWrapping').live('click', function () {
		$(this).closest('form').ajaxSubmit();
	});

	// toggle the visibility of the optional delivery form
	$('.jsOptionalDelivery').click(function () {
		var $this = $(this);

		if ($this.attr('checked')) {
			$('.secondaryAddress').show();
		} else {
			$('.secondaryAddress').hide();
		}
	});


	// empty city and postalcode input fields, when changing country 
	$('#tDelivery').find(':input[name=country]').change(function () {
		$('#tDelivery').find(':input[name=city], :input[name=postalcode]').val('');
		$('#addrPostalcode').flushCache();
	})
	.end().find(':input[name=country],:input[name=country2]').change(function () {
		$('#tDelivery').find(':input[name=city2], :input[name=postalcode2]').val('');
		$('#addrPostalcode2').flushCache();
	});



	// ajax submitting the subscribe newsletter form
	$('#newsletterSubscription').ajaxForm({
		beforeSubmit: function (formData, jqForm, options) {
			if (jqForm.data('allOk') == 0) {
				return false;
			}
			$('#newsletterSubscription').find('.preloader').fadeIn('fast');
		},
		success: function () {
			$('#newsletterSubscription').find('.preloader').hide();
			$('#newsletterSignupSuccess').fadeIn('fast', function () {
				setTimeout("$('#newsletterSignupSuccess').fadeOut('fast')", 5000);
			});

		}
	});

	$('#siteNewsletterSignupButton').click(function (e) {
		e.preventDefault();
		$('#newsletterSubscription').submit();
	});

	$('.newsletterSignupForm a.button').click(function (e) {
		e.preventDefault();
		$(this).next('.inpSubmit').click();
	});

	// promotion articles rotation
	if ($('#promotion .promotionImages img').size() > 1) {
		$('#promotion .promotionImages').cycle({
			speed: 'fast',
			timeout: 4000,
			pager: '#promotion .promotionNav',
			pagerAnchorBuilder: function (idx, slide) {
				// return selector string for existing anchor 
				return '#promotion .promotionNav li:eq(' + idx + ') a';
			},
			pagerEvent: 'mouseover',
			pauseOnPagerHover: true
		});

		// force a click event on the carousel navigation links, to counteract the cycle plugin event unbinder.
		$('#promotion .promotionNav a').click(function () {
			location.href = this;
		});
	}

	// toggle visibility of input fields on the customerinfo page, when clicking on the edit profile button
	$('#tCustomerinfo').find('.inpEditProfile').click(function () {
		$('#tCustomerinfo .updatecustomerForm').find('span.value,:text, select, textarea,:submit,:button').toggle();
		return false;
	});

	// on submitting forms on the shoppinglist page, ask if the user wants to save the list for later. 
	$('#tShoppinglist').find('.jsTransferShoppinglistToBasket').submit(function () {
		var preserveText = (typeof preserveListText != 'undefined') ? preserveListText : 'Vil du bevare listen?';
		var agree = confirm(preserveText);
		if (agree) {
			this.preserve.value = '1';
		}
	});


	// galleries on pages should have lightbox/colorbox functionality and an icon at mouseover
	$('#pageGallery').find('a[rel="imageGallery"]').append('<img class="zoom" src="/images/icon_zoom.png" alt="">').colorbox({
		current: ''
	});

	// images on normal pages should have lightbox/colorbox functionality
	$('a[rel="pageImages"]').colorbox({
		current: ''
	});

	// activate search suggests - type-ahead search
	$('.searchform input[name="searchtext"]').searchSuggest({
		ajaxDataFormat: 'SearchSuggest',
		ajaxSearchtextKey: 'key',
		appendTo: '#siteSearchbar .searchform',
		containerCss: {
			width: 'auto'
		},
		afterAjax: function () {
			$('.jsQuantity').quantityAddSubtract();
		},
		afterClose: function () {
			$('#siteSearchLink').removeClass('active').blur().next().hide();
		}
	});

	$('.getEmailLink').click(function () {
		var $this = $(this);
		$.ajax({
			url: '/dynamic.aspx?ajaxmode=1&data=article&template=getemail',
			data: {
				key: $this.attr('href').substring(1)
			},
			success: function (data) {
				$this.replaceWith(data);
			}
		});
		return false;
	});




	// toggle visibility of the searchbox
	$('#siteSearchLink, #siteCountryLink, #siteBasketpreviewLink').live('click', function (e) {
		var $this = $(this);

		clearTimeout(window.basketpreview);

		if ($this.attr('id') == 'siteSearchLink' && $('#tFrontpage').size() > 0) {
			$this.next().find('.shadowRight').remove();
		}


		if ($this.hasClass('active')) {
			$this.removeClass('active').blur().next().hide();
		} else {
			$('#siteSearchbar > div:visible, #siteCountrySelect > div:visible, #siteBasketpreview > div:visible, #siteWishlist > div:visible').hide().prev().removeClass('active');
			$('.menuLinkActive').click();

			$this.blur().next().css('top', '-9000px').show();

			if ($this.attr('id') == 'siteBasketpreviewLink') {
				resizeBasketPreview();
			}


			// find out what the height of the box is
			var boxHeight = $this.next().outerHeight();

			$this.next().css('top', boxHeight * -1).animate({ 'top': 33 }, 400, 'easeInOutQuart', function () { $(this).prev().addClass('active') }).find(':text:first').focus();
		}

		e.preventDefault();
	});


	productPages();


	// activate the frontpage themes
	themeSelector();

	activateFrontpageSplash();

	// on submitting the search form, forward to the correct URL
	$('#siteSearchForm, .tSearch>.searchform>form').submit(function (e) {
		e.preventDefault();
		location.href = '/search/' + this.searchtext.value + '/';
	});

	// when clicking on the search button on the searchform, make it submit the form
	$('.tSearch .searchform, .mediaSearch, .mediaLogin').find('.button').click(function (e) {
		e.preventDefault();
		$(this).closest('form').submit();
	});


	// activate checkbox script
	$('#productfilters input:checkbox').checkbox({
		empty: '/images/empty.png'
	});

	$('#productfilters ul ul').prev('a').click(function (e) {
		e.preventDefault();
		var $this = $(this);

		if ($this.parent().hasClass('open')) {
			$this.next('ul').slideUp(function () {
				$(this).parent().removeClass('open');
			});
		}
		else {
			$this.next('ul').slideDown(function () {
				$(this).parent().addClass('open');
			});
		}
	});
	// when the user selects new series on the productlist, update the list accordingly
	$('#productfilters').find(':checkbox').click(updateProductlist);

	$('#productfilters').find('a').click(function (e) {
		e.preventDefault();
		$('#productfilters').find(':checkbox').removeAttr('checked');

		$(this).parent().siblings('.open').find('ul').slideUp(function () {
			$(this).parent().removeClass('open');
		});


		updateProductlist($(this));
	});


	// when loading the productlist and productinfo pages, resize the right column to fit the height of the page
	//$('.collectionDescription, .seriesDescription').height($('.collectionDescription, .seriesDescription').parent().innerHeight());

	$('#productActions a.buttonBuy').click(function (e) {
		$(this).closest('form').submit();
		e.preventDefault();
	});


	// star rating on comments
	$('.setRating .lblInline').hide();
	$('.setRating input[type=radio]').rating();


	// make the commentsform submit via an Ajax submit
	$('.commentsForm form').submit(function (e) {
		$(this).find('input[name=Captcha]').val('true');
		$(this).attr('Captcha', 'true').ajaxSubmit().find('.response').fadeIn(500).focus();
		this.reset();
		e.preventDefault();
	});
	$('.commentsForm form .button').click(function (e) {
		$(this).closest('form').submit();
		e.preventDefault();
	});

	$('#productWriteReview').click(function (e) {
		$(this).hide();
		$('.commentsForm').show().find(':text:first').focus();
		e.preventDefault();
	});

	// activate show more button on comments
	$('#productShowMore').click(function (e) {
		e.preventDefault();
		var $this = $(this);
		$this.prevAll('.comment:hidden').fadeIn(500);


		var strProductid = $this.metadata().productid;
		var intPage = parseInt($this.metadata().page);
		var intCommentcount = parseInt($this.metadata().commentcount);

		if ((intPage + 1) <= Math.ceil((intCommentcount / 10))) {
			$this.metadata().page = intPage + 1;

			$.ajax({
				url: '/dynamic.aspx?data=productcomments&key=' + strProductid + '&page=' + (intPage + 1),
				success: function (data) {
					$this.prevAll('.comment:first').after(data);
					$this.prevAll('.comment').find('input[type=radio]').rating();
				}
			});
		} else {
			$this.remove();
		}
	});


	// changing product on selection of new size 
	$('#productSizeSelection').change(function () {
		location.href = '/productinfo/' + $(this).val() + '/';
	});

	// breadcrumb show/hide
	$('#siteBreadCrumb').find('.breadcrumbs > a').mouseover(function () {
		$(this).addClass('active').siblings().removeClass('active');

		var intIndex = $('#siteBreadCrumb').find('.breadcrumbs > a').index(this);

		$('#siteBreadCrumb ul').hide().eq(intIndex).show();
		$(document).bind('mouseover.breadcrumb', function (e) {
			var $target = $(e.target);

			if (!$target.is('#siteBreadCrumb') && $target.closest('#siteBreadCrumb').size() < 1) {
				$('#siteBreadCrumb .active').removeClass('active');
				$('#siteBreadCrumb ul').hide();
				$(document).unbind('mouseover.breadcrumb');
			}
		});
	});

	// activate the reseller page map and list
	resellerPage();



	// cufon replacing
	Cufon.replace('h1, h2, #universeMenu .name, #productsMenu .productNews strong, #productsMenu .productNews span');


	$('#productColors').find('a').click(function (e) {
		var $this = $(this);

		e.preventDefault();

		if (typeof $this.metadata().imagefilename != '') {
			$('#largeProductImage').attr('href', $this.metadata().zoomimagefilename).find('img').attr('src', $this.metadata().imagefilename);
			updateProductImagesLightbox();
		}

		$('.jsUpdateBasket').find('input[name=productid]').val($this.metadata().productid);
		$('#productContainer').find('h1:first').addClass('cufonReplacing').text($this.attr('title'));

		if ($this.metadata().cansell == 'true') {
			$('#productActions').show();
			$('#stockText').hide();
		} else {
			$('#productActions').hide();
			$('#stockText').show();
		}

		// replace the text with cufon and remove the class again 
		Cufon.replace('.cufonReplacing');
		$('.cufonReplacing').removeClass('cufonReplacing');

	});

	// on resize, make sure that the best image is shown
	$(window).resize(function () {

		if (window.onResizeTimeout != 'undefined') {
			clearTimeout(window.onResizeTimeout);
		}

		window.onResizeTimeout = setTimeout(function () {
			$('#jsThemeSelector').find('img[src$=_active.png]').parent().click();
		}, 500);

	});


	$('#linkARDemo').click(function (e) {
		e.preventDefault();

		var player = $f('ARDemoVideoLink', '/files/flowplayer-3.2.5.swf');

		$.colorbox({
			innerHeight: 360,
			innerWidth: 640,
			inline: true,
			href: '#ARDemoVideoLink',
			onComplete: function () {
				player.load();
			},
			onClosed: function () {
				player.unload();
			}
		});
	});

	$('.basketpreview .continueshopping').live('click', function (e) {
		e.preventDefault();
		$('#siteBasketpreviewLink').click();
	});

	// activate scroll functionality on the basketpreview if needed
	$('.basketScrollUp, .basketScrollDown').live('click', function () {
		// stop an eventual timeout, if the user clicks to scroll up or down
		clearTimeout(window.basketpreview);

		var currentBasketItemIndex = $('.scrollContainer').data('scrollItem');

		if (!currentBasketItemIndex) {
			currentBasketItemIndex = 0;
		}

		var nextBasketItem;
		if ($(this).hasClass('basketScrollUp')) {

			if (currentBasketItemIndex < 1) {
				currentBasketItemIndex = 1;
			}

			nextBasketItem = $('.scrollContainer table').get(currentBasketItemIndex - 1);
			$('.scrollContainer').data('scrollItem', currentBasketItemIndex - 1);

		} else {
			if (currentBasketItemIndex > $('.scrollContainer table').size() - 2) {
				currentBasketItemIndex = $('.scrollContainer table').size() - 2;
			}

			nextBasketItem = $('.scrollContainer table').get(currentBasketItemIndex + 1);
			$('.scrollContainer').data('scrollItem', currentBasketItemIndex + 1);

		}

		$('.scrollContainer').scrollTo(nextBasketItem, 800, { easing: 'easeInOutQuart' });
	});

	// set the language data and submit the form
	$('#siteCountrySelect').find('ul a').click(function (e) {
		e.preventDefault();

		var strLangid = $(this).attr('href').substr($(this).attr('href').indexOf('#') + 1);
		var strUrl = location.href;

		$('#countryselectLangid').val(strLangid);
		$('#countryselectUrl').val(strUrl);

		$('#siteCountrySelect').find('form').submit();
	});

	$('#discountcodeQuestion').bind('mouseenter mouseleave', function () {
		$('#discountcodeExplanation').toggle();
	});

	$('#giftcertificateQuestion').bind('mouseenter mouseleave', function () {
		$('#giftcertificateExplanation').toggle();
	});


	// make the contact-form submit when clicking the send-button
	$('.contactForm').find('.actions a').click(function (e) {
		e.preventDefault();
		$(this).closest('form').submit();
	});

	$('.openLightbox').colorbox({
		innerHeight: "85%",
		innerWidth: "500px",
		iframe: true,
		onOpen: function () {
			window.openLightboxFullUrl = this.href;
			if (this.href.indexOf('#') != -1) {
				this.href = this.href.substr(0, this.href.indexOf('#'));
			}
		},
		onLoad: function (a, b, c) {
			this.href = window.openLightboxFullUrl;
		}
	});

	$('.mediaLogin').find('form').clientCaptcha();

	$('#productsMenu').find('.campaignarticles').cycle({
		pager: '#campaignarticlesNav',
		pagerAnchorBuilder: function (idx, slide) {
			// return selector string for existing anchor 
			return '#campaignarticlesNav a:eq(' + idx + ')';
		}
	}).cycle('pause');
	$('#productsMenu').find('.productnewsGroups').cycle({
		timeout: 0
	}).siblings('.btnPrev').click(function () {
		$('#productsMenu').find('.productnewsGroups').cycle('prev');
	}).siblings('.btnNext').click(function () {
		$('#productsMenu').find('.productnewsGroups').cycle('next');
	});


	// submit groupsmenu click conversion
	$('#menuProductsLink').click(countGroupsmenuConversion);

});  // jQuery ready end



// activate the frontpage splashbox
function activateFrontpageSplash() {
	var $splash = $('#splashBox');
	var splashCookie = readCookie('showFrontpageSplash');

	if ($splash.size() > 0 && splashCookie == null) {

		$splash.insertAfter('#themesContainer');

		/*
		if (objActiveTheme.hideSplash == false) {
			$splash.delay(5000).fadeIn();
		}
		*/

		$('#splashBoxClose, #splashBox .jsCancel').click(function (e) {
			e.preventDefault();
			createCookie('showFrontpageSplash', '1', 2);
			$splash.fadeOut();
		});
	}
}

// update productlist with filters
function updateProductlist($clickedObject) {
	$inputLink = $(this);

	if ($clickedObject instanceof jQuery) {
		$inputLink = $clickedObject;
	}

	// has to have a setTimeout function to not trigger the serialize event before the data is stored in the form
	window.setTimeout(function () {
		var arrUrlParts = location.pathname.substr(1).split('/');
		var strUrl = '';

		strUrl = '/dynamic.aspx?data=' + arrUrlParts[0] + '&collection=' + $inputLink.metadata().collection + '&key=' + $inputLink.metadata().group + '&' + $('#productfilters').serialize();

		/*

		if (arrUrlParts.length == 2) {
		strUrl = '/dynamic.aspx?data=' + arrUrlParts[0] + '&collection=' + arrUrlParts[1] + '&' + $('#productfilters').serialize();
		} else {
		strUrl = '/dynamic.aspx?data=' + arrUrlParts[0] + '&collection=' + arrUrlParts[1] + '&key=' + arrUrlParts[2] + '&' + $('#productfilters').serialize();
		}
		*/

		if (typeof strSearchtext != 'undefined') {
			strUrl = '/dynamic.aspx?data=' + arrUrlParts[0] + '&searchtext=' + strSearchtext + '&' + $('#productfilters').serialize();
			if (typeof strSparepartsearch != 'undefined') {
				strUrl = strUrl + '&sparepartsearch=1';
			}
		}

		activatePagePreloader();
		$('.productlistpaging-ajax-container').fadeOut(500);

		$.ajax({
			url: strUrl,
			success: function (data) {

				var startCut = data.indexOf('<body');
				var endCut = data.indexOf('</body>') + 7;
				var $productlist = $(data.substring(startCut, endCut)).find('.productlist, .productlistActions');

				// if the new page has content, insert it and scroll to it
				if ($productlist.size() > 0) {
					$('.productlistpaging-ajax-container').replaceWith($productlist);
					$('.tProducts').ajaxProductlistpagingEva();
				}
				deActivatePagePreloader();

			},
			error: function () {
				deActivatePagePreloader();
			}
		});
	}, 100);

};


// if popups are used on the page, show it
// have to be in the load event, since "ready state" is to early
$(window).load(function () {
	// set default id on the popup
	var strCurrentPKID = '0';

	// if the strPagePKID variable is set, replace the old id 
	if (typeof strPagePKID != 'undefined') { strCurrentPKID = strPagePKID; }

	// if a popup should be shown and the cookie is not set to 1
	if ($('#pagePopup').size() > 0 && readCookie('pagePopup' + strCurrentPKID) != '1') {
		$.colorbox({
			href: $('#pagePopup').attr('href'),
			iframe: true,
			width: '700',
			height: '80%',
			title: '<a href="#" onclick="closeAndHidePopup(' + strCurrentPKID + '); return false;">Luk og vis ikke igen</a>',
			onOpen: function () {
				$('#colorbox').addClass('pagePopup');
			},
			onClosed: function () {
				$('#colorbox').removeClass('pagePopup');
			}
		});
	}
});

// close and hide the pagePopup
function closeAndHidePopup(strPKID) {
	createCookie('pagePopup' + strPKID, '1', 1);
	$.colorbox.close();
}

// standard lightbox feature for productinfo page - building the container
function updateProductImagesLightbox() {

	$('#productImagesLightbox .imageContainer').find('img').remove()
		.end().prepend($('#productImages img').clone().removeAttr('id')).find('.zoom').remove()
		.end().find('img').each(function () {

			var strSrc = $(this).attr('src').replace('/thumbnail/', '/productzoom/').replace('/productmain/', '/productzoom/');
			$(this).attr('src', strSrc);

		}).hide();

} // updateProductImagesLightbox end


function autocompletePostalCode3(pcodeField, cityField, countryField) {
	if ($.isFunction($(this).autocomplete)) {//kontroller om autocomplete-funktionen er importeret
		$(pcodeField)
			.autocomplete('/dynamic.aspx?data=citynames&ajaxmode=1', {
				formatItem: function (row, i, max) {
					return row[0].replace('_', ' ');
				},
				max: 9,
				extraParams: {
					countryid: function () { return $(countryField).val(); }
				},
				width: '200px'
			})
			.result(function (event, data, formatted) {

				if (data) {
					var result = data[0].split('_');
					$(pcodeField).val(result[0]);
					if ($(pcodeField).val() != '') {
						$(cityField).val(result[1]);
					}
					else {
						$(cityField).val('');
					}
				}

			});

		//$(cityField).attr('readonly', true).addClass('disabled');
	}
}


function activatePagePreloader() {
	$('#pagePreloader').fadeTo('fast', 0.5);
}
function deActivatePagePreloader() {
	$('#pagePreloader').fadeOut('fast');
}

// productImagesLightbox buttons update
function updateLightboxButtons() {

	var $imageContainer = $('#productImagesLightbox').find('.imageContainer');
	var $prev = $imageContainer.find('.prev'),
			$next = $imageContainer.find('.next'),
			$img = $imageContainer.find('img:visible');

	// enable/disable the next-button as needed
	if ($img.nextAll('img').size() < 1) { $next.addClass('disabled'); }
	else { $next.removeClass('disabled'); }

	// enable/disable the prev-button as needed
	if ($img.prevAll('img').size() < 1) { $prev.addClass('disabled'); }
	else { $prev.removeClass('disabled'); }

} // updateLightboxButtons end





// beskrivelse
// version: 1.0 - 2010-06-08
(function ($) {

	$.fn.formvalidation = function (options) {

		// create the options object with data from the default options and the user specified options
		var opts = $.extend({}, $.fn.formvalidation.defaults, options);

		// activate the script for each instans found in the selector
		return this.each(function () {
			var objForm = this;
			var $this = $(objForm);
			// build element specific options
			var o = $.metadata ? $.extend({}, opts, $this.metadata()) : opts;


			// if the 'allOk' is already set as a string on the form, validation is already active and does not need to bet set again.
			if (typeof ($this.data('allOk')) == 'string') {
				return false;
			}

			$this.data('allOk', '1');

			// select all fields that require a certain mask validation
			$this.find('.jsValidate').bind('keyup blur', validateField);

			$this.submit($.fn.formvalidation.validate);
		});
	}

	$.fn.formvalidation.validate = function () {
		var $this = $(this), bitSendform = true;

		// Run a validation on all required fields
		$this.find(':input[name*=_Required], :input[name*=_required]').each(function () {
			var relatedInput = $this.find(':input[name=' + $(this).attr('name').replace(/_Required$/i, '').replace(/^_/, '') + ']');
			relatedInput.each(validateField);
		});

		// test if any active fields are not valid
		$this.find(':input').not('[disabled]').each(function () {
			var $input = $(this);

			if ($input.data('validatedOk') == false) {
				bitSendform = false;
			}
		});

		if (!bitSendform) {
			$this.data('allOk', '0');

			var strAlert = 'Du skal udfylde alle felter med * med korrekt data';
			alert(strAlert);
			return false;
		} else {
			$this.data('allOk', '1');
		}
	}

	// single field validation
	function validateField(evt) {
		var $this = $(this), objForm = $this.closest('form'), strActivateKeyup = 'jsTextfieldactivatekeyup', bitOk = true, re;

		if (evt.type != "keyup" || $this.hasClass(strActivateKeyup)) {
			// if the input doesn't allow keyup events, activate it (this happens at first blur event)
			if (!$this.hasClass(strActivateKeyup)) {
				$this.addClass(strActivateKeyup);
			}

			// validate field

			/*
			* Valideringen skal understoette foelgende data, krav og afgraensninger:
			*
			* Fornavn og efternavn skal indeholde tekst.
			* Gade skal indeholde minimum et ord efterfulgt af et mellemum og et tal.
			* postnummer skal vaere 4 tegn i Danmark.
			* By bliver automatisk indsat efter postnummer.
			* Telefon skal indeholde 8 tegn for dansk tlf.nummer.
			* E-mail skal indeholde min. 1 tegn efterfulgt af et @ (snabel a) efterfulgt af min. 1 tegn efterfulgt af et . (punktum) efterfulgt af 2-4 karakterer.
			*
			*
			* For at identificere de forskellige felttyper, skal hvert felt have en css klasse der fort�ller hvordan feltet skal valideres.
			* Forslag til css klasser, der kan benyttes til validering samt beskrivelse af hvad de skal validere:
			*
			* jsValidate: bruges kun til at identificere hvilke felter der skal valideres.
			* jsValidatetext: validerer om feltet ikke er tomt - dette skal vaere basis form for validering, alle andre valideringstyper goer automatisk dette
			* jsValidatefullname: kontrollerer om der er minimum 2 ord i feltet
			* jsValidatepostalcode: tester om postnummeret er korrekt i forhold til det enkelte lands krav
			* jsValidatephone: Ser om telefonnummeret er indtastet korrekt i forhold til landets krav
			* jsValidatemail: E-mail skal indeholde de paakraevede dele specificeret ovenfor
			* jsValidateaddress: Korrekt indtastet adresse - efter ovenstaaende specifikation
			* jsValidaterepeat: Tester om teksten i feltet er det samme som i feltet med det tilknyttede ID (i css klassen "jsValidaterepeatfromIDPAAFELT"
			*
			*
			*/
			// test if there is a required field for this input field
			var strCurrentName = $this.attr('name');
			var objRequiredField = $('input[name=_' + strCurrentName + '_required],input[name=' + strCurrentName + '_Required]', objForm);
			var bitRequired = (objRequiredField.size() > 0);

			if ($this.hasClass('jsValidatetext')) {
				re = /.+/;
			}
			else
				if ($this.hasClass('jsValidatefullname')) {
					re = /[^ ]+ [^ ]+/;
				}
				else
					if ($this.hasClass('jsValidatepostalcode')) {
						// her boer man have forskellige landevalg, saa valideringen ved hvordan den skal validere? ligenu gaar den kun efter 4 cifre
						//re = /^\d{4}$/;
						re = /^\d+$/;
					}
					else
						if ($this.hasClass('jsValidatephone')) {
							// her boer man have forskellige landevalg, saa valideringen ved hvordan den skal validere? ligenu gaar den kun efter 8 cifre
							re = /^\d{8}$/;
						}
						else
							if ($this.hasClass('jsValidatemail')) {
								re = /^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]+$/i;
							}
							else
								if ($this.hasClass('jsValidateaddress')) {
									re = /^(.)+\s[1-9]/;
								}
								else {
									// hvis der ikke er nogen specifik validering, skal der alligevel valideres paa om der er indhold i feltet.
									re = /.+/;
								}

			bitOk = re.test($this.val());

			// hvis feltet er et repeat felt, f.eks. gentag password eller e-mail,
			// skal valideringen i stedet gaa paa om feltets indhold er det samme som det tilknyttede
			if ($this.hasClass('jsValidaterepeat')) {
				var strAllclasses = $this.attr('class').split(' '), strOriginalInputId;

				$.each(strAllclasses, function (i, val) {
					if (val.indexOf('jsValidaterepeatfrom') > -1) {
						strOriginalInputId = val.replace('jsValidaterepeatfrom', '');

						return false;
					}
				});

				bitOk = ($this.val() == $('#' + strOriginalInputId).val() && $this.val != '');
			}

			// hvis et postalcode felt ikke indeholder tal mellem 1000 og 9999, skal der vises en fejl
			/*
			if ($this.hasClass('jsValidatepostalcode') && bitOk) {
			var intPostal = parseInt($this.val());
			if (intPostal < 1000 || intPostal > 9999){
			bitOk = false;
			}
			}
			*/

			if ((bitRequired && bitOk) || (!bitRequired && $this.val() != '' && bitOk)) {
				// hvis feltet er korrekt udfyldt
				$this.removeClass('textfield_error').siblings('.validationMessage').removeClass('validationMessageError');
				$this.addClass('textfield_valid').siblings('.validationMessage').addClass('validationMessageValid');

				$this.data('validatedOk', true);
			}
			else
				if ((bitRequired && !bitOk) || (!bitRequired && $this.val() != '' && !bitOk) || (bitRequired && $this.val() == '')) {
					// hvis feltet ikke er udfyldt korrekt.
					$this.removeClass('textfield_valid').siblings('.validationMessage').removeClass('validationMessageValid');
					$this.addClass('textfield_error').siblings('.validationMessage').addClass('validationMessageError');

					$this.data('validatedOk', false);
				}
				else
					if ($this.val() == '' && !bitRequired) {
						// hvis feltet ikke er udfyldt og det ikke er paakraevet
						$this.removeClass('textfield_error').siblings('.validationMessage').removeClass('validationMessageError');
						$this.removeClass('textfield_valid').siblings('.validationMessage').removeClass('validationMessageValid');

						$this.data('validatedOk', true);
					}
					else {
					}
		}
	} // validateField end



	// default values for the options
	$.fn.formvalidation.defaults = {
		option: 'value'
	};

})(jQuery);


// searchSuggest - type ahead
// version: 1.1 - 2010-08-19
(function ($) {

	$.fn.searchSuggest = function (options) {

		// create the options object with data from the default options and the user specified options
		var opts = $.extend({}, $.fn.searchSuggest.defaults, options);

		// activate the script for each instans found in the selector
		return this.each(function () {
			var $this = $(this);
			// build element specific options
			var o = $.metadata ? $.extend({}, opts, $this.metadata()) : opts;

			// remove the autocomplete from the input
			$this.attr('autocomplete', 'off').keyup(function (e) {
				var intKey = e.keyCode;
				// only allow certain keystrokes
				if ((intKey > 47 && intKey < 58) || (intKey > 36 && intKey < 41) || (intKey > 64 && intKey < 91) ||
						(intKey > 96 && intKey < 112) || (intKey > 185 && intKey < 223) ||
						intKey == 32 || intKey == 226 ||
						intKey == 46 || intKey == 8) {

					// if the timeout is still counting down, cancel it to stop the client from hammering the server with search requests
					if (typeof ($.fn.searchSuggest.searchSuggestTimeout) != 'undefined') {
						clearTimeout($.fn.searchSuggest.searchSuggestTimeout);
					}

					// set the timeout to when the search should be made after last keystroke
					$.fn.searchSuggest.searchSuggestTimeout = window.setTimeout(function () {
						searchSuggestAjax($this, o);
					}, o.timeout);
				}
			});
		});
	}


	// timeout container for the searchsuggestion container
	$.fn.searchSuggest.searchSuggestTimeout;


	// search suggest ajax request
	// strSort: optional method of sorting
	function searchSuggestAjax($this, o, strSort) {

		// if no sorting method has been chosen, use the default
		if (!strSort) {
			strSort = o.defaultSort
		};

		if ($this.val().length >= o.minLength) {
			var strQuery = '/dynamic.aspx?ajaxmode=1&data=' + o.ajaxDataFormat + '&template=' + o.ajaxTemplate + '&sort=' + strSort + '&' + o.ajaxSearchtextKey + '=' + encodeURI($this.val());

			$.ajax({
				url: strQuery,
				type: 'get',
				success: function (data) {

					// collect the position and dimensions of the searchfield
					var inputX = $this.offset().left,
							inputY = $this.offset().top,
							inputHeight = $this.outerHeight(),
							inputWidth = $this.outerWidth();

					// position the search container below the searchfield aligned to the left.
					var containerX = inputX + o.offsetX,
							containerY = inputY + inputHeight + o.offsetY;

					// If horisontalAlign is set to right, position the search container to be aligned to the right
					if (o.horisontalAlign == 'right') {
						containerX = inputX - (o.containerCss.width - inputWidth);
					}

					// set the default container CSS and let the user extend it as needed
					var containerCssObject = $.extend({
						position: 'absolute',
						top: containerY,
						left: containerX,
						zIndex: o.zIndex
					}, o.containerCss);

					// if the user specified a container to append the searchSuggest other than the default, cancel
					// the CSSS positioning and only fetch the optional containerCSS, as the user would rather specify the positioning if needed
					if (o.appendTo != $.fn.searchSuggest.defaults.appendTo) {
						containerCssObject = o.containerCss;
					}

					//if the container do not already exist, create it and append it to the body
					if ($('#' + o.containerId).size() == 0) {
						var ajaxSearchBox = $('<div/>', {
							'id': o.containerId,
							css: containerCssObject,
							html: data
						}).css('opacity', 0).appendTo(o.appendTo).fadeTo(200, 1);
					} else {
						// if the container already exists, just replace the content with new data
						$('#' + o.containerId).html(data);
					}

					// unbind previous events and append new ones.
					// if the user press Esc on the keyboard or click outside the search container, close the search container and unbind the events
					$(document).unbind('.searchSuggest').bind('keyup.searchSuggest click.searchSuggest', function (e) {
						if (e.which == 27 || (e.type == 'click' && (!$(e.target).closest('#' + o.containerId).size() > 0 && (o.appendTo != $.fn.searchSuggest.defaults.appendTo && !$(e.target).closest(o.appendTo).size() > 0)))) {
							$('#' + o.containerId).remove();
							$(document).unbind('.searchSuggest');

							// run the afterClose callback if it is set
							if (o.afterClose) {
								o.afterClose();
							}
						}
					});

					// run the afterAjax callback if it is set
					if (o.afterAjax) {
						o.afterAjax();
					}
				}
			});
		} else {
			$('#' + o.containerId).remove();
		}
	}


	// default values for the options
	$.fn.searchSuggest.defaults = {
		ajaxDataFormat: 'products',
		ajaxTemplate: 'ajaxsearch',
		ajaxSearchtextKey: 'searchtext',
		containerCss: {
			background: '#fff', // IE6-7 bugfix, so elements can't be clicked through the searchcontainer. It can be replaced with a (transparent) background-image instead.
			width: 300
		},
		appendTo: 'body',
		containerId: 'ajaxSearchSuggestContainer',
		defaultSort: 'pop',
		horisontalAlign: 'right',
		minLength: 2,
		offsetX: 0,
		offsetY: 5,
		timeout: 200,
		zIndex: 1000,
		afterAjax: null,
		afterClose: null
	};

})(jQuery);


function initializeBBQ() {

	// insert the needed classes and default content
	$('#site').addClass('jsBbq');
	$('#siteMain').addClass('jsBbq-content').wrapInner('<div class="jsBbq-default"/>');

	// For each .bbq widget, keep a data object containing a mapping of
	// url-to-container for caching purposes.
	$('.jsBbq').each(function () {
		$(this).data('bbq', {
			cache: {
				// If url is '' (no fragment), display this div's content.
				'': $(this).find('.jsBbq-default'),
				'/': $(this).find('.jsBbq-default')
			}
		});
	});

	// For all links inside a .jsBbq widget, push the appropriate state onto the
	// history when clicked.
	$('#areaMenu a[href^="/groups/"], #siteBreadcrumb a[href^="/groups/"]').live('click', function (e) {
		var state = {},  // Get the id of this .jsBbq widget.
		id = $(this).closest('.jsBbq').attr('id'),  // Get the url from the link's href attribute, stripping any leading #.
		url = $(this).attr('href');

		// Set the state!
		state[id] = url;
		$.bbq.pushState(state);

		// save the request for the latest clicked url, so the callback knows which to show, even if the return order is not the same as the requested order
		$(this).closest('.jsBbq').data('currentLinkUrl', url);

		// And finally, prevent the default link click behavior by returning false.
		e.preventDefault();
		//return false;

	});

	// Bind an event to window.onhashchange that, when the history state changes,
	// iterates over all .bbq widgets, getting their appropriate url from the
	// current state. If that .bbq widget's url has changed, display either our
	// cached content or fetch new content to be displayed.
	$(window).bind('hashchange', function (e) {

		// Iterate over all .bbq widgets.
		$('.jsBbq').each(function () {
			var that = $(this),   // Get the stored data for this .bbq widget.
			data = that.data('bbq'),   // Get the url for this .bbq widget from the hash, based on the
			// appropriate id property. In jQuery 1.4, you should use e.getState()
			// instead of $.bbq.getState().
			url = $.bbq.getState(that.attr('id')) || '';

			// If the url hasn't changed, do nothing and skip to the next .bbq widget.
			if (data.url === url) {
				return;
			}

			// Store the url for the next time around.
			data.url = url;

			// Remove .bbq-current class from any previously "current" link(s).
			that.find('a.selected').removeClass('selected');

			// Hide any visible ajax content.
			that.find('.jsBbq-content').children(':visible').hide();

			// Add .bbq-current class to "current" nav link(s), only if url isn't empty.
			url && that.find('#areaMenu a[href="' + url + '"]').addClass('selected');

			// create a url to the dynamic page, to get a faster and smaller page
			// the url could be built up of a dataformat, key and template
			var arrLinkUrl = url.substr(1).split('/');
			var strLinkUrl = '/dynamic.aspx?ajaxmode=1';
			var strBreadcrumbUrl = '/dynamic.aspx?ajaxmode=1&data=breadcrumb';

			if (arrLinkUrl[0] && arrLinkUrl[0] != '') {
				strLinkUrl = strLinkUrl + '&data=' + arrLinkUrl[0];
				strBreadcrumbUrl = strBreadcrumbUrl + '&maindata=' + arrLinkUrl[0];
			}
			if (arrLinkUrl[1] && arrLinkUrl[1] != '') {
				strLinkUrl = strLinkUrl + '&key=' + arrLinkUrl[1];
				strBreadcrumbUrl = strBreadcrumbUrl + '&mainkey=' + arrLinkUrl[1];
			}
			if (arrLinkUrl[2] && arrLinkUrl[2] != '') {
				strLinkUrl = strLinkUrl + '&template=' + arrLinkUrl[2];
				strBreadcrumbUrl = strBreadcrumbUrl + '&maintemplate=' + arrLinkUrl[2];
			}

			// update the breadcrumb if the URL contains something
			if (url) {
				$('#siteBreadcrumb').load(strBreadcrumbUrl + ' >div');
			}

			if (data.cache[url]) {
				// Since the widget is already in the cache, it doesn't need to be
				// created, so instead of creating it again, let's just show it!
				data.cache[url].show();

			}
			else {
				// Show "loading" content while AJAX content loads.
				that.find('.jsBbq-loading').show();

				// Create container for this url's content and store a reference to it in
				// the cache.


				$.ajax({
					url: strLinkUrl,
					success: function (strData) {

						// find the body element  
						var startCut = strData.indexOf('<body');
						var endCut = strData.indexOf('</body>') + 7;

						// Create container for this url's content and store a reference to it in
						// the cache.

						var strStyle = '';
						if (that.data('currentLinkUrl') != url && typeof that.data('currentLinkUrl') != 'undefined') {
							strStyle = ' style="display: none;"';
						}

						// if the new page has content, insert it and scroll to it
						data.cache[url] = $('<div class="jsBbq-item"' + strStyle + '/>')				// Append the content container to the parent container.
						.appendTo(that.find('.jsBbq-content'))
						.html($(strData.substring(startCut, endCut)));

						// reactivate the add and subtract features on productlists 
						$('.jsQuantity').quantityAddSubtract();

						$('.tProducts').ajaxProductlistpaging({
							beforeAjaxAnimation: function () {
								$('.jsQuantity').quantityAddSubtract();
							}
						});

						// Content loaded, hide "loading" content.
						that.find('.jsBbq-loading').hide();
					}
				});


			}
		});
	});

	// Since the event is only triggered when the hash changes, we need to trigger
	// the event now, to handle the hash the page may have loaded with.
	$(window).trigger('hashchange');
}


function MenuStructuring() {

	// append the dark layer to the left column for later use
	$('#siteLeft').prepend('<div id="menuLinkUnderlay"/>');
	$('#universeMenu').css('backgroundPosition', '-874px 390px');
	//$('#productsMenu').css('backgroundPosition', '-874px 391px');


	// insert a hidden groupsmenu overlay, that hides everything else
	$('<div id="groupsmenuBackground"/>').insertAfter('#siteMain');


	// insert the hidden page overlay, for when the user opens the menus
	$('<div />', {
		'id': 'pageOverlay',
		css: {
			background: '#000',
			display: 'none',
			height: '100%',
			left: '0',
			opacity: '0.5',
			position: 'fixed',
			top: '0',
			width: '100%',
			zIndex: '5'
		}
	}).insertAfter('#siteMain').click(function () {
		// remove the active class on the previously active menulink
		$('#siteLeft').find('.menuLinkActive').removeClass('menuLinkActive');

		// hide the open menu
		$('#menuLinkUnderlay').hide();
		$('#pageOverlay, #groupsmenuBackground').fadeOut(500);

		var strBackPos = '-874px 390px';
		if ($('.menuOpen').attr('id') == 'productsMenu') {
			strBackPos = '-874px 391px';
		}

		$('.menuOpen').removeClass('menuOpen').addClass('animating').animate({ backgroundPosition: strBackPos }, 600, 'easeInOutQuart').children().animate({
			left: '-100%'
		}, 600, 'easeInOutQuart', function () {
			$(this).parent().removeClass('animating').hide();
		});
	});

	// remove focus marking on links in the menu
	$('#siteLeft').find('a').focus(function () {
		$(this).blur();
	});

	//MK: Clicking on the first of the 4 menu items in the universe menu will fake a click on the "shop" link.
	$('#universeMenuContainer .menuItems .items4 li:first a').click(function() {
		$('#menuProductsLink').click();
		return false;
	});
	
	// clicking on menulinks shows the dark layer and activate the menuslider
	$('#siteLeft').find('.menuLink').click(function (e) {
		// activate the menusliders

		var $this = $(this);
		var objMenu = $($this.attr('href'));
		var bolMenuHasClass = objMenu.hasClass('menuOpen');

		// if one of the menus are animating, ignore the new click, as too many items moving at the same time can be confusing for the user
		if ($('.animating').size() > 0) {
			return false;
		}

		// remove the active class on the previously active menulink
		$('#siteLeft').find('.menuLinkActive').removeClass('menuLinkActive');

		// hide the open menu
		$('#menuLinkUnderlay').hide();

		var strBackPos = '-874px 390px';
		if ($('.menuOpen').attr('id') == 'productsMenu') {
			strBackPos = '-874px 391px';
		}


		$('.menuOpen').removeClass('menuOpen').addClass('animating').animate({ backgroundPosition: strBackPos }, 600, 'easeInOutQuart').children().animate({
			left: '-1105px'
		}, 600, 'easeInOutQuart', function () {
			$(this).parent().removeClass('animating').hide();
		});

		// if the clicked menu was not the active menu
		if (!bolMenuHasClass) {

			// if the productmenu is opened, show the special background, otherwise show the normal pageoverlay
			if (objMenu.attr('id') == 'productsMenu') {
				objMenu.find('.campaignarticles, #campaignarticlesNav, .productNews, .productCollections').css('opacity', 0);
				$('#pageOverlay').fadeOut(500);
				$('#groupsmenuBackground').fadeIn(500, function () {
					objMenu.find('.campaignarticles, #campaignarticlesNav, .productNews, .productCollections').animate({
						'opacity': 1
					}, 1000).cycle('resume');
				});
			}
			else {
				$('#pageOverlay').fadeIn(500);
				$('#groupsmenuBackground').fadeOut(500);
				$('.campaignarticles, #campaignarticlesNav, .productNews, .productCollections').cycle('pause').animate({
					'opacity': 0
				}, 500);
			}

			// add the active class on the active menulink
			$this.addClass('menuLinkActive').blur();

			// position the underlay correctly and show it
			var intTop = ($this.offset().top + ($this.height() / 2)) - ($('#menuLinkUnderlay').height() / 2);
			$('#menuLinkUnderlay').css('top', intTop).show();

			// calculate where to position the menu
			var intViewportHeight = $(window).height();
			if (intViewportHeight - intTop < $($this.attr('href')).height()) {
				intTop = intViewportHeight - $($this.attr('href')).height();
			}

			// hide open topbar overlays
			$('#siteSearchbar > div:visible, #siteCountrySelect > div:visible, #siteBasketpreview > div:visible, #siteWishlist > div:visible').hide().prev().removeClass('active');

			strBackPos = '0 390px';
			if (objMenu.attr('id') == 'productsMenu') {
				strBackPos = '0 391px';
				intTop = 38;
			}

			// open the menu at the correct position
			objMenu.css('top', intTop).show().addClass('menuOpen').addClass('animating').animate({ backgroundPosition: strBackPos }, 600, 'easeInOutQuart').children().animate({
				left: 0
			}, 600, 'easeInOutQuart', function () {
				$(this).parent().removeClass('animating');

				// measure if any menuitems contains more than one line
				$('#universeMenu').find('.menuitemName > span').each(function () {
					var $this = $(this);

					if ($this.height() > 60) {
						$this.parent().addClass('menuitemDualline');
					}
				});

			});
		} else {
			$('#pageOverlay, #groupsmenuBackground').fadeOut(500);
			$('.productNews, .campaignarticles, #campaignarticlesNav, .productCollections').animate({
				'opacity': 0
			});
		}

		// stop the normal click event
		e.preventDefault();

	}).each(function () {
		// move the menus to the same structure level as the siteLeft, but right before #siteLeft
		$($(this).attr('href')).insertBefore('#siteLeft');
	});

	// set all empty productgroups to be transparent
	$('#productsMenu, .tGroups').find('.productGroups li, .grouplist li').not('.hasProducts').css('opacity', '0.3');


	// on hover on the product collections, activate the correct productgroups accordingly
	$('#productsMenu').find('.productCollections li').mouseover(function () {
		var strCollection = $(this).metadata().collection;
		$(this).addClass('active').siblings().removeClass('active');
		$('#productsMenu').find('.productGroups').each(function () {
			if ($(this).metadata().collection == strCollection) {
				$(this).show().siblings('.productGroups').hide();
			}
		});
	});

	// on hover on the product collections on the groups page, activate the correct productgroups accordingly
	$('.tGroups').find('.GroupsCollections li').mouseover(function () {
		var strCollection = $(this).metadata().collection;
		$(this).find('a').addClass('active').parent().siblings().find('a').removeClass('active');
		$('.tGroups').find('.grouplist').each(function () {
			if ($(this).metadata().collection == strCollection) {
				$(this).show().siblings('.grouplist').hide();
			}
		});
	}).filter(':first').mouseover();

	
	var strLocation = location.href;
	var strLocationShop = strLocation.substr(strLocation.length - 5);
	
	if (strLocationShop == 'shop/' || strLocationShop == '/shop') {
		frontpageAnimations(1);
		$('#menuProductsLink').click();
	}

	/*
	$('#universeMenu').find('.menuitemName > span').each(function(){
	var $this = $(this);
		
	if ($this.height() > 60){
	$this.parent().addClass('menuitemDualline');
	} 
	});
	*/
}

function productPages() {
	$('#productPageLinks').find('a').click(function (e) {
		var $this = $(this);
		var $page = $($this.attr('href'));

		// if the container is not populated, fetch the content
		var strPageid = $page.metadata().pageid;
		if (!$page.hasClass('jsPopulated') && strPageid) {
			$page.addClass('jsPopulated');

			$.ajax({
				url: '/dynamic.aspx?load=main&data=page&template=producttextpage&key=' + strPageid,
				success: function (data) {
					$page.append(data);
				}
			})
		}

		// hide the content pages and show only the selected
		$('#productPageContainer').children().hide().filter($this.attr('href')).show().trigger('productPageUpdate');
		$this.addClass('active').blur().parent().siblings().find('a').removeClass('active');

		if ($this.parent().hasClass('commentButton')) {
			$('#productWriteReview').hide();
			$('.commentsForm').show().find(':text:first').focus();
		}

		// cancel the default behaviour
		e.preventDefault();
	});

	// if the productViews page is being updated, make sure the comments have read more links if neccessary
	$('#productViews').bind('productPageUpdate', function (e) {
		$(this).find('.comment .text').each(function () {
			if ($(this).height() > 28) {
				$(this).height(28).next('.readmore').show().click(function (e) {
					$(this).hide().prev().css('height', '100%');
					e.preventDefault();
				});
			}
		});
	});

}


// activation of themes on the frontpage
function themeActivation(strChosenTheme, iState) {

	// test if the themes object variable exists
	if (typeof objThemes != 'undefined') {

		// if the themesContainer doesn't already exist, create it in the html
		if ($('#themesContainer').size() == 0) {
			if (iState) {
				$('<div id="themesContainer" style="z-index: -1;"/>').insertBefore('#site');
			}
			else {
				$('<div id="themesContainer"/>').insertBefore('#site');
			}

		}

		// specify the height and width of the screen
		var intScrHeight = $(window).height(),
				intScrWidth = $(window).width();

		// screen format  -  16:9 returns 1.77  -  4:3 returns 1.33  -  5:4 returns 1.25 
		var fltScreenFormat = parseInt((intScrWidth / intScrHeight) * 100, 10) / 100;

		// per default, pick the first theme in the object as the active theme
		var objActiveTheme = objThemes.themes[0];

		// if a theme have been previously chosen, run through all the themes and find out which one to show
		if (typeof strChosenTheme != 'undefined') {
			for (var i = 0, themeMax = objThemes.themes.length; i < themeMax; i++) {
				if (objThemes.themes[i].themeId == strChosenTheme) {
					objActiveTheme = objThemes.themes[i];
					break;
				}
			}
		}


		// save the current active theme
		createCookie('activeTheme', objActiveTheme.themeId, 1);

		// setup variables and to figure out which setup that suits the screen
		var intHeight, intWidth, fltSetupFormat,
				objSetups = objActiveTheme.themeSetup,
				strAcceptedSizes = '',
				arrAcceptedSizes, intAcceptedIndex = 0;

		// per default, pick the first setup in the object as the active setup
		var objActiveSetup = objSetups[0];

		// run through all setups for the active theme to figure out how many of them fits the profile
		for (var i = 0, sizesMax = objSetups.length; i < sizesMax; i++) {
			intWidth = objSetups[i].size.split('x')[0];
			intHeight = objSetups[i].size.split('x')[1];
			fltSetupFormat = parseInt((intWidth / intHeight) * 100, 10) / 100;

			if (fltSetupFormat <= fltScreenFormat && intHeight >= intScrHeight && intWidth >= intScrWidth) {
				// we have the correct format and the sizes fit

				// insert a comma, if the variable is not empty
				if (strAcceptedSizes.length > 0) {
					var intTestWidth = objSetups[strAcceptedSizes.substr(strAcceptedSizes.length - 1)].size.split('x')[0],
							intTestHeight = objSetups[strAcceptedSizes.substr(strAcceptedSizes.length - 1)].size.split('x')[1];

					var fltLastFormat = parseInt((intTestWidth / intTestHeight) * 100, 10) / 100;

					if (fltSetupFormat < fltLastFormat) {
						strAcceptedSizes = i + ',' + strAcceptedSizes;
					}
					else {
						strAcceptedSizes = strAcceptedSizes + ',' + i;
					}
				}
				else {
					strAcceptedSizes = strAcceptedSizes + i;
				}


			}
		}

		// if there have been at least one accepted setup, choose the last in the array, since this it the smallest of them
		if (strAcceptedSizes != '') {
			arrAcceptedSizes = strAcceptedSizes.split(',');
			intAcceptedIndex = parseInt(arrAcceptedSizes[arrAcceptedSizes.length - 1]);
			objActiveSetup = objSetups[intAcceptedIndex];
		}

		// set the new themeId to be used in the <div>
		var themeId = objActiveTheme.themeId + objActiveSetup.size;

		if ($('#' + themeId).size() > 0) {
			// if the theme already exists, fade the other ones out and fade this one in

			$('#themesContainer .theme:visible').css('z-index', '1');
			$('#' + themeId).css('z-index', '10').fadeIn(1000, function () {
				$(this).siblings().hide();
			});

		}
		else {
			// if the theme doesn't exist, create it and insert all the HTML

			var $image = $('<img/>', {
				'src': '/images/' + objActiveSetup.imagefilename,
				'alt': ''
			}).load(function () {
				// when the image have been loaded, fade out the other themes and fade this one in

				$('#themesContainer .theme:visible').css('z-index', '1');


				if (!iState || $(this).closest('.theme').siblings().size() > 0) {
					$(this).closest('.theme').css('z-index', '10').fadeIn(1000, function () {
						$(this).siblings().hide();

						// when the theme have been faded in, fade the text in, that is positioned on top of the image if we are on the frontpage 
						if (location.pathname == '/') {
							$(this).find('.text').delay(500).css({
								'opacity': '0',
								'display': 'block'
							}).animate({
								'opacity': 1,
								'filter': ''
							}, 1000, function () {
								if ($('#siteLeft').position().left == -150) {
									frontpageAnimations(1);
								}
							});
						}

					});
				}
				else {
					$(this).closest('.theme').css('z-index', '10').show().siblings().hide();
				}

			});

			// create the quote image and insert it in a link, if the link exists
			var pageImage = '';
			if (typeof objActiveTheme.themeQuoteImage != 'undefined') {
				if (typeof objActiveTheme.themeLink != 'undefined') {
					pageImage += '<a href="' + objActiveTheme.themeLink + '">';
				}

				pageImage += '<img src="' + objActiveTheme.themeQuoteImage + '" alt=""/>';

				if (typeof objActiveTheme.themeLink != 'undefined') {
					pageImage += '</a>';
				}
			}

			var $text = $('<div/>', {
				'class': 'text',
				'style': objActiveSetup.css
			}).html(pageImage);

			var $hotspots = $('<div id="hotspotContainer"/>');

			// find the related hotspots product container and give it the correct inline styles
			var $hotspotsProductContainer = $('#hotspotProductContainer' + objActiveTheme.pkid).attr('style', objActiveSetup.css);

			$hotspotsProductContainer.data('originalHeader', $hotspotsProductContainer.find('.hotspotQuote').html());

			$hotspotsProductContainer.find('.buttonClose').click(function (e) {
				e.preventDefault();
				//$hotspotsProductContainer.find('.hotspotProgress div').stop().css('width', 0);
				$hotspotsProductContainer.find('.hotspotProgress div').stop().parent().remove();
				$('.hotspot').addClass('stopPulsate');
				//initializeHotspotAutoshow(objActiveTheme.pkid);

				$hotspotsProductContainer.find('.hotspotQuote').html($hotspotsProductContainer.data('originalHeader'));

				$(this).closest('.productItem').slideUp(500);
				$('.hotspot').removeClass('active');
			});

			// run through all hotspots on the theme and insert them
			if (typeof objActiveTheme.hotspots != 'undefined') {
				var $tempHotspot;

				// for each hotspot
				for (var j = 0, intMax = objActiveTheme.hotspots.length; j < intMax; j++) {
					var currentHotspot = objActiveTheme.hotspots[j];

					$tempHotspot = $('<a />', {
						'href': '#',
						'class': 'hotspot',
						'style': currentHotspot.styles[intAcceptedIndex].css
					}).data('product', currentHotspot.productid).data('header', currentHotspot.header).click(function (e) {
						e.preventDefault();
						//$hotspotsProductContainer.find('.hotspotProgress div').stop().css('width', 0);
						$hotspotsProductContainer.find('.hotspotProgress div').stop().parent().remove();
						$(this).addClass('stopPulsate');

						var intProductid = $(this).data('product');

						$('#hotspotProductContainer' + objActiveTheme.pkid)
							.find('.productItem').slideUp(500)
							.filter(function () {
								return $(this).metadata().productid == intProductid;
							}).delay(550).slideDown(500);

						$hotspotsProductContainer.find('.hotspotQuote').html($(this).data('header'));

						$('.hotspot').removeClass('active');
						$(this).addClass('active');

					})

					
					$hotspots.append($tempHotspot);
				}

			}

			// append it all to the theme
			$('<div/>', {
				'id': themeId,
				'class': 'theme'
			}).appendTo('#themesContainer').append($image, $text, $hotspots.children(), $hotspotsProductContainer);

			
			// start pulsating the hotspots
			pulsateElements($('#themesContainer').find('.hotspot'));

			// start showing hotspot products automatically
			initializeHotspotAutoshow(objActiveTheme.pkid);

		}



		// if the splash is present on the frontpage

		var $splashBox = $('#splashBox');

		if ($splashBox.size() > 0) {

			// find out if the splash may be shown on this theme
			if (objActiveTheme.hideSplash) {
				$splashBox.fadeOut();
			}
			else {
				$splashBox.fadeIn();
			}

		}

	}
	else {
		if (location.pathname.indexOf('/groups/') == -1) {
			$.ajax({
				url: '/dynamic.aspx?data=page&key=frontpage&template=themes&ajaxmode=1',
				success: function (data) {
					window.objThemes = $.parseJSON(data);
					themeSelector(1);
				}
			});
		}

	}
}

function themeSelector(iState) {
	if (typeof objThemes != 'undefined') {

		var strListHtml = '';
		var strUrl = location.hostname;

		for (var i = 0, themeMax = objThemes.themes.length; i < themeMax; i++) {
			if (typeof objThemes.themes[i].themeWebsite != 'undefined' && strUrl.indexOf(objThemes.themes[i].themeWebsite) == -1) {
				//strListHtml = strListHtml + '<a href="#theme_' + objThemes.themes[i].themeId + '" style="display: none;"><img src="/images/theme_selector_inactive.png" alt=""/></a>';
			}
			else {
				strListHtml = strListHtml + '<a href="#theme_' + objThemes.themes[i].themeId + '"><img src="/images/theme_selector_inactive.png" alt=""/></a>';
			}

		}

		$('<div id="jsThemeSelector"/>').html(strListHtml).appendTo('#siteLeft');

		// when clicking on one of the links, the selector should be activated and the theme should be loaded
		$('#jsThemeSelector a').click(function (e) {
			// cancel the default action
			e.preventDefault();
			var $this = $(this);

			// if there is an animation going on, cancel the current theme-shift
			if ($('#themesContainer .theme:animated').size() > 0) {
				return false;
			}

			var strChosenTheme = $this.attr('href').substr($this.attr('href').indexOf('#theme_') + 7);

			$this.blur().find('img').attr('src', '/images/theme_selector_active.png');
			$this.siblings().find('img').attr('src', '/images/theme_selector_inactive.png');

			// activate the theme
			themeActivation(strChosenTheme, iState);

		});

		strCurrentThemeId = readCookie('activeTheme');

		//var intIndex = Math.floor(Math.random()*objThemes.themes.length);
		var intIndex = Math.floor(Math.random() * $('#jsThemeSelector a').size());

		// test whether there is a current theme set or not
		if (strCurrentThemeId != null) {
			// activate the current active theme

			if ($('#jsThemeSelector a[href$=#theme_' + strCurrentThemeId + ']').size() > 0) {

				// if the theme still exists (it could have been deleted)
				$('#jsThemeSelector a[href$=#theme_' + strCurrentThemeId + ']').click();

			}
			else {

				// if the theme doesn't exist anymore, fallback to a random theme
				$('#jsThemeSelector a').eq(intIndex).click();

			}

		}
		else {

			var bolContinue = true;

			// test if we are on a website, that needs a special background image
			$(objThemes.themes).each(function (i) {
				if (typeof this.themeWebsite != 'undefined') {
					if (strUrl.indexOf(this.themeWebsite) > -1) {
						bolContinue = false;
						$('#jsThemeSelector a').eq(i).click();
						return false;
					}
				}
			});

			// if no other theme have been chosen, activate a random theme
			if (bolContinue) {
				$('#jsThemeSelector a').eq(intIndex).click();
			}

		}

	}
	else {
		frontpageAnimations(0);
	}
}

function initializeHotspotAutoshow(pkid) {
	var $hotspotProgress = $('#hotspotProductContainer' + pkid).find('.hotspotProgress div');

	if ($('#hotspotProductContainer' + pkid).find('.productItem').size() > 0) {
		$hotspotProgress.css('width', 0).animate({
			'width': '100%'
		}, 10000, 'linear', function () {
			showNextHotspotProduct(pkid);
		});
	}
	else {
		$hotspotProgress.hide();
	}

}

function showNextHotspotProduct(pkid) {
	var $hotspotProductContainer = $('#hotspotProductContainer' + pkid);

	var $currentItem = $hotspotProductContainer.find('.productItem:visible');
	if ($currentItem.size() == 0) {
		$currentItem = $hotspotProductContainer.find('.productItem').eq(0);
	}

	var $nextItem = $currentItem.next('.productItem');
	if ($nextItem.size() == 0) {
		$nextItem = $hotspotProductContainer.find('.productItem').eq(0);
	}

	var intProductid = $nextItem.metadata().productid;

	$currentItem.slideUp(500, function () {
		var $activeHotspot = $('.hotspot').removeClass('active').filter(function () {
			return $(this).data('product') == intProductid;
		}).addClass('active');

		$hotspotProductContainer.find('.hotspotQuote').html($activeHotspot.data('header'));

		$nextItem.slideDown(500, function () {
			initializeHotspotAutoshow(pkid)
		});
	});
}

function pulsateElements($elements) {
	var fltFadeSpeed = 700;
	var intMaxOpacity = 1;

	if ($.browser.msie && $.browser.version < 9) {
		intMaxOpacity = 0.8;
	}


	if ($elements.size() > 0) {
		if ($elements.css('opacity') == intMaxOpacity) {
			$elements.animate({
				opacity: 0.3
			}, fltFadeSpeed, function () {
				pulsateElements($(this));
			});
		} else {
			$elements.animate({
				opacity: intMaxOpacity
			}, fltFadeSpeed, function () {
				if ($(this).hasClass('stopPulsate') == false) {
					pulsateElements($(this));
				}
			});
		}
	}
}

// activate the animations on the frontpage
function frontpageAnimations(iState) {
	var $top = $('#siteHeader');
	var $left = $('#siteLeft, #siteLogoContainer');

	if (iState == 1) {
		$left.animate({
			left: 0
		}, 500, function () {
			$top.css({
				paddingRight: 0,
				right: 0,
				left: 'auto',
				width: '100%'
			}).animate({
				top: 0
			}, 500)
		});
	} else {
		$left.css('left', 0);
		$top.css('top', 0);
		themeActivation();
	}
}


// update the table with resellers
function updateResellerList() {
	var strRows = '', arrVisibleMarkers = [];

	for (var j = 0, iMax = arrMarkers.length; j < iMax; j++) {
		if (arrMarkers[j].getVisible() && mapReseller.getBounds().contains(arrMarkers[j].position)) {
			arrVisibleMarkers.push(j);
		}
	}

	$.each(arrVisibleMarkers, function (i, e) {
		var objReseller = resellers.shownResellers[this], strAddress = '', strCompany = '', strPhone = '', strMail = '', strWww = '';
		var bolContains = mapReseller.getBounds().contains(objReseller.gMapLatLng);

		if (bolContains) {

			if (typeof objReseller.street != 'undefined') { strAddress += objReseller.street + '<br/>' }
			if (typeof objReseller.street2 != 'undefined') { strAddress += objReseller.street2 + '<br/>' }
			if (typeof objReseller.postalcode != 'undefined') { strAddress += objReseller.postalcode + ' ' }
			if (typeof objReseller.city != 'undefined') { strAddress += objReseller.city }

			if (typeof objReseller.company != 'undefined') { strCompany = objReseller.company }
			if (typeof objReseller.phone != 'undefined') { strPhone = objReseller.phone }
			if (typeof objReseller.mail != 'undefined') { strMail = objReseller.mail }
			if (typeof objReseller.www != 'undefined') { strWww = '<a href="http://' + objReseller.www + '">' + objReseller.www + '</a>' }

			strRows += '<tr>' +
			'<td>' + strCompany + '</td>' +
			'<td>' + strAddress + '</td>' +
			'<td>' + strPhone + '</td>' +
			'<td>' + strMail + '</td>' +
			'<td>' + strWww + '</td>' +
			'</tr>';
		}
	});

	if (strRows == '') {
		strRows = '<tr><td colspan="5" class="noResults">' + strTextNoResults + '</td></tr>';
	}

	$('#resellerList').find('tbody').html(strRows);
}

// find reseller map and list
function resellerPage() {

	// test if there is a reseller object
	if (typeof resellers != 'undefined') {
		googleMapInitialize();
		resellers.shownResellers = [];
		var infowindow = new google.maps.InfoWindow();

		$.each(resellers.resellers, function (i, e) {
			var objReseller = this, strContent = '', strAddress = '';

			objReseller.gMapLatLng = new google.maps.LatLng(objReseller.lat, objReseller.lng);

			if (typeof objReseller.street != 'undefined') { strAddress += objReseller.street + '<br/>' }
			if (typeof objReseller.street2 != 'undefined') { strAddress += objReseller.street2 + '<br/>' }
			if (typeof objReseller.postalcode != 'undefined') { strAddress += objReseller.postalcode + ' ' }
			if (typeof objReseller.city != 'undefined') { strAddress += objReseller.city }

			if (typeof objReseller.image != 'undefined') { strContent += '<img scr="' + objReseller.image + '" alt=""/>' }
			if (typeof objReseller.company != 'undefined') { strContent += '<h4>' + objReseller.company + '</h4>' }
			if (strAddress != '') { strContent += '<p>' + strAddress + '</p>' }
			if (typeof objReseller.phone != 'undefined') { strContent += '<p>' + objReseller.phone + '</p>' }
			if (typeof objReseller.mail != 'undefined') { strContent += '<p>' + objReseller.mail + '</p>' }
			if (typeof objReseller.www != 'undefined') { strContent += '<p><a href="http://' + objReseller.www + '">' + objReseller.www + '</a></p>' }

			var marker = new google.maps.Marker({
				'position': objReseller.gMapLatLng,
				'title': objReseller.company
			});

			google.maps.event.addListener(marker, 'click', function () {
				infowindow.setContent(strContent);
				infowindow.open(mapReseller, marker);
			});

			this.markerNo = arrMarkers.length;

			resellers.shownResellers.push(objReseller);
			arrMarkers.push(marker);

		});

		google.maps.event.addListener(mapReseller, 'bounds_changed', function () {
			updateResellerList();
		});

		mc = new MarkerClusterer(mapReseller, arrMarkers, { maxZoom: 11 });
	}


	$('#resellerFilters').change(function (e) {
		var strFilter = $(this).val();
		mc.clearMarkers();
		resellers.shownResellers.length = 0;
		arrMarkers.length = 0;

		$.each(resellers.resellers, function (i, e) {
			var objReseller = this, strContent = '', strAddress = '';

			if (objReseller.chain == strFilter || strFilter == '') {

				objReseller.gMapLatLng = new google.maps.LatLng(objReseller.lat, objReseller.lng);

				if (typeof objReseller.street != 'undefined') { strAddress += objReseller.street + '<br/>' }
				if (typeof objReseller.street2 != 'undefined') { strAddress += objReseller.street2 + '<br/>' }
				if (typeof objReseller.postalcode != 'undefined') { strAddress += objReseller.postalcode + ' ' }
				if (typeof objReseller.city != 'undefined') { strAddress += objReseller.city }

				if (typeof objReseller.image != 'undefined') { strContent += '<img scr="' + objReseller.image + '" alt=""/>' }
				if (typeof objReseller.company != 'undefined') { strContent += '<h4>' + objReseller.company + '</h4>' }
				if (strAddress != '') { strContent += '<p>' + strAddress + '</p>' }
				if (typeof objReseller.phone != 'undefined') { strContent += '<p>' + objReseller.phone + '</p>' }
				if (typeof objReseller.mail != 'undefined') { strContent += '<p>' + objReseller.mail + '</p>' }
				if (typeof objReseller.www != 'undefined') { strContent += '<p><a href="http://' + objReseller.www + '">' + objReseller.www + '</a></p>' }

				var marker = new google.maps.Marker({
					'position': objReseller.gMapLatLng,
					'title': objReseller.company
				});

				google.maps.event.addListener(marker, 'click', function () {
					infowindow.setContent(strContent);
					infowindow.open(mapReseller, marker);
				});

				this.markerNo = arrMarkers.length;
				resellers.shownResellers.push(objReseller);
				arrMarkers.push(marker);

			}
		});


		mc.addMarkers(arrMarkers);

		updateResellerList();
	});

	$('#resellerClosestForm').submit(function (e) {
		var address = $('#resellerClosest').val();
		var geocoder = new google.maps.Geocoder();
		geocoder.geocode({ 'address': address }, function (results, status) {
			if (status == google.maps.GeocoderStatus.OK) {
				mapReseller.setCenter(results[0].geometry.location);
				mapReseller.setZoom(12);
			}
		});
		e.preventDefault();
	});

	$('#mapControls h4').css('cursor', 'pointer').click(function () {
		$(this).toggleClass('closed').siblings().toggle();
	});
	$('#mapControls .button').click(function (e) {
		$(this).closest('form').submit();
		e.preventDefault();
	});


	// update the reseller list if it exists 
	$(window).load(function () {
		if (typeof resellers != 'undefined') {
			updateResellerList();
		}
	});
}

// test if the basketpreivew should be resized, so that it needs scrolling functionality
function resizeBasketPreview() {
	var basketpreview = $('.basketpreview');
	var scrollContainer = $('.scrollContainer');
	var intWindowHeight = $(window).height();
	var intNewHeight;

	// hardcoded position, shadows and extra space
	var extraMargin = 50;

	// reset the height and remove the scroll buttons
	scrollContainer.height('auto');
	$('.basketScrollUp, .basketScrollDown').remove();

	if ((basketpreview.outerHeight() + extraMargin) > intWindowHeight) {
		// insert scrollbuttons
		scrollContainer.before('<img class="basketScrollUp" src="/images/basketpreview_arrow_up.gif" alt=""/>').after('<img class="basketScrollDown" src="/images/basketpreview_arrow_down.gif" alt=""/>');

		// calculate the new height
		//intNewHeight = scrollContainer.height() - ((basketpreview.outerHeight() + extraMargin) - intWindowHeight);
		intNewHeight = 300;

		// set the new height to the scrollcontainer
		scrollContainer.height(intNewHeight)
	}
}


// conversion tracking for the groupsmenu click
//function submitGroupsmenuClickConversion() {
//	
//	// Google Website Optimizer Tracking Script
//	var _gaq = _gaq || [];
//	_gaq.push(['gwo._setAccount', 'UA-12249844-2']);
//	_gaq.push(['gwo._trackPageview', '/0714974402/goal']);
//	(function () {
//		var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
//		ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
//		var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
//	})();
//	//End of Google Website Optimizer Tracking Script

//}

