var POPUP_DURATION = 3000; // in milliseconds

var hideTop = false;
var hideBottom = false;
var subsToHide = new Array();
var subsToShow = new Array();
var blackMode = false;
var currentPage = null;	// url encoded thing

var productAnimationInProgress = false;
var lastVisitedProductsPage = null;
var singleProductAnimationEnabled = false;
var scrollInitHandlers = new Array();

function showFlashPage(hideMenu) {
	identify(arguments);
	if (pages[currentPage] != "Flash") { return; }
	setFlashPage(currentPage);
}

//var ignoreFirstTime = true;
function setFlashPage(page, hideMenu) {
  identify(arguments);
  var flash = getMovie("frontFlash");
	try {
		flash.SetVariable("/:getPageResponse", page);
		if (flash.setPage) {
		      if(hideMenu == true) {
				flash.setPage(page, true);
			}
		      else flash.setPage(page);
		}
	} catch (err) {	}
}

function showFlashMenu(doShow) {
	identify(arguments);
	try{
	  if( typeof getMovie('frontFlash').showMenu == 'function') getMovie('frontFlash').showMenu(doShow ? true : false);
	      else getMovie('frontFlash').SetVariable("/:getShowMenu", doShow ? true : false);
	} catch(e) {
	      //mylog('getMovie("frontFlash").showMenu('+(doShow ? 'true' : 'false')+') failed');
	}
}

function showBlackOverlay(listener) {
	identify(arguments);
	if ($("#BlackOverlay").css("display").toLowerCase() != "block") {
		$("#BlackOverlay").css("opacity", 0).css('left', '0').css('top', '0').css('height', '100%');
		$("#BlackOverlay").css("display", "block");
			$("#BlackOverlay").css('opacity', 0.8);
			$("#BlackOverlay").show(1, function() {
				try {listener();} catch (e) {}
			});
	} else {
		try {listener();} catch (e) {}
	}
}

function hideBlackOverlay(listener) {
	identify(arguments);
	if ($("#BlackOverlay").css("display").toLowerCase() == "block") {
		$("#BlackOverlay").hide(1, function() {
			try {listener();} catch (e) {}
		});
	} else {
		try {listener();} catch (e) {}
	}
}

function changeStaticPage() {
	identify(arguments);
	$("#StaticContent").html( "<div style='position: absolute; top: 50%; width: 100%; text-align: center; font-size: 12px;'><img src='images/loading.gif'/></div>" );
	/*
	if(currentPage.split('/')[0] == 'shopfinder') {
		$("#StaticContent").load(addAjax('shopfinder?country='+currentPage.split('/')[1]+'&city='+currentPage.split('/')[2]), "", pageLoaded);
	}
	*/
	$("#StaticContent").load(addAjax(currentPage.replace("/",".")), "", pageLoaded);
	setFlashPage('', true);

	base = currentPage.split(".")[0].split('?')[0].split('/')[0];
	if ((pages[base] == "Product") && (currentPage.split(".").length > 1)) {
	    //alert('single product');
			pageTracker._trackPageview(currentPage);
	} else if (pages[base] == "Product") {
			pageTracker._trackPageview(currentPage.split(".")[0]);
	} else {
			pageTracker._trackPageview(currentPage.replace("/","."));
			//alert('simple page');
	}
}

//JG rewrite function
function pageLoaded(responseText, textStatus, XMLHttpRequest) {
 	identify(arguments);
	///JG menu dropdown boxes
	$('.expandable > a').click(function(){
		var ul = $(this).parent().find('ul');
		if (ul.attr('class') != 'invisible'){
     	ul.addClass('invisible');
      return false;
		}
		$('.expandable ul').addClass('invisible');
		
		ul.removeClass('invisible');
		return false;
	});
	//binding click on whole holder for closing dropdowns
	$('#StaticContent').click(function(){
		$('.expandable ul').addClass('invisible');
		//also form select dropdowns
		$('#StaticContent form .pseudo-select').next().hide();
	});

	//JG events on different pages load
	base = currentPage.split(".")[0].split('?')[0].split('/')[0];
	if ((pages[base] == "Product") && (currentPage.split(".").length > 1)) {
			//alert('single product');
			$('#AddToBasket').click( function() {
				addToBasket( $(this).attr('class') );
				$('#viewBasketBtn').show();
			});
			$('#AddToWishlist').click( function() { addToWishlist( $(this).attr('class') ); });
	} else if (pages[base] == "Product") {
			//alert('products page');
      lastVisitedProductsPage = currentPage;
	 		//init price filter for the products page
			$('#op-price ul li a').click(function(){
				value = $(this).html();
				var price = encodeURI(value.split(' ')[0]);

				if(value.split('-')[1]==null){
          urlsArray = currentPage.split('?');
					if (urlsArray.length == 1){
						url = currentPage.split('.')[0].split('?')[0];
					}
					else {
            var urlParamsArray=currentPage.split('?')[1].split('&');
            var searchParams = '';
						for(i=0;i<urlParamsArray.length;i++){
							if(urlParamsArray[i].substr(0,5)!='price')
								searchParams = '?'+urlParamsArray[i];
						}
      			url = currentPage.split('?')[0]+searchParams;
					}
				}
				
				else {
	    		urlsArray = currentPage.split('?');
					if (urlsArray.length == 1)
	     			var url = currentPage+'?'+'price='+price;
					else{
	      		var urlParamsArray=currentPage.split('?')[1].split('&');
	     			var priceFlag = false;
						for(i=0;i<urlParamsArray.length;i++){
							if(urlParamsArray[i].substr(0,5)=='price'){
								urlParamsArray[i] = 'price='+price;
								priceFlag = true;
							}
						}
						var urlParamsString = urlParamsArray.join('&');
						if(!priceFlag) urlParamsString = urlParamsString+'&price='+price;
						var url = currentPage.split('?')[0]+'?'+urlParamsString;
					}
				}
				if(currentPage != url) $.historyLoad(url);
				return false;
			});
	} else {
      //alert('simple page');

			//intro pages scroll
			if (pages[base] == 'Intro'){
     		var contentHeight = 150 + $('.left-part-advanced h1').height() + $('.left-part-advanced p').height() + 148;

			  if (contentHeight > $(window).height()){
          var reservedArea = 150 + $('.left-part-advanced h1').height() + 168;
					$('.left-part-advanced p').css('height', $(window).height()-reservedArea+'px');
			  	$('.left-part-advanced p').jScrollPane();
				}
			}

			//avoid storing to history after refresh (F5)
			var lastHistLink = getLastHistoryLink();
			if (lastHistLink == currentPage)
				removeLastHistoryLinkOnRefresh();
			
      //assign back link from cookies
			$('.introPageBack').attr('href',getLastHistoryLink());
			$('.introPageBack').click(function (){
   			removeLastHistoryLink();
			});
	}

	//JG Basket JS
	$(".shopping-cart td.removeFromBasket a").click(function() {
		removeFromBasket( $(this).attr('class') );
		return false;
	});

	$(".shopping-cart td.qty a").click(function() {
  	addToBasket($(this).attr('id'), $(this).prev().attr('value'),true);
		$.historyLoad(currentPage)
		return false;
	});
	
	//JG wishlist
	$(".wishlist a.delete").click(function() {
		removeFromWishlist( $(this).attr('id') );
		return false;
	});
	
	$(".wishlist a#addToCart").click(function() {
    wishlistItems = $.cookie('wishlist');
    wishlistItems = $.evalJSON(wishlistItems);
		for(var i = 0; i < wishlistItems.length; i++)
			addToBasket(wishlistItems[i]);

		$.cookie('wishlist', null);
    $.historyLoad(currentPage);
		return false;
	});
	
	$(".wishlist a#closePopup").click(function(){
		$('.popup').hide();
		return false;
	});
	
	$(".wishlist a#mailWishList").click(function(){
    $('.popup').show();
		return false;
	});

 	//JG forms issues
	$("#StaticContent form").each(function() {
	var url = $(this).attr("action");
		if(url == '') url = currentPage;

		//simple forms SUBMIT
		$(this).find('input[type=submit]').click(function(){
				$('input[type=submit]').removeClass('submitClicked');
				$(this).addClass('submitClicked');
				//$(this).parent().addClass('submitClicked');
		});

		$(this).submit(function() {

			if ($(this).attr('class')!='normalPostForm'){
				var params = {};

				$(this).find('input:not([type=checkbox],[type=radio],[type=submit]), input[type=radio][checked=true], input[type=checkbox][checked=true], select, textarea, input.submitClicked[type=submit]').each( function() {
					if($(this).attr('title') == $(this).val() ) $(this).val('');
					if($(this).attr('type') == 'radio' || $(this).attr('type') == 'checkbox') {
						params[String($(this).attr('name')).trim()] = $(this).attr('value');
					}
					else params[String($(this).attr('name')).trim()] = $(this).val();
				});
				if($(this).attr('method').toUpperCase() == 'POST')
					$("#StaticContent").load(addAjax(url), params, pageLoaded);
				else $("#StaticContent").load(addAjax(url+'?'+params), "", pageLoaded);       // shouldn't work IMO. Good that noone uses it
				return false;
			}
		});
		//simple forms SUBMIT

		//*****JG forms submit
    $(this).find('input:not([type=checkbox],[type=radio],[type=submit]), select, textarea').each( function() {
			$(this).keypress(function(e){
	        if(e.which==13) {
        		$(this).parents('form').find('a.submit').click();
					};
	    });
	 	});

		$(this).find('a.submit').click(function(){
			if(!$(this).hasClass('submitClicked')){
				$(this).addClass('submitClicked');
				var form = $(this).parents('form');
        var url = $(this).parents('form').attr("action");
				if(url == '') url = currentPage;
				var params = {};
				form.find('input:not([type=checkbox],[type=radio],[type=submit]), input[type=radio][checked=true], input[type=checkbox][checked=true], select, textarea, input.submitClicked[type=submit]').each( function() {
					if($(this).attr('title') == $(this).val() ) $(this).val('');
					if($(this).attr('type') == 'radio' || $(this).attr('type') == 'checkbox') {
						params[String($(this).attr('name')).trim()] = $(this).attr('value');
					}
					else params[String($(this).attr('name')).trim()] = $(this).val();
				});

				if(form.attr('method').toUpperCase() == 'POST')
     $("#StaticContent").load(addAjax(url), params, pageLoaded);
				else $("#StaticContent").load(addAjax(url+'?'+params), "", pageLoaded);
			}
   		return false;
		});

		$(this).find('input[type=text], input[type=password], textarea').focus(function() {
			if($(this).val() == $(this).attr('title')) $(this).val('');
		}).blur(function() {
			if($(this).val() == '') $(this).val($(this).attr('title'));
		}).blur();
	});

	//JG custom radiobuttons & checkboxes
  $("#StaticContent input[type=checkbox], #StaticContent input[type=radio]").each(function() {
		//$(this).hide();
    if ($(this).attr("checked"))
			$(this).parent().addClass('checked');

		if($(this).attr('type') == 'radio'){
      if(isIE6) {
    			$(this).parent().click(function() {
          $(this).parents('form').find('input[type=radio]').each(function() {$(this).parent().removeClass('checked');});
					if ($(this).hasClass("checked")){
						$(this).removeClass('checked');
						$(this).find('input').attr("checked",false);
					}
					else {
					  $(this).addClass('checked');
					  $(this).find('input').attr("checked",true);
					}
				});
			}
			else {
				$(this).click(function() {
					$(this).parents('form').find('input[type=radio]').each(function() {$(this).parent().removeClass('checked');});
					if ($(this).attr("checked"))
						$(this).parent().addClass('checked');
			  });
			}
		}
		else if($(this).attr('type') == 'checkbox'){
      if(isIE6) {
				$(this).parent().click(function() {
					if ($(this).hasClass("checked")){
						$(this).removeClass('checked');
						$(this).find('input').attr("checked",false);
					}
					else {
					  $(this).addClass('checked');
					  $(this).find('input').attr("checked",true);
					}
				});
			}
			else {
        $(this).click(function() {
     			if ($(this).attr("checked"))
						$(this).parent().addClass('checked');
					else
					  $(this).parent().removeClass('checked');
				});
			}
		}
	});
	
	//JG custom select
	$('#StaticContent form .pseudo-select').click(function(){
		var ul = $(this).next();
		ul.width($(this).width());
		if(ul.is(':hidden')) ul.show();
		else ul.hide();
		return false;
	});
	
	$('#StaticContent form .pseudo-input ul li a').click(function(){
		//change pseudo input value
		input = $(this).parent().parent().next();
		inputValue = $(this).parent().attr('class').substr(4);
		input.val(inputValue);

		parentUl = $(this).parent().parent();
    parentUl.hide();
    
    //select title change
		title = $(this).parent().parent().prev();
		title.html(inputValue);
		return false;
	});

	$("#StaticContent a").fixURL();
	// add current page to history
	addPageToHistory();
	showFlashMenu(false);

	//*********************OLD STUFF ON PAGE LOAD AFTER FINISHING CHECK IF NEEDED

	// add custom checkbox
	/*
	if(jQuery.browser.msie) $('#StaticContent #ShopFinderForm .newListSelected ul.newList li').fixIEZIndex( $('#StaticContent') );
	if(jQuery.browser.msie) $('#StaticContent .ShoppingBag .Quantity .newListSelected ul.newList li').fixIEZIndexAdvanced( $('#StaticContent') );

	$("#StaticContent").removeClass(); // reset all classes on static content box
	$("#Scrollable").addClass('page-'+currentPage.split('?')[0].split('/')[0]).mousewheel( handleMousewheelScroll );
	$("#StaticContainer").removeClass().addClass('pageContainer-'+currentPage.split('?')[0].split('/')[0])
	if($("#Scrollable").length == 0) $("#StaticContent").addClass('page-'+currentPage.split('?')[0].split('/')[0]);
	*/
	/*
	scrollInit();
	$('#StaticContent img').load( function(){
	      if(scrollFixTimer != null) clearTimeout(scrollFixTimer);
		scrollFixTimer = setTimeout("scrollInit();", 100);
	});
	scrollFixTimer = setTimeout("scrollInit()", 250);
	*/
	//*********************OLD STUFF ON PAGE LOAD AFTER FINISHING CHECK IF NEEDED
	fixTransparentPng();
}

function shopFinderChange() {
	identify(arguments);
	var country = encodeURI($('#ShopFinderForm select[name=country]').val());
	var city = encodeURI($('#ShopFinderForm select[name=city]').val());
	var url = currentPage.split('?')[0].split('/')[0]+'/'+country+'/'+city;
	$.historyLoad(url);
}

function showStaticOverlay(listener) {
	identify(arguments);
	if ($("#StaticContainer").css("display").toLowerCase() != "block") {
		$("#StaticContainer").show();
		$("#StaticContainer").css("left", "50%");
		      $("#StaticContainer").css('filter', 'none');
			try {listener();} catch (e) {}
	} else {
		try {listener();} catch (e) {}
	}
}
function hideStaticOverlay(listener) {
	identify(arguments);
	if ($("#StaticContainer").css("display").toLowerCase() == "block") {
			$("#StaticContainer").hide();
			try {listener();} catch (e) {}
	} else {
		try {listener();} catch (e) {}
	}
	//remove history cookie on vieving frontpage
	clearPagesHistory();
}

function websiteNavigation(hash) {
	identify(arguments);
  //JG hide login popup if visible
	if($('#loginPopup').is(':visible')) $('#loginPopup').hide();

	//console.log( (new Date()).getTime()+' :: websiteNavigation('+hash+')' );
	if(productAnimationInProgress) {
    setTimeout('websiteNavigation("'+hash+'");', 100);
    return;
	}
	// hash is url encoded
	var oldPage = currentPage ? currentPage : '';
	currentPage = hash;

	if(currentPage == 'quiz') {
		websiteNavigation('the_quiz');
		return;
	}
	if(currentPage == 'dk_and_manchester_united') {
		$.historyLoad('manchester_united_intro');
		return;
	}
	if(currentPage == 'mobil_collection_pseudo') {
		$.historyLoad('mobilcharms');
		return;
	}
	/*
	if(currentPage == 'kaleidoscope_flash') {
		websiteNavigation('kaleidoscope');
		return;
	}
	*/
	if(currentPage == 'meet_our_designers') {
		$.historyLoad('meet_our_designers_intro');
		return;
	}
	if(currentPage == 'riviera'){
    $.historyLoad('riviera_intro');
		return;
	}
	if(currentPage == 'time2'){
    $.historyLoad('time_intro');
		return;
	}
	if(currentPage == 'eyewear2'){
    $.historyLoad('eyewear_intro');
		return;
	}
	if(currentPage == 'man_collection'){
    $.historyLoad('man');
		return;
	}
	if(currentPage == 'in_the_club_link'){
    $.historyLoad('in_the_club');
		return;
	}
	if(currentPage == 'the_club_link'){
    $.historyLoad('the_club');
		return;
	}
	if(currentPage == 'edit_your_profile'){
    $.historyLoad('edit_your_profile2');
		return;
	}
 	if(currentPage == 'shop_help_link'){
    $.historyLoad('shop_help');
		return;
	}
	if(currentPage == 'customer_service_link'){
    $.historyLoad('customer_service');
		return;
	}
	
	if(currentPage.split('?').length > 1) {
		var filters = currentPage.split('?')[1].split('&');
		$('input#priceX').attr('checked', true);
		$('input#colorX').attr('checked', true);
		for(var i = 0; i < filters.length; i++) {
			if(filters[i] == '') continue;
			var vals = filters[i].split('=');
			if(vals[0] == 'color') vals[0] = 'colorAI';
			$('input[name='+vals[0]+'][value='+vals[1]+']').attr('checked', true);
		}
	}
	var oldBase = oldPage.split(".")[0].split('?')[0];
	base = currentPage.split(".")[0].split('?')[0].split('/')[0];
	if (pages[base] == "Flash") {
     hideStaticOverlay(showFlashPage);
	} else {
	    changeStaticPage();
			showStaticOverlay();
	}
	
	document.title = 'Dyrberg/Kern webshop';
 	if(jQuery.browser.msie){
		setTimeout(function(){document.title = 'Dyrberg/Kern webshop'},500);
	}
}
//////////////////////////////////////
// Mouse Wheel Scroll
//////////////////////////////////////


function handleMousewheelScroll (e, delta) {
	identify(arguments);
      var top = parseInt($("#CurrentScroll").offset().top) - parseInt($("#Scroll").offset().top);
	top -= delta*15;  // because up is positive and down is negative, while top should change in opposite direction
	top = Math.min(top, scrollBarMax);
	top = Math.max(top, 0);
	$("#CurrentScroll").css("top", top+"px");
	var contentScroll = Math.round(scrollRatio*top);
	$("#Scrollable").attr("scrollTop", contentScroll);
	lastScrollTop = contentScroll;
	//$(window).scroll();
	if(jQuery.browser.msie) fixStylishSelect( $('#Scrollable') );
	return false;
}

//////////////////////////////////////
// Product menu functions
//////////////////////////////////////
function showProductMenu() {
	identify(arguments);
  //showFlashMenu(false);
	$("#ProductMenuSlider").slideDown("slow");
	hideBottom = false;
}

function hideProductMenu() {
	identify(arguments);
	setTimeout(function() {
		if (hideBottom) {
			$("#ProductMenuSlider").slideUp("slow");
		}
	},1000);
	/*
	setTimeout(function() {
		if (hideBottom) {
			showFlashMenu(true);
		}
	},1500);
	*/
	hideBottom = true;
}

//////////////////////////////////////
// Submenu functions
//////////////////////////////////////
function prepareSubMenus(selector) {
	identify(arguments);
	var subMenus=$(selector+" > li");	// like Jewels, Time, ...
	subMenus.each(function(i){
		var curSubMenu = $(this);
		//curSubMenu.mouseenter(showSub);
		curSubMenu.mouseleave(hideSub);
		curSubMenu.find("div").eq(0).click(showSub2);
	});
}

function showSub() {
	identify(arguments);
	var id = $(this).find("div").eq(0).attr("innerHTML");
	var sub = $(this).find("ul").eq(0);
	subsToShow[id] = true;
	subsToHide[id] = false;
	setTimeout(function() {
		if (subsToShow[id] == true) {
			$(sub).slideDown("slow");
		}
	}, 1000);
}

function showSub2() {
	identify(arguments);
	var id = $(this).attr("innerHTML");
	var sub = $(this).siblings().eq(0);
	subsToShow[id] = true;
	subsToHide[id] = false;
	$(sub).slideDown("slow");
}

function hideSub() {
	identify(arguments);
	var id = $(this).find("div").eq(0).attr("innerHTML");
	var sub = $(this).find("ul").eq(0);
	subsToShow[id] = false;
	subsToHide[id] = true;
	setTimeout(function() {
		if (subsToHide[id] == true) {
			$(sub).slideUp("slow");
		}
	}, 1000);
}

function fixStylishSelect($obj) {
	identify(arguments);
	$obj.find('.newListSelected').each( function() {
		var oldPos = ''
		try{ oldPos = $(this).css('position'); } catch(e) { }
		$(this).css('position', 'static').css('position', 'relative');
		if(oldPos != '') $(this).css('position', oldPos);
	});
}

jQuery.fn.fixIEZIndex = function( $stop ) {
	identify(null, "fixIEZIndex");
      if(!jQuery.browser.msie) return true;

	$(this).each( function() {
		var c = $(this).css('z-index') > 0 ? $(this).css('z-index')-1 : 999;
		var $obj = $(this).parent();
		while($obj.length > 0 && $obj.get(0) != $stop.parent().get(0)) {
		      //mylog('c='+c+' on '+$obj.get(0).tagName+'#'+$obj.attr('id')+'.'+$obj.get(0).className);
			if(!$obj.css('z-index')) $obj.css('z-index', c);
			if($obj.css('position') != 'absolute' && !$obj.hasClass('importantPosition')) $obj.css('position', 'relative');
			$obj = $obj.parent();
			c--;
		}
	});

	$('#CardInfo').css('position', ''); // random but necessary
}

jQuery.fn.fixIEZIndexAdvanced = function( $stop ) {
	identify(null, "fixIEZIndexAdvanced");
	if(!jQuery.browser.msie) return true;

	var startZ = 5000;
	$(this).each( function() {
	      $(this).css('z-index', startZ).fixIEZIndex( $stop );
	      startZ -= 50;
	});
};

//////////////////////////////////////
// Flash related functions
//////////////////////////////////////
function getMovie(movieName) {
	identify(arguments);
	//return document.getElementById(movieName);


    	//if (navigator.appName.indexOf("Microsoft Internet")==-1) {
		if (document.embeds && document.embeds[movieName]) {
//		      if(console) console.log("Found document.embeds[movieName]="+document.embeds[movieName]);
			return document.embeds[movieName];
	//	}
	}
      if (window[movieName]) {
//	      if(console) console.log("Found window[movieName]="+window[movieName]);
		return window[movieName];
	}
	if (window.document[movieName]) {
//	      if(console) console.log("Found window.document[movieName]="+window.document[movieName]);
		return window.document[movieName];
	} else {
//		if(console) console.log("Found document.getElementById(movieName)="+document.getElementById(movieName));
		return document.getElementById(movieName);
	}
}

function navigateBgLeft() {
	identify(arguments);
	try{
		getMovie("frontFlash").SetVariable("/:getBgPrev", "yes");
		getMovie("frontFlash").navigateBgLeft()
	}
	catch(e) {}
}

function navigateBgRight() {
	identify(arguments);
    	try{
		getMovie("frontFlash").SetVariable("/:getBgNext", "yes");
		getMovie("frontFlash").navigateBgRight()
	}
	catch(e) {}
}

function getPage() {
	identify(arguments);
	var flash = getMovie("frontFlash");
	var page = jQuery.historyCurrentHash.replace("#", "");
	flash.SetVariable("/:getPageResponse", page);
	if (jQuery.browser.msie) {
		flash.SetVariable("/:isIE", true);
	}
	return page;
}

function setPage(page) {
	identify(arguments);
	$.historyLoad(page);
}

function talk(msg) {
    	alert(msg);
}

//////////////////////////////////////
// Shopping bag and Wishlist
//////////////////////////////////////

var BasketBubbleState = 'hidden';
var WishlistBubbleState = 'hidden';

function addToBasket(id, count, update) {
	identify(arguments);
	if(typeof(count) == 'undefined' || isNaN(count)) addCount = 1;
	else addCount = count;

	var basketItems = $.cookie('basket');
	if(basketItems == null) basketItems = new Array();
	else basketItems = $.evalJSON(basketItems);

	var found = false;
	for(var i = 0; i < basketItems.length; i++) {
		if(basketItems[i].id == id) {
			if(update)
        basketItems[i].count = addCount*1;
			else
				basketItems[i].count = basketItems[i].count*1 + addCount*1;
			if(basketItems[i].count == 0) basketItems.splice(i,1);
			found = true;
			break;
		}
	}

	if(!found) {
		basketItems[ basketItems.length ] = { id: id, count: 1 };
	}

	$.cookie('basket', $.toJSON(basketItems), {expires: 2}); // expire in 48 hours

	$('#insideShoppingBag').load('basket.summary', "", function(){});

	if(typeof(count) == 'undefined') showBasketBubble();

	//mylog($.cookie('basket'));
}

function addToWishlist(id) {
	identify(arguments);
	var wishlistItems = $.cookie('wishlist');
	if(wishlistItems == null) wishlistItems = new Array();
	else wishlistItems = $.evalJSON(wishlistItems);

	var found = false;
	for(var i = 0; i < wishlistItems.length; i++) {
		if(wishlistItems[i] == id) {
			found = true;
			break;
		}
	}

	if(!found) {
		wishlistItems[ wishlistItems.length ] = id;
		$.cookie('wishlist', $.toJSON(wishlistItems), {expires: 7}); // expire in 1 week
	}

	showWishlistBubble();
}

function showBasketBubble() {
	identify(arguments);
	basketBubbleState = 'appearing';
	$('#BasketBubble').fadeIn('slow', function() {
		basketBubbleState = 'visible';
		setTimeout(hideBasketBubble, POPUP_DURATION);
	} );
}

function showWishlistBubble() {
	identify(arguments);
	wishlistBubbleState = 'appearing';
	$('#WishlistBubble').fadeIn('slow', function() {
		wishlistBubbleState = 'visible';
		setTimeout(hideWishlistBubble, POPUP_DURATION);
	} );
}

function hideBasketBubble() {
	identify(arguments);
	if(basketBubbleState != 'visible') return;
	basketBubbleState = 'hiding';
	$('#BasketBubble').fadeOut('slow', function() {
		basketBubbleState = 'hidden';
	} );
}

function hideWishlistBubble() {
	identify(arguments);
	if(wishlistBubbleState != 'visible') return;
	wishlistBubbleState = 'hiding';
	$('#WishlistBubble').fadeOut('slow', function() {
		wishlistBubbleState = 'hidden';
	} );
}

function removeFromBasket(id) {
	identify(arguments);
	var basketItems = $.cookie('basket');
	if(basketItems == null) basketItems = new Array();
	else basketItems = $.evalJSON(basketItems);

	var found = false;
	for(var i = 0; i < basketItems.length; i++) {
		if(basketItems[i].id == id) {
			basketItems.splice(i,1);
			found = true;
			break;
		}
	}

	if(found) {
		$.cookie('basket', $.toJSON(basketItems), {expires: 2}); // expire in 48 hours
	}

	$('#insideShoppingBag').load('basket.summary', "", function(){});
	$.historyLoad(currentPage);
}

function removeFromWishlist(id) {
	identify(arguments);
	var wishlistItems = $.cookie('wishlist');
	if(wishlistItems == null) wishlistItems = new Array();
	else wishlistItems = $.evalJSON(wishlistItems);

	var found = false;
	for(var i = 0; i < wishlistItems.length; i++) {
		if(wishlistItems[i] == id) {
			wishlistItems.splice(i,1);
			found = true;
			break;
		}
	}

	if(found) {
		$.cookie('wishlist', $.toJSON(wishlistItems), {expires: 7}); // expire in 1 week
	}

	$.historyLoad(currentPage);
}

function replaceInBasket(oldID, newID) {
	identify(arguments);
	var basketItems = $.cookie('basket');
	if(basketItems == null) basketItems = new Array();
	else basketItems = $.evalJSON(basketItems);

	for(var i = 0; i < basketItems.length; i++) {
		if(basketItems[i].id == oldID) {
			basketItems[i].id = newID;
			for(var j = 0; j < basketItems.length; j++) {
				if(basketItems[j].id == newID && i!=j) {
					basketItems[i].count += basketItems[j].count;
					basketItems.splice(j,1);
					break;
				}
			}
			$.cookie('basket', $.toJSON(basketItems), {expires: 2}); // expire in 48 hours
			$('#insideShoppingBag').load('basket.summary', "", function(){ $.historyLoad(currentPage); });
			return true;
		}
	}
}

function replaceInWishlist(oldID, newID) {
	identify(arguments);
	var wishlistItems = $.cookie('wishlist');
	if(wishlistItems == null) wishlistItems = new Array();
	else wishlistItems = $.evalJSON(wishlistItems);

	for(var i = 0; i < wishlistItems.length; i++) {
		if(wishlistItems[i] == oldID) {
			wishlistItems[i] = newID;
			for(var j = 0; j < wishlistItems.length; j++) {
				if(wishlistItems[j] == newID && i!=j) {
					wishlistItems.splice(j,1);
					break;
				}
			}
			$.cookie('wishlist', $.toJSON(wishlistItems), {expires: 2}); // expire in 48 hours
			$.historyLoad(currentPage);
			return true;
		}
	}
}

//////////////////////////////////////
// Pages history (used for back buttons and single product page info)
//////////////////////////////////////
function clearPagesHistory(){
  $.cookie('history', null);
}

function addPageToHistory() {
	identify(arguments);

	var pagesHistory = $.cookie('history');
	if(pagesHistory == null) pagesHistory = new Array();
  else pagesHistory = $.evalJSON(pagesHistory);

	if (pagesHistory[pagesHistory.length-1]!=currentPage){
		pagesHistory[ pagesHistory.length ] = currentPage;
		$.cookie('history', $.toJSON(pagesHistory), {expires: 1});
	}
}

function removeLastHistoryLink(){
  var pagesHistory = $.cookie('history');
  if(pagesHistory == null) return;
	else pagesHistory = $.evalJSON(pagesHistory);
	//removing two pages as current is also stored
	pagesHistory.pop();
	pagesHistory.pop();

	$.cookie('history', $.toJSON(pagesHistory), {expires: 1});
}

function removeLastHistoryLinkOnRefresh(){
  var pagesHistory = $.cookie('history');
  if(pagesHistory == null) return;
	else pagesHistory = $.evalJSON(pagesHistory);
	//removing two pages as current is also stored
	pagesHistory.pop();
	$.cookie('history', $.toJSON(pagesHistory), {expires: 1});
}

function getLastHistoryLink(){
  var pagesHistory = $.cookie('history');
  if(pagesHistory == null) return;
  else pagesHistory = $.evalJSON(pagesHistory);

  return (pagesHistory[pagesHistory.length-1]);
}

//////////////////////////////////////
// JG LOGIN POPUP ISSUES
//////////////////////////////////////
function enableSignInPopup() {
 $('#NavigationBar .Menu a:first').addClass('showPopup');
 $('#NavigationBar .Menu a:first span#signOut').hide();
 $('#NavigationBar .Menu a:first span#signIn').show();
}
function disableSignInPopup() {
 $('#NavigationBar .Menu a:first').removeClass('showPopup');
 $('#NavigationBar .Menu a:first span#signIn').hide();
 $('#NavigationBar .Menu a:first span#signOut').show();
}
function clearPopupFields() {
	$('#loginPopup form p.formError').html('&nbsp;');
  $('#loginPopup form input#login-email').val('E-mail');
  $('#loginPopup form input#login-password').val('Password').hide();
  $('#loginPopup form input#login-pseudo-password').val('Password').show();
}

function switchLoginPswFields(){
  $('#loginPopup form input#login-pseudo-password').hide();
  $('#loginPopup form input#login-password').show().focus();
}
//////////////////////////////////////
// JG PRODUCTS GRID ALIGN
//////////////////////////////////////

function organizeProducts(){
  if ($('#grid-holder li:first').length) {
		var productsInRowQuantity = Math.floor($('#grid-holder').width() / (parseInt($('#grid-holder li:first').width()) + parseInt($('#grid-holder li:first').css('margin-right').split('px')[0])+ 2));
		var rowQuantity = Math.floor($('#grid-holder').height() / (parseInt($('#grid-holder li:first').height()) + parseInt($('#grid-holder li:first').css('margin-bottom').split('px')[0])));
		var productsQuantity = $('#grid-holder li').length;
		var optimalProductsQuantity = productsInRowQuantity * rowQuantity;
		if (productsQuantity != optimalProductsQuantity){
			 var prodToAdd = optimalProductsQuantity - productsQuantity;
	  	 for (i=0; i < prodToAdd; i++){
	        $('#grid-holder').append('<li class="pseudoProd"></li>');
			 }
		}
	}
}
//////////////////////////////////////
//////////////////////////////////////
$(document).ready(function() {
	identify(null, "document.ready");
	// Flash related stuff
	$("#ContentFlash").flash({
		src: "flash/frontPage.swf",
		width: "100%",
		height: "100%",
		scale: "noscale",
		swliveconnect: "true",
		wmode: "transparent",
		allowScriptAccess: "always",
		name: "frontFlash",
		id: "frontFlash"
	});
	$("#ProductMenu #Groups").mouseenter(showProductMenu);
	$("#ProductMenu").mouseleave(hideProductMenu);
	prepareSubMenus("#ProductMenuNonSlider > ul");
	prepareSubMenus("#ProductMenuSlider > ul");
	
	$.historyInit(websiteNavigation, "");

	$('a').fixURL();

	//JG sign in popup
	$('#NavigationBar .Menu a.showPopup').live('click', function(){
    $.historyLoad('');
		$('#loginPopup').show();
		return false;
	});
	
	$('#loginPopupClose').click(function(){
 		$('#loginPopup').hide();
 		clearPopupFields();
	});

  //JG popup form submit
	$(".popup form#login").each(function() {
    	$(this).find('input').each( function() {
			$(this).keypress(function(e){
	        if(e.which==13) {
        		$(this).parents('form').find('a.submit').click();
					};
	    });
	 	});

		$(this).find('a.submit').click(function(){
			if(!$(this).hasClass('submitClicked')){
				$(this).addClass('submitClicked');
				var form = $(this).parents('form');
        var url = $(this).parents('form').attr("action");
				if(url == '') url = currentPage;

				var params = {};
				form.find('input').each( function() {
					if($(this).attr('title') == $(this).val() ) $(this).val('');

					params[String($(this).attr('name')).trim()] = $(this).val();
				});
				if(form.attr('method').toUpperCase() == 'POST')
        $("#StaticContent").load(addAjax(url), params, pageLoaded);
				else $("#StaticContent").load(addAjax(url+'?'+params), "", pageLoaded);
			}
   		return false;
		});

		$(this).find('input[type=text], input[type=password], textarea').focus(function() {
			if($(this).val() == $(this).attr('title')) $(this).val('');
		}).blur(function() {
			if($(this).val() == '') $(this).val($(this).attr('title'));
		}).blur();
	});
	
	// customer selects
	$('#NavigationBar select').sSelect();
	setInterval( function() {
		if(currentPage != '' && currentPage != undefined && currentPage != '?utm_source=www.shopdyrbergkern.com&utm_medium=website&utm_campaign=OldSite') showFlashMenu(false);}, 1000 );

	$(window).resize( function() {
		//mylog('window.resize');
		/*var widthThreshold = Math.round(($(window).height()-77)*25/16.0*1.1);
		if(widthThreshold > 1300) widthThreshold = 1300;
		if(widthThreshold < 950) widthThreshold = 950;
  	*/
		var widthThreshold = 1300;
		/*
		if($(window).width() > widthThreshold) {
			$('#WholeContent').css('width', widthThreshold+'px');
		}
		*/
		if ($(window).width() < 1000) {
			$('#WholeContent').css('width', '1000px');
		}
		else {
			// IE problem avoid (-1px)
			$('#WholeContent').css('width', ($(window).width() - 1)+'px');
		}

		$('#WholeContent').css('margin-left', -1*$('#WholeContent').width()/2+'px');
		if(isIE6) {
      $('#HrLeft, #HrRight').remove();
			//$('#NavigationBar .Menu').css('width', $('#NavigationBar').width()-460+'px');
		  //$('#NavigationBar .Menu #Hr').css('width', $('#NavigationBar .Menu').width()+'px');
		  //alert('Widths: NavBar='+$('#NavigationBar').width()+' & Menu='+$('#NavigationBar .Menu').width()+' & Hr='+$('#NavigationBar #Hr').width());
		}
	}).resize();

	// imitate resize for IE6
	if(isIE6) {
		//$('#HrLeft, #HrRight').remove();
		//$('#NavigationBar .Menu').css('width', $('#NavigationBar').width()-460+'px');
		
		
		//lm
		$('#ProductMenu li' ).mouseover(function () { 
			$( this ).addClass('ov'); 
			
		});
		$('#ProductMenu li' ).mouseout(function () { 
			$( this ).attr('class', '');
		});
		//lm
	}


//	checkFlashVersion();
	//checkForIE6();
	if(jQuery.browser.msie && jQuery.browser.version == '7.0') {
		//$('#WholeContent').css('height', 'auto');
		//setTimeout("$('#WholeContent').css('height', '100%');", 10);
		//$('#WholeContent').css('height', 'auto');
		
	}

	fixTransparentPng();

});

function checkFlashVersion() {
	identify(arguments);
      if(typeof(jQuery.fn.flash.hasFlash)!= 'function') {
	      //console.log('jQuery.fn.flash.hasFlash => '+typeof(jQuery.fn.flash.hasFlash));
	      setTimeout(checkFlashVersion, 2000);
	      return;
	}
	var $$ = jQuery.fn.flash;
	var brwsr = '';
	switch(true) {
	      case $.browser.msie : brwsr = 'IE '+ $.browser.version; break;
	      case $.browser.mozilla : brwsr = 'Firefox '+ $.browser.version; break;
	      case $.browser.opera : brwsr = 'Opera '+ $.browser.version; break;
	      case $.browser.safari : brwsr = 'Safari '+ $.browser.version; break;
	}

/*	if($$.hasFlash(10,0,32)) alert('Congratulations, you have the latest flashplayer! (Your browser is recoginzed as "'+brwsr+'" and Flash player version '+$$.hasFlash.playerVersion()+')');
	else if($$.hasFlash(10,0,0)) alert('Hey, you have Flash player 10 (That\'s good), but you should upgrade the the latest version. (Your browser is recoginzed as "'+brwsr+'" and Flash player version '+$$.hasFlash.playerVersion()+')');
	else alert('You don\'t have Flash player (or it\' old) - should upgrade the the latest version. (Your browser is recoginzed as "'+brwsr+'" and Flash player version '+$$.hasFlash.playerVersion()+')');
*/
}

jQuery.fn.fixURL = function() {
	identify(null, "fixURL");
	$(this).each(function() {
		var href = $(this).attr("href");
		var base = $('base').attr('href');
		var oldHref = href;
			if (href.indexOf("#") > -1) return;
			if (href.substr(0,6).toLowerCase() == "mailto") return;

			if (href.substr(0,4).toLowerCase() != "http") {
				// remove window.location from href's -- for IE
				href = href.replace(base, '');
				$(this).attr("href", "#"+href);
			}
			else {
			      if(href.replace(base, '') == oldHref) {
			      	if(href.substr(0,5) != 'https') $(this).attr('target', '_blank');
				}
			      else $(this).attr("href", "#"+href.replace(base, '') );
			}

		// TODO: uncomment the line below, when https is available!
		//if($(this).attr('href') == '#checkout') $(this).attr('href', base.replace('http', 'https')+'checkout').attr('target', '_self');
		//mylog(oldHref+' => '+$(this).attr('href') );
	});
	$(this).unbind('click', noClick);
};

String.prototype.trim = function() {
	identify(null, "string.trim");
	return this.replace(/^\s+|\s+$/g,"");
}

function addAjax(url) {
	if (url.indexOf("?") > -1) {
		return url+"&ajax";
	} else {
		return url+"?ajax";
	}
}

//*** JG needed for final step
function  updateTotalPrice(){
	identify(arguments);
	var tmp = $('.subtotal #initPrice').text();
	var currency = tmp.match(/(£|DKK|SEK|€)/)[0];
	var currencyFirst = (tmp.indexOf(currency) == 0);
	tmp = tmp.split(' ');
	var separator = (tmp.length > 2) ? ' ' : ((tmp[0].split(',').length > 1) ? ',' : (tmp[0].split('.').length > 1) ? '.' : '');
	var initPrice = getPriceFromObj( $('.subtotal #initPrice') );
	if($('.subtotal #discountPrice').length > 0)
		var discountPrice = getPriceFromObj( $('.subtotal #discountPrice') );
	else
	  var discountPrice = 0;

	var useDecimal = /[0-9]*\.[0-9][0-9]?/.test( $('.subtotal #initPrice').text() );
	var shippingPrice = $('.subtotal #shippingPrice').text().toUpperCase() == 'FREE' ? 0 : getPriceFromObj($('.subtotal #shippingPrice'));// ? getPriceFromObj( $('.PriceBox #shippingPrice') ) : 0;

	//JG update this one with invoice price
	var invoicePrice = ( $('input#payment_type2').length > 0 && $('input#payment_type2').attr('checked') ? 29 : 0) ;

	var totalPrice = initPrice + shippingPrice + invoicePrice + discountPrice;
	//mylog( currency+' '+useDecimal+' : '+initPrice+'/'+shippingPrice+'/'+invoicePrice+'/'+totalPrice );
      if(currencyFirst) $('.total-sum #totalPrice').text( currency+' '+formatNumber(totalPrice, separator, useDecimal) );
      else $('.total-sum #totalPrice').text( formatNumber(totalPrice, separator, useDecimal)+' '+currency );
}

function getPriceFromObj( $o ) {
	identify(arguments);
	var sep
	var tmp = $o.text().split(' ');
	var numstr = '';
	for(var i = 0; i < tmp.length; i++) {
		if( /^\-?[0-9]*\.?[0-9]+$/.test( tmp[i] ) ) numstr += tmp[i];
	}
	return parseFloat(numstr);
	//return array_drop( $o.text().split(' ') ).join('').split(',').join('').split('.').join('') * 1;
}

function formatNumber(num, separator, useDecimal) {
	identify(arguments);
	if(separator == '') return num+( useDecimal ? '.00' : '' );
	num += '';
	x = num.split('.');
	x1 = x[0];
	x2 = x.length > 1 ? '.' + x[1] : '';
	var rgx = /(\d+)(\d{3})/;
	while (rgx.test(x1)) {
		x1 = x1.replace(rgx, '$1' + separator + '$2');
	}
	if(useDecimal) return x1 + x2 +'.00';
	else return x1+x2;
}

function array_drop(a) {
	identify(arguments);
	a.splice(a.length-1, 1);
	return a;
}

function dropShadow($obj, size) {
	identify(arguments);
	return false;

	var $img = $('img.shadow'+size);
	if($img.length == 0) {
		$img = $(document.createElement('img')).attr('src', 'images/shadow.'+size+'.png');
		$img.addClass('shadow'+size).css('width', (size+12)+'px').css('height', (size+12)+'px');
	}
	else $img.parent().remove('img#shadow169,img#shadow338');
	$obj.append($img.show());
	$img.css('cursor', 'pointer').click(function(){
		hideShadow(size);
		var href = $obj.find('a').attr('href').split('#').join('');
		if(href.indexOf( window.location.toString().split('#')[0] ) > -1) {
			href = href.split( window.location.toString().split('#')[0] );
			href = href.length > 1 ? href[1] : href[0];
		}
		$.historyLoad( href );
	});
}

function hideShadow(size) {
	identify(arguments);
	$('img.shadow'+size).hide().unbind('click');
}

function mylog(str) {
	try{ console.log(str); }
	catch(e) { }
}

var $i1, $i2;
function animateProductEntry() {
	identify(arguments);
      //mylog('animateProductEntry started...');
	scrollingDisabled = true;
	productAnimationInProgress = true;
	var mode = $("#Scrollable2").length > 0 ? 2 : 1;      // 2 or 1 lines of products
	$w1 = getCenteredBlock( $('#Scrollable1') );
	//mylog('getCenteredBlock returned '+$w1);

	if($w1 == null || $w1.length == 0) {
	      //mylog('$w1='+$w1+'$w1.length = 0');
	      $i1 = $i2 = $('#empty-set-which-doesnt-exist');
	      renderProductEntryAnimation();
	      return;
	}

	if(mode == 2) {
	      //mylog('animateProductEntry mode=2');
		$w2 = getCenteredBlock( $('#Scrollable2') );

	      if(singleProductAnimationEnabled) {
			var $td1 = $("<td class='DummyTD'><div class='ProductSmall' style='width: auto'><img id='dummy2' src='images/x.gif' style='width: 1px' /></div></td>");
	      	$i1 = $td1.find('img');
	      	$td1.insertBefore( $w1 );

	      	var $td2 = $("<td class='DummyTD'><div class='ProductSmall' style='width: auto'><img id='dummy2' src='images/x.gif' style='width: 1px' /></div></td>");
	      	$i2 = $td2.find('img');
	      	$td2.insertBefore( $w2 );
	      }

	      renderProductEntryAnimation();
	}
	else {
	      //mylog('animateProductEntry mode=else');
	      if(singleProductAnimationEnabled) {
	      	var $td1 = $("<td class='DummyTD'><div class='ProductSmall' style='width: auto'><img id='dummy2' src='images/x.gif' style='width: 1px' /></div></td>");
	      	$i1 = $td1.find('img');
	      	$td1.insertBefore( $w1 );
	      }

	      renderProductEntryAnimation();
	}
}

function renderProductEntryAnimation() {
	identify(arguments);
      //mylog('renderProductEntryAnimation called...');
	var step = 52;

	if( singleProductAnimationEnabled && $i1.length > 0 && $i1.width() < 4*169 ) {
	      //if(jQuery.browser.msie) $('#Scrollable1, #Scrollable2').hide();
	      //mylog(parseInt($i1.width())+'+'+step);
	      $i1.css('width', parseInt($i1.width())+step+'px');
	      if($i2 != undefined && $i2.length > 0) $i2.css('width', parseInt($i2.width())+step+'px');
	      //mylog($('#Scrollable1').attr('scrollLeft')+'+'+step/2);
		$('#Scrollable1').attr('scrollLeft', $('#Scrollable1').attr('scrollLeft')+step/2);
	      if($i2 != undefined && $i2.length > 0) $('#Scrollable2').attr('scrollLeft', $('#Scrollable2').attr('scrollLeft')+step/2);
	      //if(jQuery.browser.msie) $('#Scrollable1, #Scrollable2').show();
	      setTimeout(renderProductEntryAnimation, 50);
	}
	else {
	      //mylog('renderProductEntryAnimation - ELSE');
	      $i1 = $i2 = $('#empty-set-which-doesnt-exist');
	      $('#ProductContainer').css({left:'50%',opacity:0.01,display:'block'}).animate({opacity: 1}, 500, 'linear', function(){
      		if(jQuery.browser.msie && jQuery.browser.version == '7.0') {
			      $('#ProductContainer').css('filter', '');
			}
			if(isIE6) {
                        $('#ProductContainer .Close').insertAfter('#ProductContainer').css(
					{ top: '50%', left: '50%', 'margin-left': '315px', 'margin-top': '-230px' }
				).click(function(){
 					$(this).insertBefore($('#ProductContent'));
				});
		      }
  			productAnimationInProgress = false;
	      	if(postAnimationListener != null) {
				try{ postAnimationListener() }
				catch(e) { }
				postAnimationListener = null;
				scrollingDisabled = false;
			}
		});
	}
}

var getCenteredBlockRetries = 0;
function getCenteredBlock($s) {
	identify(arguments);
      //mylog('getCenteredBlock called...');
	if(!$s || $s.length == 0) return false;
	var $w = null;

	$s.find('td').each( function() {
	      if( Math.abs( $(this).offset().left - $s.width()/2 ) < $(this).width()/2+1 ) $w = $(this);
	});

	if($w == null) return $w;

	$s.attr('scrollLeft', parseInt( $s.attr('scrollLeft') ) + ( $w.offset().left - $s.width()/2 ) );

	if( $w.offset().left < Math.round($s.width()/2) ) {
		//$w = $w.next();
		//$s.attr('scrollLeft', parseInt( $s.attr('scrollLeft') ) + ( $w.offset().left - $s.width()/2 ) );
		$s.attr('scrollLeft', parseInt( $s.attr('scrollLeft') ) + $w.width() );
		getCenteredBlockRetries++;
		if(getCenteredBlockRetries < 5) $w = getCenteredBlock($s);

	}
	else if($w.offset().left > Math.round($s.width()/2) ) {
		//$w = $w.prev();
		//$s.attr('scrollLeft', parseInt( $s.attr('scrollLeft') ) + ( $w.offset().left - $s.width()/2 ) );
		$s.attr('scrollLeft', parseInt( $s.attr('scrollLeft') ) - $w.width() );
		getCenteredBlockRetries++;
		if(getCenteredBlockRetries < 5) $w = getCenteredBlock($s);
	}

	getCenteredBlockRetries = 0;

	return $w;
}

function animateProductExit() {
	identify(arguments);
      //mylog('animateProductExit');
	scrollingDisabled = true;
	productAnimationInProgress = true;
	$('#ProductContainer').animate({opacity:0.01}, 500, 'linear', function() {
	      $('#WholeContent>.Close').insertBefore($('#ProductContent'));
		$('#ProductContainer').css('display', 'none');
		renderProductExitAnimation();
	});
}

function renderProductExitAnimation() {
	identify(arguments);
	//mylog('renderProductExitAnimation');
	var step = 52;

	var $items = $('.DummyTD');
	if(singleProductAnimationEnabled && $items.length > 0 && $items.width() > step) {
		$items.each( function() {
			$(this).parents('#Scrollable1,#Scrollable2').each(function(){
				$(this).attr('scrollLeft', $(this).attr('scrollLeft')-step/2);
			});
			$(this).find('img').each(function(){
				$(this).css('width', parseInt($(this).width())-step+'px' );
			});
			$(this).css('width', '1px');
		});
		setTimeout(renderProductExitAnimation, 30);
	}
	//else if($items.length > 0) {
	else {
	      //mylog('renderProductExitAnimation - ELSE');
		$items.remove();
		productAnimationInProgress = false;
		$("#ProductsBlackoverlay").hide(1, function(){
			if(postAnimationListener != null) {
				try{ postAnimationListener() }
				catch(e) { }
				postAnimationListener = null;

			}
			scrollingDisabled = false;
		});
	}
}

function selectScrollStart(e) {
	identify(arguments);
	var step = 18;
 	var borderZone = 40;

	//mylog('selectScrollStart');
	selectScroller = this;
	$(this).css('overflow', 'hidden');
	if( e.pageY - $(this).offset().top < borderZone ) selectScrollDelta = -1*step;
	else if( $(this).offset().top + $(this).height - e.pageY < borderZone ) selectScrollDelta = step;
	else selectScrollDelta = 0;

	$(selectScroller).bind('mousemove',selectScrollChange);
	selectScrollInterval = setInterval( selectScrollTick, 166 );
}

function selectScrollEnd(e) {
	identify(arguments);
      //mylog('selectScrollEnd');
	$(selectScroller).unbind('mousemove',selectScrollChange);
	selectScroller = null;
	selectScrollDelta = 0;
	if(selectScrollInterval != null) clearInterval(selectScrollInterval);
	selectScrollInterval = null;
}

function selectScrollChange(e) {
	identify(arguments);
 	var step = 18;
 	var borderZone = 40;
      if( e.pageY - $(selectScroller).offset().top < borderZone ) selectScrollDelta = -1*step;
	else if( $(selectScroller).offset().top + $(selectScroller).height() - e.pageY < borderZone ) selectScrollDelta = step;
	else selectScrollDelta = 0;
}

function selectScrollTick() {
	identify(arguments);
      //mylog('selectScrollTick => '+selectScrollDelta+' '+selectScroller);
	if(selectScroller != null && selectScrollDelta != 0) {
		var oldScroll = $(selectScroller).attr('scrollTop');
		var newScroll = oldScroll + selectScrollDelta;
		//mylog('selectScrolled '+oldScroll+' => '+newScroll);
		$(selectScroller).attr('scrollTop', newScroll);
	}
}

function SingleProductZIndexWorkaround() {
	identify(arguments);
      //$('#ProductContent .newListSelected').css('z-index', '1000').fixIEZIndex( $('#ProductContent') );
      //$('#ProductContent .newListSelected .selectedTxt').css('z-index', '1001');
      $('#ProductContent .newListSelected ul.newList').css('z-index', '');
      //$('#ProductContent .newListSelected ul.newList li').css('z-index', '1003');
      $('#ProductContent .ProductColor .newListSelected ul.newList li').css('z-index', '1000').fixIEZIndex( $('#ProductContent').parent() );
      $('#ProductContent .ProductColor .newListSelected .selectedTxt').css('z-index', '998');
      $('#ProductContent .ProductSize .newListSelected ul.newList li').css('z-index', '900').fixIEZIndex( $('#ProductContent').parent() );
      $('#ProductContent .ProductSize .newListSelected .selectedTxt').css('z-index', '898');
      return true;
}

function validateDateField(f) {
	identify(arguments);
      var str = $(f).val();
      var msg = 'Birthday must be in the format mm.dd.yyyy';
      var $eb = $('.ErrorBox, .ErroBox');

      //     m     m   .  d     d   .  y    y    y    y
      if( /^(0[0-9]|1[0-2])\.([0-2][0-9]|3[0-1])\.(1|2)(0|9)[0-9][0-9]$/.test(str) ) {
            if($eb.length > 0 ) {
                  var txt = $eb.text();
                  txt = txt.split(msg).join('').replace(/(, $)/, '').replace(/(, ,)/, ',');
                  if(txt == '') $eb.remove();
                  else $eb.text(txt);
            }
      }
      else {

            if($eb.length == 0 && $('form.BorderForm').length > 0) {
                  $eb = $('<div class="ErrorBox" style="color: red; font-weight: bold"></div>');
                  $('form.BorderForm').prepend($eb);
            }

            var txt = $eb.text();
            txt = txt.split(msg).join('').replace(/(, $)/, '').replace(/(, ,)/, ',');
            txt += (txt.length > 0) ? ', ' : '';
            txt += msg;

            $eb.text(txt);
      }
}

String.prototype.isNumeric = function() {
      return /^[0-9]*$/.test(this);
}

var isIE6 = false;

function notifyIE6() {
	identify(arguments);
	isIE6 = true;
	//if(jQuery.browser.msie && parseFloat(jQuery.browser.version) < 7) {
	if($.cookie('ie6warned') != 'Yes') {
		showBlackOverlay( function() {
			$box = $("<div class='IE6'></div>");
			//$('#WholeContent').prepend($box);
			$('body').prepend($box);
			$box.append( $("<h3>Sorry</h3>") );
			$box.append( $("<p>The interactiveness of this website cannot be fullfilled by the abilities of MS Internet Explorer version 6 or earlier.</p>") );
			$box.append( $("<p>In order to get the full experience of browsing this website, you should upgrade to a newer version or use another browser.</p>") );
			$box.append( $("<p>You can get the latest version of MS Internet Explorer by following <a id='ie'>this link</a></p>") );
			$box.append( $("<p>Or you can check out other browsers if you don't have one yet:<ul id='others'></ul></p>") );
			$ul = $box.find('ul#others');
			$ul.append( $("<li><a id='ff'>Firefox</a></li>") );
			$ul.append( $("<li><a id='ch'>Google Chrome</a></li>") );
			$ul.append( $("<li><a id='op'>Opera</a></li>") );
			$ul.append( $("<li><a id='sa'>Safari</a></li>") );
			$box.append( $("<p>You can stay and browse this site with your current browser, if you like. Click <a id='close'>here</a> to close this popup</p>") );

			$box.find('#ie').attr('href', "http://www.microsoft.com/windows/internet-explorer/worldwide-sites.aspx");
			$box.find('#ff').attr('href', "http://www.getfirefox.com/");
			$box.find('#ch').attr('href', "http://www.google.com/chrome");
			$box.find('#op').attr('href', "http://www.opera.com/browser/");
			$box.find('#sa').attr('href', "http://www.apple.com/safari/");
			$box.find('#close').attr('href', "#").click( function(){ $('.IE6').hide(1,hideBlackOverlay); } );

			$.cookie('ie6warned', 'Yes');
		});
	}
	fixTransparentPng();
}

function identify(obj, name) {
	return false;
	if(obj != null) {
		if(jQuery.browser.msie) mylog(obj.callee.toString().split('(')[0]);
		else mylog(obj.callee.name);
	}
	else mylog(name+"");
}

function fixTransparentPng() {
	if(isIE6) {
		$('img.pngTransparent, img.transparentPng').each(function(){
	      	var src = $(this).attr('src');
	      	if(src.substr( src.length - 3 ) ) $(this).attr('src', src.substr( 0, src.length - 3)+'gif' );
		});
	}
}

function continueShopping() {
	if(lastVisitedProductsPage == null) {
	      for(i in pages) {
	            if(pages[i] == 'Product' && i != 'product' && i != 'search') {
	                  $.historyLoad(i);
	                  return;
	            }
	      }
	}
	else {
	      $.historyLoad(lastVisitedProductsPage);
	}
}

// JG rewritten gift wrapping
function giftwrapping() {
	var $box = $('#gift_wrapping');
	var giftPrice = 0;
  $.each( $('#giftWrapPrice').text().split(' '), function() { if( !isNaN(parseFloat(this)) ) giftPrice = parseFloat(this); } );

	var tmp = $('.subtotal #initPrice').text();
	var currency = tmp.match(/(£|DKK|SEK|€)/)[0];
	var currencyFirst = (tmp.indexOf(currency) == 0);

	tmp = tmp.split(' ');

	var separator = (tmp.length > 2) ? ' ' : ((tmp[0].split(',').length > 1) ? ',' : (tmp[0].split('.').length > 1) ? '.' : '');
	var initPrice = getPriceFromObj( $('.subtotal #initPrice') );
	var useDecimal = /[0-9]*\.[0-9][0-9]?/.test( $('.subtotal #initPrice').text() );

	if($box.attr('checked')) {
	  initPrice += giftPrice;
		if(currencyFirst) $('.subtotal #initPrice').text( currency+' '+formatNumber(initPrice, separator, useDecimal) );
		else $('.subtotal #initPrice').text( formatNumber(initPrice, separator, useDecimal)+' '+currency );
    updateTotalPrice();
    $('#fromToBlock').show();
    $('#giftWrapTr').show();
    $('#pseudoGiftWrapTr').hide();
	}
	else {
		initPrice -= giftPrice;
		if(currencyFirst) $('.subtotal #initPrice').text( currency+' '+formatNumber(initPrice, separator, useDecimal) );
	      else $('.subtotal #initPrice').text( formatNumber(initPrice, separator, useDecimal)+' '+currency );
	      updateTotalPrice();
				$('#fromToBlock').hide();
				$('#giftWrapTr').hide();
    		$('#pseudoGiftWrapTr').show();
	}
}

/*** ManUtd Special ***/

function ManUtdInit() {
	return;
  /*
  if($.cookie('ManUtdVisited') != null) {
//		mylog('Cookie='+$.cookie('ManUtdVisited'))
		return;
	}

	$('#ManUtdSpecial #PressRelease').fadeIn('slow', function(){
	      //setTimeout(ManUtdScrollInit, 100);
	      ManUtdScrollInit();
	      scrollInitHandlers[scrollInitHandlers.length] = ManUtdScrollInit;
	});
	$.cookie('ManUtdVisited', 1, {expires: 2/24});  // expires in 2 hours
	*/
}

function ManUtdScrollInit() {
	identify(arguments);
	var $scrollable = $("#ManUtdSpecial .Scrollable");
	var visible = $scrollable.height();
	$scrollable.css("height", "auto");

	scrollMax = $scrollable.height() - visible;
	scrollRatio = parseFloat(scrollMax)/(parseFloat(visible)-100);
	$scrollable.css("height", visible+"px");
	$scrollable.attr("scrollTop", 0);
	lastScrollTop = 0;

	$scrollable.find("#Scroll").css("display", "block");
	$scrollable.find("#CurrentScroll").css("top", "0px");
	scrollBarMax = visible - 80;
	$scrollable.find("#Scroll").mousedown(function() {
		$("body").mousemove(ManUtdScrollMouseMove);
		return false;
	});
	$("body").mouseup(function() {
		$("body").unbind("mousemove", ManUtdScrollMouseMove);
	});

	$scrollable.mousewheel( ManUtdHandleMousewheelScroll );
	$('#ManUtdSpecial #PRClose').click(ManUtdClosePR);
}

function ManUtdScrollMouseMove(event) {
	identify(arguments);
	var $scrollable = $("#ManUtdSpecial .Scrollable");
	var top = parseInt(getMousePos(event, 'Y')) - parseInt($scrollable.find("#Scroll").offset().top) - 50;
	top = Math.min(top, scrollBarMax);
	top = Math.max(top, 0);
	$scrollable.find("#CurrentScroll").css("top", top+"px");
	var contentScroll = Math.round(scrollRatio*top);
	$scrollable.attr("scrollTop", contentScroll);
	lastScrollTop = contentScroll;
	return false;
}

function ManUtdHandleMousewheelScroll (e, delta) {
	identify(arguments);
	var $scrollable = $("#ManUtdSpecial .Scrollable");
      var top = parseInt($scrollable.find("#CurrentScroll").offset().top) - parseInt($scrollable.find("#Scroll").offset().top);
	top -= delta*15;  // because up is positive and down is negative, while top should change in opposite direction
	top = Math.min(top, scrollBarMax);
	top = Math.max(top, 0);
	$scrollable.find("#CurrentScroll").css("top", top+"px");
	var contentScroll = Math.round(scrollRatio*top);
	$scrollable.attr("scrollTop", contentScroll);
	lastScrollTop = contentScroll;
	return false;
}

function ManUtdClosePR() {
	$('#ManUtdSpecial #PressRelease').fadeOut();
}