/*
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;
}

function getQuerystring(key, default_)
{
	if (default_==null) {
		default_="";
	}
	key = key.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
	var regex = new RegExp("[\\?&]"+key+"=([^&#]*)");
	var qs = regex.exec(window.location.href);
	if(qs == null) {
		return default_;
	} else {
		return qs[1];
	}
}

/*
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.jfeed.js');

/*
ON LOAD
*********************************************/
// jQuery 'onReady' script - runs when the document have been loaded, but before images
$(function(){
	validateForms();
	toggleMainMenu();
	toggleAreaMenu();
	activateAjaxShopping();
	autocompletePostalCode();
	productlistImage();
	postPolls();
	quizWizzard();
	tracktrace();
	feedReader();
	changeProductImage();
	SendShoppingList();
	ClosePopups();
	ActivateShoppingListFunctions();
	ActivateShoppingListSelection();
});


/*
MENU
**********************************************/
// insert a style-tag, which hides the menu lists before they are shown
$('<style type="text/css">#mainMenu ul ul, #areaMenu ul ul { 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().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
**********************************************/
// 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
	$('#productinfo form, .jsAjaxBasket, .productlist table form.addToBasket').submit(function(){
		log_debug('GO!');
		$.post("post.aspx",{
				_Function: this._Function.value,
				_ReturnTo: 'dynamic.aspx?data=basketstatus',
				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'
					$('#tBasketStatus').replaceWith($(data.substring(startCut,endCut)));
log_debug($(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;
	});
}

/* Festival: Shoppinglists
 * ei@e-supplies.dk
************************************************/

function updateShoppingList(pkid, action) {
	if (action == 'add') {
		$('.jsAdd' + pkid).hide();
		$('.jsRemove' + pkid).show();
		$('form#jsFavourite' + pkid).ajaxSubmit();
	} else {
		$('.jsAdd' + pkid).show();
		$('.jsRemove' + pkid).hide();
		$('form#jsRemove' + pkid).ajaxSubmit();
	}
	return false;
}

function ShoppingListSender(pos) {
	$('.jsListSender').hide('fast');
	$('.jsListSender').show('slow');
	//$('.jsListSender_' + pos).show('slow');
}
 function SendShoppingList() {
	$('.jsListSender form').submit(function(){
		$(this).parent().find('.jsListFeedback').fadeIn('slow');
		$(this).ajaxSubmit();
		return false;
	});
 }
 function ClosePopups() {
	$(".jsCloseSend").click(function(){
		$('.jsListSender').hide('fast');
	});
	$(".jsCloseEdit").click(function(){
		$('.jsListDescription').hide('fast');
	});
 }
 
 function ActivateShoppingListFunctions() {
	$('.jsDeleteshoppinglist').click(
		function(){
			var $this = $(this);
			$.get(
				"dynamic.aspx",
				{
					data:'DeleteShoppingList',
					key:$this.parent().parent().find('.jsActiveShoppingList').val()
			},
				function(data) {
					location.href="/default.aspx?load=main&data=shoppinglist";
				},
				'html'
			);
	});
	
	$('.jsSelectalllists').click(function(){
		$('.jsMarkshoppinglist').attr('checked',true);
	});
	
	$('.jsRemovemarks').click(function(){
		$('.jsMarkshoppinglist').attr('checked',false);
	});
	
	$('.jsDeletemarked').click(function(){
		$('input:checked.jsMarkshoppinglist').each(function(i) {
			var $this = $(this);
			$this.data('ajaxing','1');	
			$.get(
				"dynamic.aspx",
				{
					data:'DeleteShoppingList',
					pkid:$this.val()
				},
				function(data) {		
					$this.data('ajaxing','0');
					var bitReload = true;
					$('input:checked.jsDelete').each(function(i){
						if ($(this).data('ajaxing') == '1'){
							bitReload = false;
							return false;
						}
					});
					
					if (bitReload){
						window.location.reload();
					}
					
				},
				'html'
			);
		});
	});
	
	$('.jsPrint').click(function(){
		window.open('dynamic.aspx?Data=Shoppinglist&printmode=1&key=' + getQuerystring('key'),'print','scrollbars=yes,left=200,top=200,width=600,height=600');
	});
	
	$('.jsMarkedtobasket').click(function(){
		$('input.jsMarkshoppinglist').each(function(i) {
			var $this = $(this);
			if ($this.attr('checked') == true) {
				$('#postQuantity' + $this.val()).val($('#listQuantity' + $this.val()).val());
			} else {
				$('#postQuantity' + $this.val()).val('');
			}
		});
		$('#jsAddshoppinglist').submit();
	});
	
	$('.jsChangeshoppinglistname').click(function(){
		var pkid = $(this).parent().parent().find('.jsActiveShoppingListId').val();
		$('.jsListDescription_' + pkid).show('fast');
		$('.jsListDescription_' + pkid + ' form').submit(function(){
			$(this).ajaxSubmit({
				success:reloadChangedList($(this))
			});
			return false;
		});
	});
}
function reloadChangedList($this) {
	var returnString;
	var key = getQuerystring('key');
	var newKey = $this.find('.listName:first').val();
	
	if(newKey == '' || newKey == key) {
		returnString = window.location.href;
	} else {
		returnString = '/default.aspx?load=main&data=shoppinglist&key=' + newKey;
	}
	if(key == '') {
		returnString = window.location.href;
	}
	setTimeout('window.location.href = "' + returnString + '"', 500);
}
function ActivateShoppingListSelection() {
	$('#activeShoppinglist').change(function(){
		$.get(
			"dynamic.aspx",
			{
				data:'SelectShoppingList',
				List:$(this).val()
			}/*,
			function(data) {
				window.location.reload();
			},
			'html'*/
		);
	});
	$('.jsAddtolist').click(function(){
		var $this = $(this);
		if ($('#activeShoppinglist').size() < 1) {
			$.post(
				"post.aspx",
				{
					_function:'UPDATESHOPPINGLIST',
					productid:$this.closest('table').find('input[name="productid"]:first').val(),
					quantity:$this.closest('table').find('input[name="quantity"]:first').val(),
					name:'NEW_LIST',
					NEW_LIST:'Standard'
				},
				function(data) { },
				'html'
			);
		} else {
			$.post(
				"post.aspx",
				{
					_function:'UPDATESHOPPINGLIST',
					productid:$this.closest('table').find('input[name="productid"]:first').val(),
					quantity:$this.closest('table').find('input[name="quantity"]:first').val(),
					name:$('#activeShoppinglist:first').val()
				},
				function(data) { },
				'html'
			);
		}
	});
}
