/*
		index of e-supplies.js functions:
		
		js(f) // include the javascript 'f' on the webpage
		log_debug(arguments) //console.log without breaking IE
		isNumberKey(evt) //Allow only numbers in an input-field
		toggleMainMenu() // open/close the different levels in the main menu
		toggleAreaMenu() // open/close the different levels in the area menu on clicks
		activateAjaxShopping() // append ajax shopping and updating of previewbasket
		validateForms() // validate forms based on hidden input fields
		autocompletePostalCode() // autocomplete on postal codes
		productlistImage() // productlist images - on mouseover, show large version of image
		postPolls() // post polls via an Ajax call
		postPollsForms() // form functions - are added when page loads and when the forms are being inserted into the page.
		quizWizzard() // create a wizzard like quiz, if there are more than one question
		tracktrace() // track & trace ajax implementation
		feedReader() // read rss and atom feeds
		changeProductImage() // show the small image thumbs in the large image position on productinfo pages
		flashLoad() // load flash elements if the class of a link is 'jsFlash'
		openPopups() // open links in a new window if they have 'jsOpen' as class
		sendmaildirect() // send an e-mail directly without a popup box to ask for e-mail. Requires some variables defined on the page
		showInlineHelp() // show inline help at help icons
		variantSelection() // if productvariants are available, find the input fields and activate Ajax implementation on them
		productVariantAjax() // common functionality for the variantSelection function
		modalAlert(strMessage) // a modal alertbox - containing only a message
		modalConfirm(strMessage) // a modal confirmation box - containing yes and no options
		createCookie(name,value,days) // create a local cookie with a name, value and optional days
		readCookie(name) // read the specified cookie
		eraseCookie(name) // delete the specified cookie
		errorInPaymentPopup() // if an urgent message is found, show it
*/

$(function(){
	variantSelection();
});

/*
GLOBAL FUNCTIONS 
**********************************************/
// include the javascript 'f' on the webpage
function js(f) {
  document.write('<script type="text/javascript" src="'+ f + '"></s' + 'cript>'); 
}
function js_defer(f) {
  document.write('<script defer type="text/javascript" src="'+ f + '"></s' + 'cript>'); 
}
//console.log without breaking IE
log_debug = function() {
  if(window.console && window.console.firebug) console.log.apply(this, arguments)
}
//Allow only numbers in an input-field
function isNumberKey(evt){
	var charCode = (evt.which) ? evt.which : event.keyCode
	if ((charCode > 47 && charCode < 58) || (charCode > 95 && charCode < 106) || (charCode == 8) || (charCode == 9) || (charCode == 12) || (charCode == 27) || (charCode == 37) || (charCode == 38) || (charCode == 39) || (charCode == 46)){
		return true;
	}
	return false;
}

/*
MENU
**********************************************/
// insert a style-tag, which hides the menu lists before they are shown
$('<style type="text/css">#mainMenu ul ul, #areaMenu ul.closed { display: none; }</style>').appendTo('head');

// open/close the different levels in the main menu
function toggleMainMenu(){
	$('#mainMenu li').hoverIntent(function(){ // on mouseover
		$('ul:first',this).fadeIn('fast');
	},function(){ // on mouseout
		$('ul:first',this).fadeOut('fast');
	});
}

// open/close the different levels in the area menu on clicks
function toggleAreaMenu(){
	$('#areaMenu li ul').prev().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('ul').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;
	})
	$('#areaMenu li ul.closed').prev().addClass('closed');
	$('#areaMenu li ul.open').prev().addClass('open');
}

/*
OTHER
**********************************************/
// append ajax shopping and updating of previewbasket 
function activateAjaxShopping(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'; // add an extra '_ajax' at the end of the template name and call the page with ajaxmode = 1 
	}
	
	// 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' + strAjaxMode,
				productid: this.productid.value,
				quantity: this.quantity.value,
				pkid: this.pkid.value
			},
			function(data){
				
				var $content = '';
				
				if (objArg.ajaxMode){
				
					$content = $(data).find(objArg.find);
				
				} else {
					
					// find the body element  
					var startCut = data.indexOf('<body');
					var endCut = data.indexOf('</body>') + 7;
					
					var $content = $(data.substring(startCut,endCut));
					
				}
				
				// replace the target with the new content
				$(objArg.target).replaceWith($content);
				
			},'html');
			
			// cancel the normal form submit
			return false;
		});
	});
	
	// add products to basket and update basketpreview
	$('#jsProducttobasket, .productlist form.addToBasket').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ødvendige 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,
				_Message: this._Message.value
			},
			function(data){
				
				var $content = '';
				
				if (objArg.ajaxMode){
				
					$content = $(data).find(objArg.find);
				
				} else {
					
					// find the body element  
					var startCut = data.indexOf('<body');
					var endCut = data.indexOf('</body>') + 7;
					
					var $content = $(data.substring(startCut,endCut));
					
				}
				
				// replace the target with the new content
				$(objArg.target).replaceWith($content);
				
			},'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;
	});
}
// 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 && relatedInput.attr('name') != 'horoskop__4')){ // 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 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;
			}
		}
	});
}

// autocomplete on postal codes
function autocompletePostalCode() {
	if ($.isFunction($(this).autocomplete)) {//kontroller om autocomplete-funktionen er importeret
		$('.jsPostalcode')
			.autocomplete('/dynamic.aspx?data=citynames&ajaxmode=1', {
				formatItem: function(row, i, max) {
					return row[0].replace('_',' ');
				},
				max: 9,
				extraParams: {
					countryid: function() { return $(':input[name="country"]').val(); }
				},
				width: '200px'
			})
			.result(function(event, data, formated){
				var result = data[0].split('_');
				$('.jsPostalcode').val(result[0]);
				if ($('.jsPostalcode').val() != '') {
					$('.jsCity').val(result[1]);
				} else {
					$('.jsCity').val('');
				}
			})
			.blur(function(){
				$this = $(this);
				if ($this.val() != ""){
					$.ajax({
						url: "/dynamic.aspx?data=citynames",
						data: {
							q: $this.val(),
							countryid: $('input[name="country"]').val(),
							ajaxmode: "1"
						},
						success: function(data){
							var strFirstResult = data.match(/(.+)\n/i)[1].split('_');
							$(".jsPostalCode").val(strFirstResult[0]);
							$(".jsCity").val(strFirstResult[1]);
						}
					});
				}
			});
	
		$('.jsCity, .jsCity2')
			.attr('readonly', true).addClass('disabled')
		;
		
		$('.jsPostalcode2')
			.autocomplete('/dynamic.aspx?data=citynames&ajaxmode=1', {
				formatItem: function(row, i, max) {
					return row[0].replace('_',' ');
				},
				max: 9,
				extraParams: {
					countryid: function() { return $(':input[name="country2"]').val(); }
				},
				width: '200px'
			})
			.result(function(event, data, formated){
				var result = data[0].split('_');
				$('.jsPostalcode2').val(result[0]);
				if ($('.jsPostalcode2').val() != '') {
					$('.jsCity2').val(result[1]);
				} else {
					$('.jsCity2').val('');
				}
			})
			.keydown(function(e){
				$('.jsPostalcode').unautocomplete();
				$('.jsCity').removeAttr('readonly').removeClass('disabled');
			})
			.blur(function(){
				$this = $(this);
				if ($this.val() != ""){
					$.ajax({
						url: "/dynamic.aspx?data=citynames",
						data: {
							q: $this.val(),
							countryid: $('input[name="country2"]').val(),
							ajaxmode: "1"
						},
						success: function(data){
							var strFirstResult = data.match(/(.+)\n/i)[1].split('_');
							$(".jsPostalCode2").val(strFirstResult[0]);
							$(".jsCity2").val(strFirstResult[1]);
						}
					});
				}
			});
	}
}


//new, slimmer version
//takes parameters to decide what fields should be affected. Also adds an blur() to make sure the city field always get a value.
function autocompletePostalCode2(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, formated){
				var result = data[0].split('_');
				$(pcodeField).val(result[0]);
				if ($(pcodeField).val() != '') {
					$(cityField).val(result[1]);
				} else {
					$(cityField).val('');
				}
			})
			.blur(function(){
				$this = $(this);
				if ($this.val() != ""){
					$.ajax({
						url: "/dynamic.aspx?data=citynames&ajaxmode=1",
						data: {
							q: $this.val(),
							countryid: $(countryField).val()
						},
						success: function(data){
							if (data != "") {
						  	var strFirstResult = data.match(/(.+)\n/i)[1].split('_');
						  	$(pcodeField).val(strFirstResult[0]);
						  	$(cityField).val(strFirstResult[1]);
						  }
						}
					});
				}
			});
		/*
		$(cityField)
			.attr('readonly', true).addClass('disabled')
		;
		*/
	}
}

// productlist images - on mouseover, show large version of image
function productlistImage(){
	$('.jsProductimg').bind('mouseenter',function(e){
		var $this = $('img',this);
		var img = $this.attr('src').substring($this.attr('src').lastIndexOf('/'));
		$('<img id="prodImgBig" src="/images/medium' + img + '" alt=""/>').css({
			position: 'absolute',
			top: $this.offset().top +'px',
			left: ($this.offset().left + $this.width() + 10) +'px',
			border: '1px solid #aaa',
			background: '#fff'
		}).appendTo('body');
	}).bind('mouseleave',function(){
		$('#prodImgBig').remove();
	});
}

// post polls via an Ajax call
function postPolls(){
	postPollsForms();
	
	$('.pollLinkResults, .pollLinkQuestions').live('click',function(){
		var $this = $(this);
			$.ajax({
				url: $this.attr('href').replace('/default.aspx','/dynamic.aspx'),
				success: function(data){
					var startCut = data.indexOf('<body');
					var endCut = data.indexOf('</body>') + 7;
					
					// replace the poll questions with the pollanswers
					$this.closest('.tPollquestions,.tPollanswers').replaceWith($(data.substring(startCut,endCut)));
					postPollsForms();
				}
			});
			return false;
	});
}

// form functions - are added when page loads and when the forms are being inserted into the page.
function postPollsForms(){
	$('.tPollquestions form:not(.pollAjaxed), .tQuizquestions form:not(.pollAjaxed)').each(function(){
		this._ReturnTo.value = this._ReturnTo.value.replace('/default.aspx','/dynamic.aspx');
		var $this = $(this);
		
		$(this).addClass('pollAjaxed').ajaxForm({
			success: function(data){
				var startCut = data.indexOf('<body');
				var endCut = data.indexOf('</body>') + 7;
				
				// replace the poll questions with the pollanswers
				$this.parent().replaceWith($(data.substring(startCut,endCut)));
			}
		});
	});
}

// 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;
	});
}

// read rss and atom feeds
function feedReader(){
	$('.rssFeed').each(function(){
			var $this = $(this),
					feed = $this.attr('class').replace('rssFeed feed:','');
			
			if (feed.match('http://') == null){ feed = 'http://' + feed; }
			feed = 'proxy.aspx?datatype=xml&url=' + feed;
			
			$.getFeed({
				url: 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);
				}
			});
	});
}

// show the small image thumbs in the large image position on productinfo pages
function changeProductImage(){
	$('#imagePreviewList a').click(function(){
		$('#imagePreviewList .largeImage img').attr('src',$(this).attr('href'));
		return false;
	});
}

// load flash elements if the class of a link is 'jsFlash'
function flashLoad(){
	$('a.jsFlash').flash(null,{version: 8},function(htmlOptions){
		var $this = $(this);
		var $parent = $this.parent();
		htmlOptions.src = $this.attr('href');
		htmlOptions.width = 185;
		htmlOptions.height = 128;
		htmlOptions.wmode = 'transparent';
		if ($parent.hasClass('intro')){
			htmlOptions.width = 767;
			htmlOptions.height = 220;
		}
		$parent.html('<div class="flashAlt">'+$this.parent().html()+'</div>');
		$parent.addClass('flash-replaced').prepend($.fn.flash.transform(htmlOptions));
	});
}

// open links in a new window if they have 'jsOpen' as class
function openPopups(){
	$('a.jsOpen').click(function(){
		window.open(this,'popup',"location=yes,width=500,height=500,scrollbars=yes,resizable=yes");
		return false;
	});
}

// send an e-mail directly without a popup box to ask for e-mail. Requires some variables defined on the page
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);
		});
	});
}

// show inline help at help icons
function showInlineHelp(){
	$('.jsHelp[title][title != ""]').hoverIntent(function(){
		$this = $(this);
		textHeight = $this.height();
		$('<span style="left: -9000px; top: 0;"><span>' + $this.attr('title') + '</span></span>').appendTo($this);
		var intHeight = ($('span',this).eq(0).height()/2) - (textHeight/2);
		
		$('span',this).eq(0).css({
			opacity: 0,
			left: ($this.width() + 10) + 'px',
			top: '-' + intHeight + 'px'
		}).animate({ opacity: 1 });
	},function(){
		$(this).find('span').fadeOut('fast',function(){ $(this).remove(); });
	});
}

// if productvariants are available, find the input fields and activate Ajax implementation on them 
function variantSelection(){
	if ($('#productVariants').size() > 0){
		productVariantAjax();
		$('#productVariants').find(':input').change(productVariantAjax);
	}
}

// common functionality for the variantSelection function 
function productVariantAjax(){
	var $this, noElement;
	
	if (this.name){
  	$this = $(this);
		noElement = false;
	} else {
		$this = '';
		noElement = true;
	}
	
	// clear the productid everytime we mess around with the variants
	$('#productVariants').closest('form').find('input[name="productid"]').val('');
	
	if ($(this).val() != '' || $this == '') {
  	
		var objBox, intIndex;
		if (noElement) { // if there is not an element in $this
			intIndex = 0;
			objBox = $('#productVariants').find(':input').eq(0); // return the first box
		}
		else {
			intIndex = $('#productVariants').find(':input').index(this); // the index of the current item in the object
			if ($('#productVariants').find(':input').eq(intIndex + 1).size() > 0) {
				objBox = $('#productVariants').find(':input').eq(intIndex + 1); // the next box
			}
			else {
				objBox = null;
			}
		}
		
		if ($this != ''){
			
				if ($this.data('variants') != ''){
					
					var arrData = $this.data('variants').split('|'),
							strNewImage = '',
							strNetPrice = '',
							strNetPrice2 = '';
					
					$.each(arrData,function(i){
						arrVariant = arrData[i].split(';');
						
						
						var strVariantValue = $this.val();
						
						if ($this.val().indexOf('$') != -1){
							strVariantValue = $this.val().split('$')[1];
						}
						
						var intIndexArray = $.inArray(strVariantValue,arrVariant);
						if (intIndexArray != -1){
						
							strNewImage = arrVariant[1];
							strNetPrice = arrVariant[2];
							strNetPrice2 = arrVariant[3];
							return false;
						
						}
					
					});
					
					// change images based on variants, if there is an image specified and there is an actual productimage on the page.
					if ($('#productImages').size() > 0){
					
						var objFirstimage = $('#productImages').find('img:first');
						var objFirstimageLink = objFirstimage.parent('a');
						if (objFirstimage.size() > 0 && strNewImage != '' && strNewImage != 'undefined'){
				
							var intIndexOfSlash = objFirstimage.attr('src').lastIndexOf('/')+1;
							objFirstimage.attr('src',objFirstimage.attr('src').substring(0,intIndexOfSlash) + strNewImage);
							
							if (objFirstimageLink.size() > 0) {
								var intIndexOfSlash2 = objFirstimageLink.attr('href').lastIndexOf('/')+1;
								objFirstimageLink.attr('href',objFirstimageLink.attr('href').substring(0,intIndexOfSlash2) + strNewImage);
							}
						}
						
						// if we have a lightbox container that should be updated, execute this function, if it exists
						if (typeof updateProductImagesLightbox == 'function'){
							updateProductImagesLightbox();
						}
					}
					
					
					// change netprice of the product, if it exists on the page and there is something in the variable
					if ($('#jsProductnetprice').size() > 0 && strNetPrice != '' && strNetPrice != '0,00' && strNetPrice != '0.00'){
						$('#jsProductnetprice').text(strNetPrice);
					}
					
					// change netprice2 of the product, if it exists on the page and there is something in the variable
					if ($('#jsProductnetprice2').size() > 0 && strNetPrice2 != '' && strNetPrice2 != '0,00' && strNetPrice2 != '0.00'){
						$('#jsProductnetprice2').text(strNetPrice2);
					}
					
				}
			
		}
		
		// when changing the last box, it must insert the value into the productid
		if (!objBox){
			if ($this.val() != ''){
				$('#productVariants').closest('form').find('input[name="productid"]').val($this.val());
			}
		} else {
			$('#productVariants').closest('form').find('input[name="productid"]').val('');
			objBox.attr('disabled', 'disabled'); // disable the object, that will be updated
		
			var bolLast = false;
			if ($('#productVariants').find(':input').index(objBox) == $('#productVariants').find(':input:not(:last)').size()){ // define whether this is the last object
				bolLast = true;
			}
			
			// if we are not working with an element, strVars should not be set
			var strVars;
			if (noElement){
				strVars = '';
			} else {
				
				
				var collectedVars = '';
				var intStopAtIndex = $('#productVariants').find(':input').index($this);
				
				// run through all variants and collect the previous variantinformation
				$('#productVariants').find(':input').each(function(i){
					
					if (i <= intStopAtIndex) {
					
						if ($(this).val()!= ''){
							if (i != 0){
								collectedVars += '|';
							} 
							collectedVars += $(this).val();	
						}
						
					}
					else {
						$(this).find('option[value !=""]').remove();
					}
					
					// stop when we reach the current element in the loop
					//if (i == intStopAtIndex){
					//	return false;
					//}
					
				});
				
				strVars = collectedVars;
			}
			

			// make an Ajax call to retrieve data for the next box

			$.ajax({
				url: '/dynamic.aspx',
				data: {
					ajaxmode: '1',
					data: 'utilizevariants',
					key: $('#productVariants').closest('form').find('input[name=original_productid]').val(),
					type: objBox.attr('id').replace('variant',''),
					vars: strVars,
					last: bolLast
				},
				dataType: 'text',
				success: function(data){
					var data2 = eval("(" + data + ")");
					var objVars = data2.variants.variant,
							strHtml = '<option value="">' + objBox.find('option').eq(0).text() + '</option>',
							strVariant = '';
						
					for(var i = 0; i<objVars.length;i++){
						if (objVars[i].productid != ''){
					
							strHtml += '<option value="' + objVars[i].productid + '">' + objVars[i].propertytext + '</option>';
							strVariant += '|' + objVars[i].productid;
					
						} else {
							strHtml += '<option value="' + objBox.attr('id').replace('variant','') + '$' + objVars[i].property + '">' + objVars[i].propertytext + '</option>';
							strVariant += '|' + objVars[i].property;
					
						}
					
						strVariant += ';' + objVars[i].imagefilename + ';' + objVars[i].netprice + ';' + objVars[i].netprice2;
					
					}
				
					objBox.html(strHtml); // insert the options into the box
					objBox.get(0).disabled = false; // enable the object again
					objBox.data('variants',strVariant.substring(1)); // insert the strImages without the first pipe

				},
				error: function(data,status,error){
//					log_debug(data);
//					log_debug(status);
//					log_debug(error);
				}

			});
			
		}
	}
}

// a modal alertbox - containing only a message
function modalAlert(strMessage){
	$.modal(strMessage,{overlayClose:true, minHeight: 10});
}

// a modal confirmation box - containing yes and no options
function modalConfirm(strMessage){
	var strOutput = '<div>' + strMessage + '</div><div><input id="modalYes" type="button" value="Ja"/><input id="modalNo" type="button" value="Nej"/></div>';
	$.modal(strOutput,{focus: false});
}

// show a modal box with an imagegallery on click on productinfo images
function showimagesonproductinfo(){
	if ($('#productImages').size() > 0){
		$('#productImages').find('a').click(function(){
			var strImage = $(this).attr('href');
			objImage = $('<img src="' + strImage + '" alt=""/>')
			$.modal(objImage);
			return false;
		});
	}
}

// create cookie on the local computer
function createCookie(name,value,days) {
	if (days) {
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	}
	else var expires = "";
	document.cookie = name+"="+value+expires+"; path=/";
}

// read a cookie on the local computer
function readCookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}

// erase cookie on the local computer
function eraseCookie(name) {
	createCookie(name,"",-1);
}

// if an urgent message is found, show it
function errorInPaymentPopup(){
	if ($('#jsUrgentmessage').size() > 0){
		if (!readCookie('urgentMessage') || readCookie('urgentMessage') != $('#jsUrgentMessageStripped').text().replace(/\n/gi,'')){
			$('#jsUrgentmessage .jsUrgentmessageInner').modal({
				overlayCss: {
					background: '#000',
					opacity: 0.5
				},
				containerCss: {
					width: '400px'
				},
				minHeight: $('#jsUrgentmessage .jsUrgentmessageInner').outerHeight(1)
			});
			
			createCookie('urgentMessage', $('#jsUrgentMessageStripped').text().replace(/\n/gi,''), 0.0146);
		}
	}
}
