/*
GLOBAL FUNCTIONS 
**********************************************/
// include the javascript 'f' on the webpage
function js(f) {
  document.write('<script 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;
}

/* global variable set */
var globals = {
	validNewslettersubscribe: false // if this is true, it's okay to submit the newsletter subscription form
}

/*
INCLUDES
**********************************************/
// specify which javascripts to include on the webpage
js('/files/javascript/jquery.hoverIntent.minified.js');
js('/files/javascript/jquery.flash.js');
//js('/files/javascript/ui.core.js');
//js('/files/javascript/ui.slider.js');
//js('/files/javascript/jquery.mousewheel.min.js');
//js('/files/javascript/jquery.gzoom.js');
js('/files/javascript/jcarousellite_1.0.1.min.js');
js('/files/javascript/slimbox2.js');

//js('/files/javascript/jquery.form.js');
//js('/files/javascript/jquery.jfeed.js');

/*
ON LOAD
*********************************************/
// jQuery 'onReady' script - runs when the document have been loaded, but before images
$(function(){
	//validateForms();
	formValidation();
	toggleMainMenu();
	toggleAreaMenu();
	activateAjaxShopping();
	autocompletePostalCode();
	productlistImage();
	postPolls();
	quizWizzard();
	tracktrace();
	feedReader();
	changeProductImage();
	flashLoad();
	openPopups();
	//activateGzoom();
	newslettersubscribe();
	bindDelivery_form();
	/*bindDelivery_contact();*/
	productbarTabs();
	//variantKontrol();
	variantSelection();
	imagefilename_fix();
	
	$('.jsInput').toggleInputText();
	
	// set carousel on "you saw" on basket
	if ($('#IgnoreScroll').val() != "1")
	{
		$('#basketyousawcontent').jCarouselLite({
			btnNext: ".next",
			btnPrev: ".prev",
			auto: 4000,
			visible: 3 //2
		});
	}
});

/* Imagefilename space fix */
function imagefilename_fix() {
	$("a").each(function(){
		$(this).attr('href',encodeURI($(this).attr("href")));
	});
}
/* end: Imagefilename space fix */
/*
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');
}


/*function toggleAreaMenu(){
	$('#areaMenu li ul').prev().addClass('closed').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');
		}
		return false;
	});
}*/


/*
OTHER
**********************************************/
// Validate postalcode
function ValidatePostalCode()
{
	if ($('#postalcode').val() > 999 && $('#postalcode').val() < 10000)
	{
		return true;
	}
	else
	{
		return false;
	}
}

// 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(){
			
			q = this.quantity.value;
			
				$.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)));
				},'html');
				
				// Max salg begrænsning (AS d.23/09-09)
				if ($('#buycontrol_variant').length > 0)
				{
					$('#buycontrol_variant').val(parseInt($('#buycontrol_variant').val()) + 1);
				}
				else
				{
					$('#buycontrol').val(parseInt($('#buycontrol').val()) + 1);
				}
				
				// cancel the normal form submit
				return false;
			});
	});
	
	// add products to basket and update basketpreview
	$('#productinfo form, .productlist table form.addToBasket').submit(function(){
	
		// Max salg begrænsning (AS d.23/09-09)
		if (($('#buycontrol_variant').length < 1) && (parseInt($('#buycontrol').val()) > 0))
		{
			if ($(this).find('input[name=productid]').val() == ''){
				alert('Udfyld alle felter');
				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)));
				},'html');
			
			// Max salg begrænsning (AS d.23/09-09)
			$('#buycontrol').val(parseInt($('#buycontrol').val()) - 1); // Max salg begrænsning (AS d.23/09-09)

			// 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;
		}
		else if (($('#buycontrol_variant').length > 0) && (parseInt($('#buycontrol_variant').val()) > 0))
		{
			if ($(this).find('input[name=productid]').val() == ''){
				alert('Udfyld alle felter');
				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)));
				},'html');
			
			// Max salg begrænsning (AS d.23/09-09)
			$('#buycontrol_variant').val(parseInt($('#buycontrol_variant').val()) - 1);

			// 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;
		}
		else
		{
			$('.notadded_maxsale',this).show(1,function(a){
				setTimeout(function(){
					$('.notadded_maxsale').fadeOut('slow');
				},1000)
			});
			return false;
		}
	});
}
// validate forms based on hidden input fields
function validateForms(){
$('form').unbind('submit');
	$('form').submit(function(e){
	
		/* Nyt 13/11-2009 AS */
		if ($('#contact').length != 0)
		{
			$('#contact').val($('#firstname').val() + ' ' + $('#lastname').val());
			$('#contact2').val($('#firstname2').val() + ' ' + $('#lastname2').val());
		}
		/* Slut nyt AS */
	
		var theForm = this;
		if ($('#old_validator').length == 0)
		{
			var ok = true;
			var postalwarning = false;
			var emailwarning = false;
			// select all 'required' fields inside the current form (indicated by the 'i')
			$('input:hidden[name*=Required],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('name') == 'postalcode' && (relatedInput.val() > 9999 || relatedInput.val() < 1000) && $('input:hidden[name*=postalcode_dk]').length != 0)
				{
					ok = false;
					relatedInput.addClass('notValid_box');
					postalwarning = true;
				}
				
				if ((relatedInput.attr('type') == 'checkbox' && !relatedInput.attr('checked')) || (relatedInput.attr('type') != 'checkbox' && (relatedInput.val() == '' || 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;
					emailwarning = true;
					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 we are in the newsletter subscription form, indicate that it's not okay to submit the form
				if ($(theForm).hasClass('subscribenewsletterform')){
					globals.validNewslettersubscribe = false;
				}
			
				if ($('input[name=contactvalidation]',theForm).length > 0){
					alert($('input[name=contactvalidation]',theForm).val());
				} else {
					var warningStr = 'Udfyld alle markerede felter.';
					if (postalwarning)
					{
						warningStr = warningStr + ' Postnumre skal være mellem 1000-9999.';
					}
					if (emailwarning)
					{
						warningStr = warningStr + ' E-mail adresser skal være gyldige.';
					}
					alert(warningStr);
				}
				return false;
			}
			
			// if we are in the newsletter subscription form and if we have come this far, then it's okay to submit the form
			if ($(theForm).hasClass('subscribenewsletterform')){
				globals.validNewslettersubscribe = true;
			}
			
		}
	});
}

// autocomplete on postal codes
function autocompletePostalCode() {
	if ($.isFunction($(this).autocomplete)) {//kontroller om autocomplete-funktionen er importeret
		$('.jsPostalcode')
			.autocomplete("/dynamic.aspx?data=citynames", {
				formatItem: function(row, i, max) {
					return row[0].replace("_", " ");
				},
				max: 100
			})
			.result(function(event, data, formated){
				var result = data[0].split("_");
				$(".jsPostalcode").val(result[0].replace("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 Transitional//EN\">","").replace("<span id=\"Placeholder\" style=\"Z-INDEX: 101; POSITION: absolute;\"></span>",""));
				if ($(".jsPostalcode").val() != "") {
					$(".jsCity").val(result[1]);
				} else {
					$(".jsCity").val("");
				}
			})
			.keydown(isNumberKey)
		;
	
		$(".jsCity, .jsCity2")
			.attr("readonly", true).addClass("disabled")
		;
		
		$('.jsPostalcode2')
			.autocomplete("/dynamic.aspx?data=citynames", {
				formatItem: function(row, i, max) {
					return row[0].replace("_", " ");
				},
				max: 100
			})
			.result(function(event, data, formated){
				var result = data[0].split("_");
				$(".jsPostalcode2").val(result[0].replace("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 Transitional//EN\">", "").replace("<span id=\"Placeholder\" style=\"Z-INDEX: 101; POSITION: absolute;\"></span>", ""));
				if ($(".jsPostalcode2").val() != "") {
					$(".jsCity2").val(result[1]);
				} else {
					$(".jsCity2").val("");
				}
			})
			.keydown(function(e){
				$('.jsPostalcode').unautocomplete();
				$(".jsCity").removeAttr("readonly").removeClass("disabled");
				return(isNumberKey(e));
			})
		;
	}
}

// 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,$(this).text(),"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);
		});
	});
}

// activate gzoom
/*function activateGzoom(){
	if ($('#productInfo').size() > 0){
		$('#imagePreviewList').find('.largeImage div').gzoom({
			sW: 298,
			sH: 170,
			lW: 1050,
			lH: 600, 
			lightbox: true,
			re: /large\//, 
  		replace: '',
			frameWidth: 0
		});
	}
}*/

// make an Ajax based submit of the newsletter subscription form
function newslettersubscribe(){
	$('.subscribenewsletterform').submit(function(){
		if (globals.validNewslettersubscribe){
			$.post('post.aspx',{
				Email: this.Email,
				_ReturnTo: this._ReturnTo,
				_Function: this._Function
			}, function(){
				if (typeof(window['youarenowsubscribedtext']) == "undefined"){
					var youarenowsubscribedtext = "Du er nu tilmeldt nyhedsbrevet";
				}
				$('.subscribenewsletterform :text').val('');
				alert(youarenowsubscribedtext);
			});
		}
		return false;
	});
}

// Show/hide alternative delivery form
function bindDelivery_form(){
	$("#alternative_address").click(function(){
		if(!$('.extended_delivery').hasClass("checkbox_show")){
			//do stuff if the checkbox is checked
			$('.extended_delivery').removeClass('checkbox_hide');
			$('.extended_delivery').addClass('checkbox_show');
		}
		else{
			//do stuff if the checkbox isn't checked
			$('.extended_delivery').removeClass('checkbox_show');
			$('.extended_delivery').addClass("checkbox_hide");
		}
	});
}

// Merge firstname & lastname to "Contact" when submitting
function bindDelivery_contact(){
	$('#form1').submit(function(e) {
		$('#contact').val($('#firstname').val() + ' ' + $('#lastname').val());
		$('#contact2').val($('#firstname2').val() + ' ' + $('#lastname2').val());
	});
}

// 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);

// productbar tab selection
function productbarTabs(){
	if ($('#productBar') > 0) {
			
		$('#productBar').siblings('.productShowbox').not(':first').hide();
		$('#productBar').find('div').click(function(){
			var divId = $(this).find('a').attr('id').replace('jsTab','');
			$('#'+divId).siblings('.productShowbox').hide().end().show();
			$(this).addClass('selected').removeClass('tab').siblings().removeClass('selected').addClass('tab');
			return false;
		});
	}
}

// Productinfo variants
String.prototype.endsWith = function(t) {
	return (t == this.substring(this.length - t.length));
}

function variantKontrol() {
	if ($('#useSizes').length > 0)
	{
		$('#stxrrelser').change(function(e){
			if ($('#productidVal').val().endsWith('-s') || $('#productidVal').val().endsWith('-m') || $('#productidVal').val().endsWith('-l') || $('#productidVal').val().endsWith('-xl'))
			{
				$('#productidVal').val($('#productidVal').val().replace(/-.*$/, ""));
				$('#productidVal').val($('#productidVal').val() + '-' + $('#stxrrelser').val());
			}
			else
			{
				$('#productidVal').val($('#productidVal').val() + '-' + $('#stxrrelser').val());
			}
		});
	}
}

/*function variantKontrol() {
	$('#basket').submit(function(e){
		if ($('#useSizes').length > 0)
		{
			if ($('#productidVal').endsWith('-s') || $('#productidVal').endsWith('-m') || $('#productidVal').endsWith('-l') || $('#productidVal').endsWith('-xl'))
			{
				$('#productidVal').val($('#productidVal').val().replace(/-.*$/, ""));
				$('#productidVal').val($('#productidVal').val() + '-' + $('#stxrrelser').val());
			}
			else
			{
				$('#productidVal').val($('#productidVal').val() + '-' + $('#stxrrelser').val());
			}
		}
	});
}*/

// if productvariants are available, find the input fields and activate Ajax implementation on them
/*
function variantSelection(){
	if ($('#productVariants').size() > 0){
		$('#productVariants').find(':input:not(:last)').change(function(){
			var $this = $(this);
			if ($this.val() != ''){
				
				var intIndex = $('#productVariants').find(':input').index(this);
				var nextBox = $('#productVariants').find(':input').eq(intIndex+1);
				var bolLast = false;
				if (intIndex = $('#productVariants').find(':input:not(:last)').size()) { bolLast = true; }
				
				nextBox.attr('disabled','disabled');
				
				$.get('/dynamic.aspx',{
					data: 'utilvariants',
					key: $('#productVariants').closest('form').find('input[name=original_productid]').val(),
					vars: $this.val(),
					last: bolLast,
					type: nextBox.attr('id').replace('variant','')
				},function(data){
					// find the body element  
					var startCut = data.indexOf('<body id=\'pageDynamic\'>')+23;
					var endCut = data.indexOf('</body>');
					
					var strContent = data.substring(startCut,endCut).split(',');
					var bolProductid = (data.indexOf('|') > -1);
					
					console.log(bolProductid);
					
					
					var strHtml = '<option value="">' + nextBox.find('option').eq(0).text() + '</option>';
					for(var i = 0; i<strContent.length;i++){
						if (bolProductid){
							var strProduct = strContent[i].split('|');
							strHtml += '<option value="' + strProduct[0] + '">' + strProduct[1] + '</option>';
						} else {
							strHtml += '<option value="' + nextBox.attr('id').replace('variant','') + '$' + strContent[i] + '">' + strContent[i] + '</option>';
						}
						
					}
					
					nextBox.html(strHtml);
					nextBox.removeAttr('disabled');
				});
			}
		});
		
		$('#productVariants').find(':input:last').change(function(){
			$this = $(this);
			if ($this.val() != ''){
				$('#productVariants').closest('form').find('input[name="productid"]').val($this.val());
			}
		});
		
		// insert Ajax content into the first box
		var thisBox = $('#productVariants').find(':input').eq(0);
		thisBox.attr('disabled','disabled');
		
		$.get('/dynamic.aspx',{
			data: 'utilvariants',
			key: $('#productVariants').closest('form').find('input[name=original_productid]').val(),
			type: $('#productVariants').find(':input:first').attr('id').replace('variant','')
		},function(data){
			// find the body element  
			var startCut = data.indexOf('<body id=\'pageDynamic\'>')+23;
			var endCut = data.indexOf('</body>');
			var strContent = data.substring(startCut,endCut).split(',');
			
			var strHtml = '<option value="">' + thisBox.find('option').eq(0).text() + '</option>';
			for(var i = 0; i<strContent.length;i++){
				strHtml += '<option value="' + thisBox.attr('id').replace('variant','') + '$' + strContent[i] + '">' + strContent[i] + '</option>';
			}
			
			thisBox.html(strHtml);
			thisBox.removeAttr('disabled');
		});
	}
}
*/

function variantSelection(){
	if ($('#productVariants').size() > 0){
		productVariantAjax();
		$('#productVariants').find(':input').change(productVariantAjax);
	}
}

function productVariantAjax(){
	var $this, noElement; 
	
	if (this.name){
  	$this = $(this);
		noElement = false;
  } else {
		$this = '';
		noElement = true;
	}
	
	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;
				}
			}
			
		// 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());
				var sidx = $('#productVariants').find(':input:last').get(0).selectedIndex - 1;
				$('#buycontrol_variant').val($('#_availNum option[value=' + sidx + ']').text());
			}
		} 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 {
				strVars = $this.val();
			}
					
			// make an Ajax call to retrieve data for the next box
			$.get('/dynamic.aspx',{
				data: 'utilvariants',
				key: $('#productVariants').closest('form').find('input[name=original_productid]').val(),
				type: objBox.attr('id').replace('variant',''),
				vars: strVars,
				last: bolLast
			},function(data){
				// find the body element  
				var startCut = data.indexOf('<body id=\'pageDynamic\'>')+23;
				var endCut = data.indexOf('</body>');
				
				var strContent = data.substring(startCut,endCut).split(',');
				var bolProductid = (data.indexOf('|') > -1);
				
				// Maks. salg (AS d.24/09-2009)     $('#buycontrol_variant').val();
				var strNumAvailable = strContent.slice(0);
				var numHTML = '<select id="_availNum" style="display:none;">';
				
				for (var c = 0; c<strNumAvailable.length;c++){
					strNumAvailable[c] = strNumAvailable[c].substring(strNumAvailable[c].indexOf('[')+1, strNumAvailable[c].indexOf(']'));
					strContent[c] = strContent[c].substring(0, strContent[c].indexOf('['));
					numHTML += '<option value="' + c + '">' + strNumAvailable[c] + '</option>';
				}
				
				numHTML += '</select>';
				
				$('#buyPlaceholder').after(numHTML).remove();
				if ($('#_availNum').length > 0)
				{
					$('#_availNum').after(numHTML).remove();
				}
				
				var strHtml = '<option value="">' + objBox.find('option').eq(0).text() + '</option>';
				
				for(var i = 0; i<strContent.length;i++){
					if (bolProductid){
						var strProduct = strContent[i].split('|');
						strHtml += '<option value="' + strProduct[0] + '">' + strProduct[1] + '</option>';
					} else {
						strHtml += '<option value="' + objBox.attr('id').replace('variant','') + '$' + strContent[i] + '">' + strContent[i] + '</option>';
					}
				}
				
				
				objBox.html(strHtml); // insert the options into the box
				objBox.removeAttr('disabled'); // enable the object again
				
				// end: Maks. salg
			});
		}
	}
}




// validate forms on submit and on input typing and blur
function formValidation(){

	// single field validation
	function validateField(evt){
		var $this = $(this), objForm = $this.closest('form'), strActivateKeyup = 'jsTextfieldactivatekeyup', bitOk = true, re;
		
		if (evt.type != "keyup" || $this.hasClass(strActivateKeyup)) {
			// if the input doesn't allow keyup events, activate it (this happens at first blur event)
			if (!$this.hasClass(strActivateKeyup)) {
				$this.addClass(strActivateKeyup);
			}
			
			// validate field
			
			/*
			 * Valideringen skal underst�tte f�lgende data, krav og afgr�nsninger:
			 *
			 * Fornavn og efternavn skal indeholde tekst.
			 * Gade skal indeholde et ord efterfulgt af et mellemum og et tal.
			 * postnummer skal vaere 4 tegn i Danmark.
			 * By bliver automatisk indsat efter postnummer.
			 * Telefon skal indeholde 8 tegn for dansk tlf.nummer.
			 * E-mail skal indeholde min. 1 tegn efterfulgt af et @ (snabel a) efterfulgt af min. 1 tegn efterfulgt af et . (punktum) efterfulgt af 2-4 karakterer.
			 *
			 *
			 * For at identificere de forskellige felttyper, skal hvert felt have en css klasse der fort�ller hvordan feltet skal valideres.
			 * Forslag til css klasser, der kan benyttes til validering samt beskrivelse af hvad de skal validere:
			 *
			 * jsValidate: bruges kun til at identificere hvilke felter der skal valideres.
			 * jsValidatetext: validerer om feltet ikke er tomt - dette skal vaere basis form for validering, alle andre valideringstyper goer automatisk dette
			 * jsValidatefullname: kontrollerer om der er minimum 2 ord i feltet
			 * jsValidatepostalcode: tester om postnummeret er korrekt i forhold til det enkelte lands krav
			 * jsValidatephone: Ser om telefonnummeret er indtastet korrekt i forhold til landets krav
			 * jsValidatemail: E-mail skal indeholde de paakraevede dele specificeret ovenfor
			 * jsValidateaddress: Korrekt indtastet adresse - efter ovenstaaende specifikation
			 * jsValidaterepeat: Tester om teksten i feltet er det samme som i feltet med det tilknyttede ID (i css klassen "jsValidaterepeatfromIDPAAFELT"
			 *
			 *
			 */
			// test if there is a required field for this input field
			var strCurrentName = $this.attr('name');
			var objRequiredField = $('input[name=_' + strCurrentName + '_required],input[name=' + strCurrentName + '_Required]', objForm);
			var bitRequired = (objRequiredField.size() > 0);
			
			if ($this.hasClass('jsValidatetext')) {
				re = /.+/;
			}
			else 
				if ($this.hasClass('jsValidatefullname')) {
					re = /.+\s.+/;
				}
				else 
					if ($this.hasClass('jsValidatepostalcode')) {
						// her boer man have forskellige landevalg, saa valideringen ved hvordan den skal validere? ligenu gaar den kun efter 4 cifre
						re = /^\d{4}$/;
					}
					else 
						if ($this.hasClass('jsValidatephone')) {
							// her boer man have forskellige landevalg, saa valideringen ved hvordan den skal validere? ligenu gaar den kun efter 8 cifre
							re = /^\d{8}$/;
						}
						else 
							if ($this.hasClass('jsValidatemail')) {
								re = /^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]+$/i;
							}
							else 
								if ($this.hasClass('jsValidateaddress')) {
									re = /^(.)+\s[1-9]/;
								}
								else {
									// hvis der ikke er nogen specifik validering, skal der alligevel valideres paa om der er indhold i feltet.
									re = /.+/;
								}
			
			bitOk = re.test($this.val());
			
			// hvis feltet er et repeat felt, f.eks. gentag password eller e-mail,
			// skal valideringen i stedet gaa paa om feltets indhold er det samme som det tilknyttede
			if ($this.hasClass('jsValidaterepeat')) {
				var strAllclasses = $this.attr('class').split(' '), strOriginalInputId;
				
				$.each(strAllclasses, function(i, val){
					if (val.indexOf('jsValidaterepeatfrom') > -1) {
						strOriginalInputId = val.replace('jsValidaterepeatfrom', '');
						
						return false;
					}
				});
				
				bitOk = ($this.val() == $('#' + strOriginalInputId).val() && $this.val != '');
			}
			
			// hvis et postalcode felt ikke indeholder tal mellem 1000 og 9999, skal der vises en fejl
			if ($this.hasClass('jsValidatepostalcode') && bitOk) {
				var intPostal = parseInt($this.val());
				if (intPostal < 1000 || intPostal > 9999){
					bitOk = false;
				}
			}
			
			
			if ((bitRequired && bitOk) || (!bitRequired && $this.val() != '' && bitOk)) {
				// hvis feltet er korrekt udfyldt
				$this.removeClass('textfield_error');
				$this.addClass('textfield_valid');
				
				$this.data('validatedOk', true);
			}
			else 
				if ((bitRequired && !bitOk) || (!bitRequired && $this.val() != '' && !bitOk) || (bitRequired && $this.val() == '')) {
					// hvis feltet ikke er udfyldt korrekt.
					$this.removeClass('textfield_valid');
					$this.addClass('textfield_error');
					
					$this.data('validatedOk', false);
				}
				else 
					if ($this.val() == '' && !bitRequired) {
						// hvis feltet ikke er udfyldt og det ikke er paakraevet
						$this.removeClass('textfield_error');
						$this.removeClass('textfield_valid');
						
						$this.data('validatedOk', true);
					}
					else {
					}
			
		}
	}
	
	
	$('form').each(function(){
		var objForm = this;
		$(objForm).data('allOk', '1');
		
		// select all fields that require a certain mask validation
		$('.jsValidate', objForm).bind('keyup blur', validateField);
		
		$(objForm).submit(function(){
			$(objForm).data('allOk', '1');
			var bitSendform = true;
			
			// Run a validation on all required fields
			$(':input[name*=_Required], :input[name*=_required]', this).each(function(){
				var relatedInput = $(':input[name=' + $(this).attr('name').replace(/_Required$/i, '').replace(/^_/, '') + ']', objForm);
				relatedInput.each(validateField)
			});
			
			// test if any active fields are not valid
			$(':input', this).not('[disabled]').each(function(){
				var $input = $(this);
				
				if ($input.data('validatedOk') == false) {
					bitSendform = false;
				}
			});
			
			// ###### Saml firstname og lastname til "kontakt", saa systemet er glad 
			if ($('#contact').length != 0)
			{
				$('#contact').val($('#firstname').val() + ' ' + $('#lastname').val());
				$('#contact2').val($('#firstname2').val() + ' ' + $('#lastname2').val());
			}
			
			if (!bitSendform) {
				$(objForm).data('allOk', '0');
				
				var strAlert = 'Du skal udfylde alle felter med * med korrekt data';
				alert(strAlert);
				return false;
			}
		});
		
	});
}
