/*
		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  
*/

/*
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;
}

/*
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(){
	// 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)));
			},'html');
			
			// cancel the normal form submit
			return false;
		});
	});
	
	// add products to basket and update basketpreview
	$('#jsProducttobasket, .productlist table form.addToBasket').submit(function(){
		
		// cancel the Ajax call, if some values are missing
		if(this.productid.value == '' || this.quantity.value == ''){
			modalAlert('Udfyld alle nødvendige felter'); // #### skal have sprogversionering på
			return false;
		}
		
		// cancel the Ajax call, if the quantity is less than minimum quantity
		if (parseInt(this.min_quantity.value) > parseInt(this.quantity.value)){
			modalAlert('Du skal bestille minimum ' + this.min_quantity.value + ' stk.'); // #### skal have sprogversionering på
			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');
			
		
		// 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", {
				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);
		});
	});
}

// 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;
	}
	
	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());
			}
		} 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);
				
				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
			});
		}
	}
}

// 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;
		});
	}
}