/*
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;
}

/*
INCLUDES
**********************************************/
// specify which javascripts to include on the webpage

/*
ON LOAD
*********************************************/
// jQuery 'onReady' script - runs when the document have been loaded, but before images
$(function(){
	validateForms();
});


/*
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, .productlist table form.addToBasket').submit(function(){
		$.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').submit(function(e,i){
		var ok = true;
		// select all 'required' fields inside the current form (indicated by the 'i')
		$('input:hidden[name*=Required]',i).each(function(){
			// find the related input for the required field
			var relatedInput = $(':input[name=' + $(this).attr('name').replace(/_Required$/i,'').replace(/^_/,'') + ']');
			if (relatedInput.val() == ''){ // if the input is empty, add a 'notValid' class on it
				ok = false;
				relatedInput.addClass('notValid');
				
				// 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');
				
				// 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]',i).each(function(){
			// find the related input for the required field
			var relatedInput = $('input[name=' + $(this).attr('name').replace(/_IsEmail$/i,'').replace(/^_/,'') + ']');
			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');
				
				// 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]').length > 0){
				alert($('input[name=contactvalidation]').val());
	  	} else {
				alert('Felter med stjerne ud for, skal udfyldes');
			}
			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();
	});
}

