/*
INCLUDES
**********************************************/
// specify which javascripts to include on the webpage
//js('/files/javascript/jquery.hoverIntent.minified.js');
//js('/files/javascript/jquery.form.js');
//js('/files/javascript/jquery.flash.js');
//js('/files/javascript/jquery.simplemodal-1.3.min.js');
//js('/files/javascript/jquery.jfeed.js');

js('/files/javascript/jquery.carousel.pack.js');

/*
ON LOAD
*********************************************/
// jQuery 'onReady' script - runs when the document have been loaded, but before images
$(function(){
	validateForms();
	//toggleMainMenu();
	toggleAreaMenu();
	toggleAreaMenu2();
	activateAjaxShopping();
	autocompletePostalCode();
	//productlistImage();
	postPolls();
	//quizWizzard();
	//tracktrace();
	//feedReader();
	flashLoad();
	openPopups();
	changeProductImage();
	basketpreviewToggle();
	wishlistpreviewToggle();
	replaceImageList();
	productVariants();
	productwishlistlink();
	productfavoriteslink();
	updatewishlist();
	sendmaildirect();
	defineProductSizes();
	tipsPopups();
	//shopOnlineModal();
	fixStoreLocatorHeight();	// Heyday
	
	$('.jsInput').toggleInputText();
	
	// activate carousel on lists with jsCarousel as a class
	$('.jsCarousel3').carousel({
		dispItems: 3,
		autoSlide: true,
		autoSlideInterval: 5000,
		loop: true
	});
	$('.jsCarousel4').carousel({
		dispItems: 4,
		autoSlide: true,
		autoSlideInterval: 5000,
		loop: true
	});

	// when clicking on the forgottenpass link, show the corresponding formular 
	$('.forgottenpass').click(function(){
		$('.forgottenpasswordform').show();
		return false;
	})
	
	$('.jsUpdatebasket').click(function(){
		$('#returnto').val('default.aspx?load=main&Data=Basket');
	});
	
	$('.productlist li a *').live('click',function(){
		location.href = $(this).closest('a').attr('href');
	});
	
	$('.jsGlspostalcode').blur(getGLS);
	if ($('.jsGlspostalcode').size() > 0) {
		getGLS();
	}
});


/*
MENU
**********************************************/
// insert a style-tag, which hides the menu lists before they are shown
$('<style type="text/css">#areaMenu2 ul.closed, #areaMenu2 div.closed { display: none; }</style>').appendTo('head');

// open/close the different levels in the area menu 2 on clicks
function toggleAreaMenu2(){
	$('#areaMenu2 li ul, #areaMenu2 li .groupContent').prev('a').click(function(){
		$this = $(this);
		if ($this.hasClass('closed')){
			// when the item is closed, open it and close all the open lists
			$this.removeClass('closed').addClass('open').next().slideDown('fast').parent().siblings().find('.groupContent').slideUp().prev().removeClass('open').addClass('closed');
		} else {
			// when the item is open, close it
			$this.removeClass('open').addClass('closed').next().slideUp('fast');
		}
		$this.blur();
		return false;
	})
	$('#areaMenu2 li ul.closed, #areaMenu2 li div.closed').prev('a').addClass('closed');
	$('#areaMenu2 li ul.open, #areaMenu2 li div.open').prev('a').addClass('open');
}

/*
OTHER
**********************************************/
// append ajax shopping and updating of previewbasket 
function activateAjaxShopping(){
	// remove products from basket and update basket preview
	$('.basketpreview input').live('click',function(){
		$(this).closest('form').submit(function(){
			$.post("post.aspx",{
				_Function: this._Function.value,
				_ReturnTo: 'dynamic.aspx?data=basket&template=basketpreview',
				productid: this.productid.value,
				quantity: this.quantity.value,
				pkid: this.pkid.value
			}, function(data){
				// find the body element  
				var startCut = data.indexOf('<body');
				var endCut = data.indexOf('</body>') + 7;
				// replace the old basketpreview with the body-content of 'data'
				$('.basketpreview').replaceWith($(data.substring(startCut,endCut)).find('.basketpreview'));
				$('.basketpreviewContent').show();
			},'html');
			
			// cancel the normal form submit
			return false;
		});
	});
	
	// add products to basket and update basketpreview
	$('.tProductinfo #productpurchase, .productlist table form.addToBasket').submit(function(){
		if (this.productid.value == ''){ return false; };
		var instock
		for (var i=0,varMax = arrVariants.length;i<varMax;i++){
			if (arrVariants[i]['productid'] == this.productid.value){
				instock = arrVariants[i]['instock'];
			}
		}
		
		if (!checkinstock(this.quantity.value,instock)) {
			return false;
		}
		if (parseInt(this.quantity.value) > parseInt(instock)) {
			this.quantity.value = instock;
		}
		if (!(confirm30(this.quantity.value))) {
			return false;
		}
		
		$.post("post.aspx",{
				_Function: this._Function.value,
				_ReturnTo: 'dynamic.aspx?data=basket&template=basketpreview',
				productid: this.productid.value,
				quantity: this.quantity.value,
				_Message: this._Message.value
			}, function(data){
					// find the body element  
				var startCut = data.indexOf('<body');
				var endCut = data.indexOf('</body>') + 7;
				// replace the old basketpreview with the body-content of 'data'
				$('.basketpreview').replaceWith($(data.substring(startCut,endCut)).find('.basketpreview'));
			},'html');
			
		
		// this is used to show that the form have been sent to the server and the basket have been updated  
		 $('.added',this).show(1,function(a){
			setTimeout(function(){
				$('.added').fadeOut('slow');
			},1000)
		});
		
		// cancel the normal form submit
		return false;
	});
	
	//Check instock on batch updatebasket
	$('.jsBatchupdatebasket').submit(function(){
		var $this = $(this);
		var bContinue = true;
		$this.find('input[name="productid"]').each(function(){
			var prodid = $(this).val();
			var $quantity = $(this).siblings('[name="quantity'+ prodid + '"]');
			if ($quantity.val() != ''){
				var $instock = $(this).siblings('[name="instock'+ prodid + '"]');
				var bCurrent = checkinstock($quantity.val(),$instock.val());
				
				if (parseInt($quantity.val()) > parseInt($instock.val())){
					if (bCurrent){
						$quantity.val($instock.val());
						bContinue = bCurrent;
					} else {
						$quantity.val('');	
					}
				}
				
				confirm30($quantity.val());
			}
		});
	});
}

// validate forms based on hidden input fields
function validateForms(){
$('form').unbind('submit');
	$('form').submit(function(e){
		var theForm = this;
		if ($('#old_validator').length == 0)
		{
			var ok = true;
			// select all 'required' fields inside the current form (indicated by the 'i')
			$('input:hidden[name*=Required]',theForm).each(function(){
				// find the related input for the required field
				var relatedInput = $(':input[name=' + $(this).attr('name').replace(/_Required$/i,'').replace(/^_/,'') + ']',theForm);
				
				if ((relatedInput.attr('type') == 'checkbox' && !relatedInput.attr('checked')) || (relatedInput.attr('type') != 'checkbox' && relatedInput.val() == '' && relatedInput.attr("disabled") != true)){ // if the input is empty, add a 'notValid' class on it
					ok = false;
					
					relatedInput.addClass('notValid_box');
					
					// if there is a label for the input field, add a 'notValid' class on it
					if (relatedInput.attr('id') != ""){
						$('label[for=' + relatedInput.attr('id') + ']').addClass('notValid');
					}
				}
				else if (relatedInput.attr('type') == 'radio' && !relatedInput.attr('checked')){
					var radiosOk = false;
					relatedInput.each(function(){
						log_debug(this, $(this).attr('checked'))
						if ($(this).attr('checked')){
							radiosOk = true;
							return false;
						}
					});
					log_debug(radiosOk);
					if (!radiosOk){
						ok = false;
					}
				}
				else { // if the input is not empty, remove the 'notValid' class, if there is one
					relatedInput.removeClass('notValid_Box');
					
					// if there is a label for the input field, remove the 'notValid' class on it
					if (relatedInput.attr('id') != ""){
						$('label[for=' + relatedInput.attr('id') + ']').removeClass('notValid');
					}
				}
			});

			// e-mail validation, check if mails are correctly typed
			$(':input:hidden[name*=IsEmail]',theForm).each(function(){
				// find the related input for the required field
				var relatedInput = $('input[name=' + $(this).attr('name').replace(/_IsEmail$/i,'').replace(/^_/,'') + ']',theForm);
				var mailValid = relatedInput.val().match(/^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}\b/i);

				if (!mailValid){ // if the mailValid does not return anything, add a 'notValid' class on the input
					ok = false;
					relatedInput.addClass('notValid_box');
					
					// if there is a label for the input field, add a 'notValid' class on it
					if (relatedInput.attr('id') != ""){
						$('label[for=' + relatedInput.attr('id') + ']').addClass('notValid');
					}
				}
			});
			
			
			if (!ok){ // tell the user, that the validation failed, and that he should check the input fields
				if ($('input[name=contactvalidation]',theForm).length > 0){
					alert($('input[name=contactvalidation]',theForm).val());
				} else {
					alert('Udfyld alle markerede felter.');
				}
				return false;
			}
		}
	});
}

// create a wizzard like quiz, if there are more than one question
function quizWizzard(){
	var btnNext = 'Næste';
	if(typeof(btnTextNext) !== 'undefined' && btnTextNext != '') { var btnNext = btnTextNext }
	
	$('.tQuizquestionssingle').each(function(){
		$this = $(this);
		
		if ($this.find('.quizItem').size() > 1){
			$this.find('.quizItem, .actions').hide().eq(0).show();
			$('<div class="quizItemActions"/>').appendTo($this.find('.quizItem').not(':last')).append('<input type="button" value="' + btnNext + '" />');
			
			
			$this.find('.quizItemActions input').click(function(){
				var quizItem = $(this).closest('.quizItem');
				quizItem.hide();
				
				if (quizItem.nextAll('.quizItem').size() < 2){
					quizItem.closest('.tQuizquestions').find('.actions, .quizItem:last').show();
					quizItem.closest('.tQuizquestions').find('.quizStart').hide();
				} else {
					quizItem.next('.quizItem').show();
				}
			});
		}
	});
}

// track & trace ajax implementation
function tracktrace(){
	$('.mTracktrace form').submit(function(){
		$.get('proxy.aspx', {
			url: 'http://www.postdanmark.dk/tracktrace/TrackTrace.do?barcode=' + this.i_stregkode.value + '&i_lang=' + this.i_lang.value 
		}, function(data){
			data = data.replace(/<script\b[^>]*>(.*?)<\/script>/gi,'');	
			var startCut = data.indexOf('<body');
			var endCut = data.lastIndexOf('</body>') + 7;
			
			$('#tracktraceOutput').html($(data.substring(startCut,endCut)));
			if ($('#tracktraceOutput #pdkTable').size() > 0){
				$('#tracktraceResult').empty().append('<div/>');
				$('#tracktraceOutput').find('#pdkTable').prev().appendTo('#tracktraceResult>div');
				$('#tracktraceOutput').find('#pdkTable').appendTo('#tracktraceResult>div');
				$('#tracktraceOutput').empty();
			} else {
				var noTrackTrace = 'Der er ingen track & trace der passer på din efterspørgsel';
				if(typeof(textNoTrackTrace) !== 'undefined' && textNoTrackTrace != '') { var noTrackTrace = textNoTrackTrace }
				
				$('#tracktraceResult').html('<p class="error">' + noTrackTrace + '</p>');
			}
		});
		return false;
	});
}

// resize footer height to fit the pageheight 
function resizeFooter(){
	/*
	console.log($('#Footer').height());
	$('#Footer').height('auto');
	console.log($('#Footer').height());
	var footerHeight = $(document).height() - $('#content').height();
	console.log(footerHeight);
	if (footerHeight > 0){
		$('#Footer').height($('#Footer').height() + footerHeight);
	}
	console.log($('#Footer').height());
	*/
}

// jQuery plugin to replace the text in input fields on focus/blur
(function($){
	$.fn.toggleInputText = function(){
		var elements = this;
		return (elements.each(function(){
			var el = $(this), title = el.attr('title');
			if (el.val() == "") {el.val(title)};
			el.focus(function(){
				if(el.val() == title) {el.val("")};
			}).blur(function(){
				if(el.val() == "") {el.val(title)};
			});
		}));
	};
})(jQuery);


// show the small image thumbs in the large image position on productinfo pages 
function changeProductImage(){
	$('#imagePreviewList a').live('click', function(){
		$('#imagePreviewList .largeImage img').attr('src',$(this).attr('href'));
		return false;
	});
}

function minimumOrder(){
	$('.tProductinfo form').submit(function(){
		var minQuantity = $(this).find('#quantity_min').val();
		var quantity = $(this).find('#quantity').val();
		
		if(quantity < minQuantity){
			alert('Du kan ikke bestille');
			return false;
		}
	});
}

// toggle visibility of the basketpreview
function basketpreviewToggle(){
	$('.basketpreview').live('mouseover',function(){
		$('.basketpreviewContent').show();
	}).live('mouseout',function(){
		$('.basketpreviewContent').hide();
	});
}

// toggle visibility of the wishlist
function wishlistpreviewToggle(){
	$('.wishlist').live('mouseover',function(){ $('.wishlistContent').show(); })
	.live('mouseout',function(){ $('.wishlistContent').hide(); });
}

// change the product variants, if available
function productVariants() {
	if ($('.tProductinfo').size() > 0){
		// find all color images and append a live click event
		if ($('#colorselection').find('img').size() > 1){
				
			$('#colorselection').find('img').live('click',function(){
				var $this = $(this),
						isCustomer = $this.parent().hasClass('jsCustomerselect'),
						colourid = $this.attr('class').replace('colourid','');
		
				if ($this.hasClass('active')) {
					return false;
				}
				
				// when image is clicked, add css class 'active' and remove 'active' from the siblings
				$this.addClass('active').siblings().removeClass('active');
				
				replaceImageList(colourid, $this.attr('src').replace('/images/thumb/',''));
					
				// replace the large image with a new
				// 07/08-2009 EI: Functionality moved to above function
				//$('#imagePreviewList').find('.largeImage img').attr('src',$this.attr('src').replace('/thumb/','/large/'));
				
				if (isCustomer){
					$('#variantscolor' + colourid).show().siblings().hide();
				}
				else {
					// go through the array and find all available sizes for the specific color,
					// append available colors to the newOptions variable
					
					if (useLengths){
						var newOptionsLengths = '';
						for (var y=0,varMaxColor = arrColorLengths.length;y<varMaxColor;y++){
							if (arrColorLengths[y]['colourid'] == colourid){
								newOptionsLengths += '<option value="' + arrColorLengths[y]['variant'] + '">' + arrColorLengths[y]['variantname'] + '</option>';
							}
						}
						// delete all but the first option inside the select #lengthselection and append the new options.
						//  the first option is the "label"
						$('#lengthselection').find('option:not(:first)').remove().end().append(newOptionsLengths);
						$('#sizeselection').find('option:not(:first)').remove();
					}
					else {
						var newOptions = '';
						for (var i=0,varMax = arrVariants.length;i<varMax;i++){
							if (arrVariants[i]['colourid'] == colourid){
								newOptions += '<option value="' + arrVariants[i]['productid'] + '">' + arrVariants[i]['size'] + '</option>';
							}
						}
						// delete all but the first option inside the select #sizeselection and append the new options.
						//  the first option is the "label"
						$('#sizeselection').find('option:not(:first)').remove().end().append(newOptions);
					}
					
					
					// reset the value of the input "productid" - it should only be set via size selection
					if ($('#sizeselection').size()>0){
						$(this).closest('form').find('input[name="productid"]').val('');
					}
					else {
						for (var j=0,varMax2=arrVariants.length;j<varMax2;j++){
							if (arrVariants[j]['colourid'] == colourid){
								$(this).closest('form').find('input[name="productid"]').val(arrVariants[j]['productid']);
							}
						}
					}
					defineProductSizes();
				}
			});
		}
		
		$('#lengthselection').change(function(){
			var colourid = $.trim($('#colorselection .active').attr('class').replace('active','').replace('colourid',''));
			var newOptions = '';
			for (var i=0,varMax = arrVariants.length;i<varMax;i++){
				if (arrVariants[i]['colourid'] == colourid && arrVariants[i]['variant'] == $(this).val()){
					newOptions += '<option value="' + arrVariants[i]['productid'] + '">' + arrVariants[i]['size'] + '</option>';
				}
			}
			// delete all but the first option inside the select #sizeselection and append the new options.
			//  the first option is the "label"
			$('#sizeselection').find('option:not(:first)').remove().end().append(newOptions);
		});
		
		// when selecting a size, insert the new productid in the productid input
		$('#sizeselection').change(function(){
			$(this).closest('.tProductinfo').find('input[name="productid"]').val($(this).val());
			
			var foundwishlistitem = false;
			for (var i=0,varMax = arrVariants.length;i<varMax;i++){
				if (arrVariants[i]['productid'] == $(this).val() && arrVariants[i]['onwishlist'] != ''){
					$('#productremovefromwishlist input[name="pkid"]').val(arrVariants[i]['onwishlist']);
					$('.sendtowishlist').show();
					$('.sendtowishlist.sendto').hide();
					foundwishlistitem = true;
					break;
				}
			}
			if (!foundwishlistitem){
					$('.sendtowishlist').hide();
					$('.sendtowishlist.sendto').show();
			}
		});
		
		// when a customer is logged in, the variants are differently placed.
		$('.tProductinfo .productvariants table').each(function(){
			$(this).find('tr:odd').addClass('odd');
		}).filter(':first').siblings().hide();
	}
}

// send to and remove from wishlist on a product
function productwishlistlink(){
	$('.sendtowishlist').click(function(){
		if ($(this).hasClass('sendto')){
			$('#productaddtowishlist').submit();	
		}
		else {
			$('#productremovefromwishlist').submit();
		}
		return false;
	});
}

function productfavoriteslink(){
	$('.sendtofavorites').click(function(){
		if ($(this).hasClass('sendto')){
			$('#productaddtofavorites').submit();	
		}
		else {
			$('#favoritesdeleteitem').submit();
		}
		return false;
	});
	$('.tFavorites .delete img').click(function(){
		$('#favoritesdeleteitem input[name="FavoriteId"]').val($(this).attr('class').replace('jsProdid',''));
		$('#favoritesdeleteitem').submit();
	});
}

// update wishlist via ajax
function updatewishlist(){
	$('.wishlist input').live('click',function(){
		$(this).closest('form').submit(function(){
			$.post("post.aspx",{
				_Function: this._Function.value,
				_Message: this._Message.value,
				_ReturnTo: 'dynamic.aspx?data=basket&template=basketpreview',
				pkid: this.pkid.value
			}, function(data){
				// find the body element  
				var startCut = data.indexOf('<body');
				var endCut = data.indexOf('</body>') + 7;
				// replace the old basketpreview with the body-content of 'data'
				$('.wishlist').replaceWith($(data.substring(startCut,endCut)).find('.wishlist'));
				$('.wishlistContent').show();
			},'html');
			
			// cancel the normal form submit
			return false;
		});
	});
	
	$('.tWishlist .delete img').click(function(){
		$('#wishlistdeleteitem input[name="pkid"]').val($(this).attr('class').replace('jsProdid',''));
		$('#wishlistdeleteitem').submit();
	});
}

//Check that the customer doesn't buy more than in stock
function checkinstock(quantity, instock) {
	if (parseInt(instock) < parseInt(quantity)) {
		return confirm(messageLowstockstart + ' ' + instock.toString() + ' ' + messageLowstockend);
	} else {
		return true;
	}
		
}

//Ask the customer to confirm before buying more than 30
function confirm30(quantity) {
	if (quantity < 30) {
		return true;
	} else {
		return confirm(messageAccept30start + ' ' + quantity.toString() + ' ' + messageAccept30end);
	}
}

function sendmaildirect(){
	$('.jsSendmail').click(function(){
		$.post('post.aspx',{
			_Function: 'Sendmail',
			_ReturnTo: '/default.aspx',
			data: mailData,
			template: mailTemplate,
			key: mailKey,
			subject: mailSubject,
			toname: mailToname,
			toemail: mailToemail,
			fromname: mailFromname,
			fromemail: mailFromemail
		}, function(){
			alert(mailsenttext);
		});
	});
}



function defineProductSizes(){
	if ($('#productText').size()>0){
		if (arrVariants[1] && useSizes){
			var arrPossibleSizes = allSizes.split(',');
			var arrAvailableSizes = new Array(arrPossibleSizes.length);
			var activeColour = $('#colorselection .active').attr('class').replace(' active','').replace('colourid','');
			
			for(var i=0,possibleMax=arrPossibleSizes.length;i<possibleMax;i++){
				for(var j=0,varMax=arrVariants.length;j<varMax;j++){
					if (arrVariants[j]['colourid'] == activeColour && arrVariants[j]['size'] == arrPossibleSizes[i]){
						arrAvailableSizes[i] = arrPossibleSizes[i];
						break;
					};
				}
			}
			
			var stringhtml = '<li class="availablesizes">';
			var imgNa = '';
			for(var k=0,possibleMax2=arrPossibleSizes.length;k<possibleMax2;k++){
				if(!arrAvailableSizes[k]){
					imgNa = '_na';
				}
				stringhtml += '<img src="/images/sizes_' + arrPossibleSizes[k].toLowerCase() + imgNa + '.gif" alt=""/>';
				imgNa = '';
			}
			stringhtml += '</li>';
			
			if($('#productText .availablesizes').size()>0){
				$('#productText .availablesizes').replaceWith(stringhtml);
			} else {
				$('#productText .subInfo').prepend(stringhtml);
			}
		}
	}
}

function getGLS(){
		var formular = $('#form1').get(0);
		$.post("post.aspx",{
			_Function: 'Return',
			_ReturnTo: 'dynamic.aspx?data=glsdelivery',
			//@firstname: formular.@firstname.value,
			//@lastname: formular.@lastname.value,
			street: formular.street.value,
			postalcode: formular.postalcode.value,
			city: formular.city.value,
			phone: formular.phone.value,
			email: formular.email.value,
			newsletter: formular.newsletter.value,
			acceptterms: formular.acceptterms.value,
			//@firstname2: formular.@firstname2.value,
			//@lastname2: formular.@lastname2.value,
			street2: formular.street2.value,
			postalcode2: formular.postalcode2.value,
			city2: formular.city2.value,
			phone2: formular.phone2.value,
			paymentid: formular.paymentid.value
		}, function(data){
			// find the body element  
			var startCut = data.indexOf('<body');
			var endCut = data.indexOf('</body>') + 7;
			// replace the old basketpreview with the body-content of 'data'
			var glsdata = $(data.substring(startCut,endCut)).find('#jsGlsdata');
			if(glsdata.size() > 0) {
				$('#jsGlsdata').replaceWith(glsdata);
			} else {
				$('#jsGlsdata').empty();
			}
		},'html');
	}
	
function flashLoad(){
	$('.tFrontpage a.jsFlash').flash(null,{version: 7},function(htmlOptions){
		var $this = $(this);
		var $parent = $this.parent();
		htmlOptions.src = $this.attr('href');
		htmlOptions.width = 185;
		htmlOptions.height = 128;
		htmlOptions.wmode = 'transparent';
		$parent.html('<div class="flashAlt">'+$this.parent().html()+'</div>');
		$parent.addClass('flash-replaced').prepend($.fn.flash.transform(htmlOptions));
	});
	
	// find an eventual flash file for the large frontpage image
	$('.tFrontpage.jsFlash').flash(null,{version: 7},function(htmlOptions){
		var $this = $(this);
		var RedGreenFlashSizes = {
			'collection': { width: 740, height: 436 }, 
			'locator': { width: 740, height: 620 },
			'defaults': { width: 945, height: 436 }
		};
		htmlOptions.src = $this.attr('class').substr($this.attr('class').indexOf('/'));
		
		var dimensions = RedGreenFlashSizes.defaults;
		if (htmlOptions.src.indexOf('/files/collection.swf') == 0) {
			dimensions = RedGreenFlashSizes.collection;
		} else if (htmlOptions.src == '/files/storeLocator.swf') {
			 dimensions = RedGreenFlashSizes.locator;
		}
		htmlOptions.width = dimensions.width;
		htmlOptions.height = dimensions.height;
		
		htmlOptions.wmode = 'transparent';
		$this.prepend('<div class="flashBackground">' + $.fn.flash.transform(htmlOptions) + '</div>');
		
	});
	
}

function replaceImageList(colourid, mainImage) {
	if ($('#imagePreviewList').size() > 0 && $('#colorselection').size() > 0){
		log_debug(colourid,mainImage);
		if(!colourid){
			colourid = $('#colorselection').find('img:first').attr('class').replace('colourid','').replace(' active','');
		}
		if(!mainImage){
			mainImage = $('#colorselection').find('img:first').attr('src').replace('/images/thumb/','')
		}
		log_debug(colourid,mainImage);
		
		var newImages
		newImages = '<li class="largeImage"><img src="/images/large/' + mainImage + '" alt=""/></li>';
		if (arrColourImageLists.length > 0) {
			for (var i=0,varMax = arrColourImageLists.length;i<varMax;i++){
				if (arrColourImageLists[i]['colourid'] == colourid){
					newImages += '<li><a href="/images/large/' + arrColourImageLists[i]['filename'] + '"><img src="/images/thumb/' + arrColourImageLists[i]['filename'] + '" alt="" /></a></li>';
				}
			}
			newImages += '<li><a href="/images/large/' + mainImage + '"><img src="/images/thumb/' + mainImage + '" alt="" /></a></li>';
		}
		$('#imagePreviewList ul').find('li').remove().end().append(newImages);
	}
};

// make inline popups for help/tips
function tipsPopups(){
	$('.jsHelp').click(function(){
  	$('span',this).show();
		$(document).one('click',function(){
			$('.jsHelp span').hide();
		});
		return false;
	});
}


function shopOnlineModal(){
	
	if (typeof langDanish != 'undefined'){
		if (!langDanish){
			$('#nav-shoponline a').click(function(){
				$.modal('<p>The REDGREEN onlineshop is currently only available for the danish market. We expect to open up for the swedish and german market in the first quarter of 2010.</p><p><a href="http://onlineshop.redgreen.dk/default.aspx">Proceed to http://onlineshop.redgreen.dk</a><br/><br/><a href="javascript: $.modal.close();">Return to website</a></p>');
				return false;
			})
		}
	}
}

// Corrects the height of the storLocator flash
function fixStoreLocatorHeight() {
	if ($('.flash\\:\\/files\\/storeLocator\\.swf')) {
		$('.flash\\:\\/files\\/storeLocator\\.swf').height(620);		
	}
}

// Insert Flash element on the frontpage of the shop - replaces a default fallback jpg
function addNewsLetterFlash() {
	$('.tGroup a.jsFlash').flash(null, {version: 7}, function(htmlOptions) {
		var $this = $(this);
		htmlOptions.src = '/files/newsletter_235x264-dk.swf';
		htmlOptions.width = 235;
		htmlOptions.height = 264;
		htmlOptions.wmode = "transparent";
		$this.html('<div class="narrow">' + $.fn.flash.transform(htmlOptions) + '</div>');
	});
}
