function js(f) {
  document.write('<script type="text/javascript" src="'+ f + '"></s' + 'cript>'); 
}

js('/files/javascript/jquery.simplemodal-1.3.min.js');
js('/files/javascript/jquery.hoverIntent.minified.js');
js('/files/javascript/jquery.maskedinput-1.2.2.min.js');
js('/files/javascript/jquery.blockUI.js');
js('/files/swfobject.js');


$(function(){
	ajaxPromotionlist();
	activateAjaxShopping();
	toggleAreaMenu();
	errorInPaymentPopup();
	$(".deliverysingle").change(function()
	{
		if($(".deliverysingle").size() > 1)
		{
			var ret = confirm(unescape("%D8") + "nsker du at bruge denne dato for alle leveringer?");
			if(ret)
				$(".deliverysingle").val($(this).val());
		}
	});
	
	productlistImageZoom();
	
	// Lock basket while updating prices and routes
	LockAndUpdate();
	
	// activate the main menu and add some padding correctly
	toggleMainMenu();
	
	var intMenupunkter;
	var intSamletbredde;
	var intSpildplads;
	var intPadding;
	var intMaxPadding;
	
	// Fix topmenu
	intMenupunkter = $("#mainMenu>ul>li").size();
	intSamletbredde = 0;
	intMaxPadding = 170;
	
	$("#mainMenu>ul>li>a").css({paddingLeft:"0", paddingRight:"0"})
		.each(function(){
			intSamletbredde += $(this).width()
		});
		
	
	intSpildplads = $("#mainMenu>ul").width() - intSamletbredde;
	
	intPadding = Math.floor(intSpildplads / intMenupunkter);
	
	if (intPadding < 0) {intPadding = 0};
	
	if (intPadding > intMaxPadding) {intPadding = intMaxPadding};
	
	
	$("#mainMenu>ul>li>a").each(function(){
		$(this).css({
			width: ($(this).width() + (intPadding-14)) + "px",
			paddingLeft: '14px'
		});
	});
	// Fix topmenu
	
	$('.jsMaskPostalcode').mask('9999',{placeholder:' '});
	$('.jsMaskPhone').mask('99999999',{placeholder:' '});
});

// on document load - when the entire page has been loaded - incl. images 
$(window).load(function(){
	ajaxPaging();
});


function returntobasket(whichLayer)
{
	if (document.getElementById)
	{
		// this is the way the standards work
		document.getElementById(whichLayer).value = 'default.aspx?data=basket&template=basket&load=main';
	}
	else if (document.all)
	{
		// this is the way old msie versions work
		document.all[whichLayer].value = 'default.aspx?data=basket&template=basket&load=main';
	}
	else if (document.layers)
	{
		// this is the way nn4 works
		var style2 = document.layers[whichLayer].value = 'default.aspx?data=basket&template=basket&load=main';
	}
}

function LockAndUpdate() {
	$('.deliverysingle').change(function() {
		$.blockUI();
		returntobasket('returnto');
		$('#subscriptionForm').trigger('submit');
		//$('body').append('<div class="lockedcurtain"><img src="/images/green-loader.gif" alt="Loading" class="lockedloader" /></div>');
		$('body').append('<div class="lockedcurtain"><img src="/images/green-loader.gif" alt="Loading" class="lockedloader" /></div>');
	});
}

function productlistImageZoom() {
	
	// zoom images on productlist
	$('#splitmid').find('.prodImg').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'
		}).appendTo('body');
	}).bind('mouseleave',function(){
		$('#prodImgBig').remove();
	});
	
}


/*
MENU
**********************************************/
// insert a style-tag, which hides the menu lists before they are shown
//$('<style type="text/css">#groupsmenu ul.closed { display: none; }</style>').appendTo('head');
$('<style type="text/css">#mainMenu ul ul, #groupsmenu 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(){
	$('#groupsmenu 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;
	})
	$('#groupsmenu li ul.closed').prev().addClass('closed');
	$('#groupsmenu li ul.open').prev().addClass('open');
}



// 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);
		}
	}
}


// 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);
}

// append ajax shopping and updating of previewbasket 
function activateAjaxShopping(){
	// remove products from basket and update basket preview
	$('#splitRight').find('.framebasketstatus input').live('click',function(){
		$(this).closest('form').submit(function(){
			$.post("post.aspx",{
				_Function: this._Function.value,
				_ReturnTo: 'dynamic.aspx?data=simplebasketpreview&template=basketstatus',
				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'
				$('#splitRight').find('.framebasketstatus>table').replaceWith($(data.substring(startCut,endCut)));
			},'html');
			
			// cancel the normal form submit
			return false;
		});
	});
	
	addProductstobasket();
	
}

function addProductstobasket(){
	// add products to basket and update basketpreview
	$('#splitmid').find('.jsProducttobasket').not('.ajaxed').submit(function(){
		
		// cancel the Ajax call, if some values are missing
		if(this.productid.value == '' || this.quantity.value == ''){
			alert('Udfyld alle n\u00D8dvendige felter'); // #### skal have sprogversionering paa
			return false;
		}
		
		// cancel the Ajax call, if the quantity is less than minimum quantity
		if (this.min_quantity){
			if (parseInt(this.min_quantity.value) > parseInt(this.quantity.value)){
				alert('Du skal bestille minimum ' + this.min_quantity.value + ' stk.'); // #### skal have sprogversionering paa
				return false;
			}
		}
		
		// add a class to mark the form activated
		$(this).addClass('ajaxed');
		
		$.post("post.aspx",{
				_Function: this._Function.value,
				_ReturnTo: 'dynamic.aspx?data=simplebasketpreview&template=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'
					$('.framebasketstatus>table').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;
	});
}


function ajaxPaging(){
	if ($('#splitmid').find('.jsPaging a').size() > 0){
		
		$('#splitmid').find('.framemain').wrapInner('<div id="jsCurpage1" style="position: absolute; left: 0; top: 0;" />').wrapInner('<div id="jsFramemaintrack" style="position: absolute; top: 0; left: 0;"/>').wrapInner('<div id="jsFramemain" />');
		
		$('#jsFramemain').css({
			position: 'relative',
			width: $('#jsCurpage1').width() + 'px',
			height: $('#jsCurpage1').height() + 'px',
			overflow: 'hidden'
		});
		
		$('#splitmid').find('.jsPaging a').live('click',function(){
			// make a new url
			var strUrl = this.href;
			var strDynamicurl = strUrl.replace('default.aspx','dynamic.aspx').replace('&load=main','');
			var objCurPage = strUrl.match(/curpage=(\d+)/);
			
			var intCurpage = 0;
			if (objCurPage){
				intCurpage = objCurPage[1];
			}
			
			if ($('#jsCurpage' + intCurpage).size() > 0){ // the page already exists
				$('#jsFramemaintrack').animate({
					left: ($('#jsCurpage' + intCurpage).position().left * -1) + 'px'
				},'slow');
			} else { // the page did not exist 
				// make the Ajax call
				$.get(strDynamicurl,function(data){
					// find the body element  
					var startCut = data.indexOf('<body');
					var endCut = data.indexOf('</body>') + 7;
					
					$('#jsFramemaintrack').append('<div id="jsCurpage' + intCurpage + '" style="float: left;"/>');
					
					$('#jsCurpage' + intCurpage).css({
						position: 'absolute',
						left: ($('#jsCurpage1').width() * (intCurpage-1)) + 'px',
						top: 0
					}).html($(data.substring(startCut,endCut)));
					
					addProductstobasket();
					
					$('#jsFramemaintrack').animate({
						left: ($('#jsCurpage' + intCurpage).position().left * -1) + 'px'
					},'slow');
				
					productlistImageZoom();
					
				});
			}
			
			// cancel the normal click event
			return false;
		});
	
	}
}

function ajaxPromotionlist(){
	var strUrl = window.location.href;
	
	var objDataformat = strUrl.match(/data=(\w+)/i);
	var strDataformat = "";
	if (objDataformat){ strDataformat = objDataformat[1]; }
	
	var objKey = strUrl.match(/key=(\w+)/i);
	var strKey = "";
	if (objKey){ strKey = objKey[1]; }
	
	var objGroup = strUrl.match(/group=(\w+)/i);
	var strGroup = "";
	if (objGroup){ strGroup = objGroup[1]; }
	
	var promotionlistUrl = '/dynamic.aspx?data=promotionlist&template=soeg&dataformat=' + strDataformat + '&key=' + strKey + '&group=' + strGroup;
	
	$.get(promotionlistUrl,function(data){
		var startCut = data.indexOf('<body');
		var endCut = data.indexOf('</body>') + 7;
		
		$('#splitRight').find('.framesearch>table').replaceWith($(data.substring(startCut,endCut)));
		promotionlistSWFObject();
	})
	
}

