var root = 'http://' + $.url.attr('host') + $.url.attr('directory'),
	file = $.url.attr("file");
	
var basket = new Basket();

var packingBox = null;
var campaignObject = null;

$(document).ready(function(){
	var root = 'http://' + $.url.attr('host') + $.url.attr('directory'),
		file = $.url.attr("file");
		
	if(BrowserDetect.browser=='Explorer' && BrowserDetect.version==6){

		$('#menu-category li.parent ul').css(
			{
				display: 'block',
				listStyle: 'none',
				listStylePosition: 'outside',
				listStyleImage: 'none',
				marginLeft: '4px',
				width: '132px'
			}
		);
		$('#menu-category li.selected ul').css(
			{
				display: 'block',
				listStyle: 'none',
				listStylePosition: 'outside',
				listStyleImage: 'none',
				marginLeft: '4px',
				width: '132px'
			}
		);
	}
	
	if (file != 'basket.php' && file != 'securetunnel.asp' && $('#welcome-ibob').size() > 0) {
		var ibobModal = $('#welcome-ibob');
		var height = 330;
		var width = 479;
		
		$(ibobModal).css({
			width: width + "px", 
			height: height + "px", 
			marginTop: "-" + (height/2) + "px",
			marginLeft: "-" + (width/2) + "px"
			});
		
		$(ibobModal).before("<div id=\"welcome-overlay\" class=\"modal-overlay\"></div>");
		$(ibobModal).addClass("modal-window");
		$(ibobModal).show();
		
		$(ibobModal).add($('.close-button', ibobModal)).click(function(){ closeModal(); });

		setTimeout(function() {
			if ($('#welcome-overlay').size() > 0) {
				closeModal();
			}
		}, 7000 );
	}
	
	// Packing Infobox
		
	var clockUpdateFunction = function(){
	
		var currentTime    = new Date(),
			currentHours   = currentTime.getHours(),
			currentMinutes = currentTime.getMinutes(),
			currentSeconds = currentTime.getSeconds();
		
		remainingHours   = 20 - currentHours;
		remainingMinutes = 59 - currentMinutes;
		remainingSeconds = 59 - currentSeconds;
		
		remainingHours   = ( remainingHours   < 10 ? "0" : "" ) + remainingHours;
		remainingMinutes = ( remainingMinutes < 10 ? "0" : "" ) + remainingMinutes;
		remainingSeconds = ( remainingSeconds < 10 ? "0" : "" ) + remainingSeconds;
		
		$('#packing-infobox #hours').html(remainingHours);
		$('#packing-infobox #minutes').html(remainingMinutes);
		$('#packing-infobox #seconds').html(remainingSeconds);
	};
	
	clockUpdateFunction();
	
	packingBox = new PackingInfoBox('#packing-infobox', function(){
		setInterval(clockUpdateFunction, 1000);
	});
	
	if ($.url.attr("file") == "index.php" || $.url.attr("file") == null) {
		$('#front-colorbob').mouseenter(function(){
			$(this).attr('src', root + 'resources/gfx/front-colorbob-hover.jpg')
		}).mouseout(function(){
			$(this).attr('src', root + 'resources/gfx/front-colorbob.jpg')
		});
		$('#front-filmbob').mouseenter(function(){
			$(this).attr('src', root + 'resources/gfx/front-filmbob-hover.jpg')
		}).mouseout(function(){
			$(this).attr('src', root + 'resources/gfx/front-filmbob.jpg')
		});
		$('#front-officebob').mouseenter(function(){
			$(this).attr('src', root + 'resources/gfx/front-officebob-hover.jpg')
		}).mouseout(function(){
			$(this).attr('src', root + 'resources/gfx/front-officebob.jpg')
		});
	}
	
	if ($.url.attr("file") == "basket.php" || $.url.attr("file") == "index.php" || $.url.attr("file") == null){
		packingBox
			.setDelay(1000)
			.setTtl(60000)
			.setEaseInAnim({top:'+=47'})
			.setEaseOutAnim({top:'-=47'})
			//.setOffDays(1,6,0)
			//.setFromTime('05:00') // default is 17:00
			.start();
	} else {
		packingBox
			.setDelay(2000)
			.setTtl(30000)
			.setEaseInAnim({top:'+=47'})
			.setEaseOutAnim({top:'-=47'})
			.start();
	}
		
	// Search
	$('#q').focus(function(event){
		var q = $(this).val();
		$(this).css('color','#dea501');
		if(q == 'Indtast søgeord...'){
			$(this).val('');
		}
	}).blur(function(event){
		var q = $(this).val();
		if(q == ''){
			$(this).css('color','#898a89');
		}
	});
	
	// Enable menu roll over function
	$('li .nav').mouseover(function(event){
		$(this).toggleClass('sfhover');
	}).mouseout(function(event){
		$(this).toggleClass('sfhover');
	});

	// Activate product effects
	$("#products").ready(function(){
		$(".product").each(function(i){
			var id = $(this).attr("id");
			if ($(this).hasClass("productshort")) {
				activateShowMore(this);
				activatePreloadImage(this);
				insertThumbnail(this);
			} else if ($(this).hasClass("productlong")){
				activateShowLess(this);
				activateProductThumbnails(this);
				activateProductZoom(this);
				activatePlayer(this);
			}
			activateCommonProductButtons(this);
		});
	});
	
	// Lazyload images
	//$("img").lazyload({ threshold: 200, effect: "fadeIn"});
	
	// Activate basket effects
	
	var elSmallbasket = $("#smallbasket");
	activateAddOne(elSmallbasket);
	activateRemoveOne(elSmallbasket);
	
	$('#smallbasket .description a').live('click', function(event){
		var src = $(this).attr('href'),
		    src_hash = src.split('#'),
		    id = src_hash[1],
		    product_query = "#" + id,
		    productElement = $(product_query);
		
		if (productElement.size() > 0) {
			// HACK to overcome bug with TNTs having same id's as products.
			if ($(productElement).hasClass('tnt')) {
				productElement = $('div[id=' + id + ']').eq(1);
			}
			
			$.scrollTo(productElement, 1000, { offset: { top:-100} });
			if ($(productElement).hasClass('productshort')) {
				$(productElement).find('.details').eq(0).click();
			}
			event.preventDefault();
		}
	});
	
	// Add scrollfollow ability to right float and to product category menu
	
	if($(".scrollfollow")){$(".scrollfollow").eq(0).wrapInner('<div id="rightfloat">');}
	$("#menu-category-container").add("#rightfloat").each(function(){
		$(this).scrollFollow({
			offset: 20,
			easing: "easeOutCubic"
		});	
	});	
	
	// Enable action mail
	
	if (false && $.url.attr("file") == "basket.php"){
		$(":input[name=lemail]").change(function(){
			var email = $(this).val();
			var url = root + "funktioner/ajax.mc.php";
			$.get(url, {
				sid: Math.random(),
				e: email
			}, function(){} );
		});
	}
	
	if ($.url.attr("file") == "basket.php"){
		
		// Kundetype
		
		$('#kundetype-privat').add('#kundetype-erhverv').click(function(event){
			if ($(event.target).val() == 'privat'){
				$('#info-form').attr('action', root + 'basket.php?u=p#recipient');
			} else {
				$('#info-form').attr('action', root + 'basket.php?u=b#recipient');
			}
			$('#info-form').submit();
		});
		
		
		// GLS delivery options
		
		if ( $('#lgade1').val() != '' && $('#lzip').val() != '') {
			updateGLSoption();
		}
		$('#lname').change(function(e){ $('#delivery-option-door .address .name strong').text($(e.target).val()); });		
		$('#lzip').change(function(e){ 
			$('#delivery-option-door .address .zipcode').text($(e.target).val()); 
			$('#delivery-option-door .address .city').text($('#lcity').val());
		});
		
		$('#lcity').change(function(e){ $('#delivery-option-door .address .city').text($(e.target).val()); });
		$('#lgade1').change(function(e){ $('#delivery-option-door .address .street').text($(e.target).val()); });
		
		$('#lzip').add('#lgade1').change(function(){
			updateGLSoption();
		});
	}
});

//var intervalId = 0;
$(window).bind("load", function() { 
    //intervalId = setInterval("lazyLoadProducts()", 5000);
	if ($.url.attr("file") == "kontorartikler.php" && $.url.attr("anchor")){
		$.scrollTo(".brands div#"+$.url.attr("anchor"), 1000, { offset: { top:-100} });
	}
}); 

/*var $products = null;
function lazyLoadProducts() {
	if ($products == null) {
		$products = $(".product:hidden").reverseOrder();
	}
	$($products).filter(":hidden").slice(0,15).each(function(i){
		var id = $(this).attr("id");
		showSimple(id, function(){
			insertThumbnail(this);
			$("img", this).lazyload({ threshold: 200, effect: "fadeIn"});
		});
	});
}*/

function insertThumbnail(elProduct){
	var elImg = $(".productillustration img[loaded=0]", elProduct).eq(0);
	if (elImg) {
		$(elImg).attr({src: "/kontorartikler/productimages/" + $(elProduct).attr("pcode") + "-1_81x72.jpg"});
	}
	
	// if(hasProductPhoto == '2'){
	// 	var productPhotoUrl = $("#productphotourl",elProduct).val();
	// 	$(".productillustration img", elProduct).attr({src: productPhotoUrl});
	// }
}

function activateProductThumbnails(elProduct) {
	$('.thumbs img', elProduct).each(function(){
		var newSrc = stripThumb($(this).attr('src'));
		$.preloadImages(newSrc);
	});
	$('.thumbs img', elProduct).mouseover(function(event){
		var mainImg = $(elProduct).find('.productillustration img').eq(1);
		var newSrc = stripThumb($(this).attr('src'));
		$(mainImg).attr({src: newSrc});
		$(mainImg).load(function(){
			//$(mainImg).hide();
			//$(mainImg).fadeIn('fast');
			
		});
	});
	// $('.thumbs img', elProduct).click(function(event){
	// 	var mainImg = $(elProduct).find('.productillustration img').eq(0);
	// 	var newSrc = stripThumb($(this).attr('src'));
	// 	$(mainImg).attr({src: newSrc});
	// 	$(mainImg).load(function(){
	// 		$(mainImg).hide();
	// 		$(mainImg).fadeIn('fast');
	// 	});
	// });
}

function stripThumb(path, dimensions) {
	var parts = path.split('_'),
		dimString = '_200x177.';
		
	if (arguments.length == 2) {
		dimString = "_" + dimensions + '.';
	}
	if (parts.length == 2) {
		var sub_parts = parts[1].split('.');
		return parts[0] + dimString + sub_parts[1];
	}
	return path;
}

function activateShowLess(elProduct) {
	var root = 'http://' + $.url.attr('host') + "/"; //$.url.attr('directory');
	$(elProduct).find("a[class=details]").each(function(i){
		var type = $(this).attr('type');
		$(this).unbind("click");
		$(this).click(function(event){
			event.preventDefault();
			$(event.target).parents().eq(0).blur();
			var prd =  $(event.target).parents(".product").eq(0);
			var id = $(prd).attr("id");
			$(prd).find(".productinfo a.details img").attr("src", root + "resources/gfx/ajax-loader.gif");
			$(prd).find("a.details").parents('div').eq(0).css('textAlign', 'center');
			showSimple(id, type);
		});
	});
}

function activateShowMore(elProduct){
	var root = 'http://' + $.url.attr('host') + "/", // + $.url.attr('directory'),
		file = $.url.attr("file");
	
	if (file == 'soeg.php' || file == 'genkoeb.php') {
		return ;
	}
	$(elProduct).find('a[class=details]').each(function(i){
		var type = $(this).attr('type');
		$(this).unbind("click");
		$(this).click(function(event){
			event.preventDefault();
			$(event.target).parents().eq(0).blur();
			var prd =  $(event.target).parents(".product").eq(0);
			var id = $(prd).attr("id");
			$(prd).find(".productinfo a.details img").attr("src", root + "resources/gfx/ajax-loader.gif");
			$(prd).find("a.details").parents('div').eq(0).css('textAlign', 'center');
			showDetailed(id, type);
		});
	});
}

function activateCommonProductButtons(elProduct){
	activateBuyButton(elProduct);
	activateChangeOneUp($(elProduct).find(".addbutton"));
	activateChangeOneDown($(elProduct).find(".subbutton"));
	$(elProduct).find("input[name=number]").change(function(event){
		$(event.target).parents(".product").attr({number: $(this).val()});
	});
	activatePriceUpdate("change", $(elProduct).find("input[name=number]"), elProduct);
	activatePriceUpdate("click", $(elProduct).find(".addbutton"), elProduct);
	activatePriceUpdate("click", $(elProduct).find(".subbutton"), elProduct);
}

function activateBuyButton(elProduct){
	$(".buybutton", elProduct).click(function(event){
		event.preventDefault();
		var id = $(elProduct).attr("id"),
			number = null;
		// TODO use the hidden input[name=productid]
		if ($(elProduct).hasClass('filmtnt')) {
			number = 1;
			id = id.substring(7);
		} else {
			number = $(elProduct).find("input[name=number]").val();
		}
		if ($(elProduct).hasClass('tnt')) {
			id = id.substring(3);
		}
		basket.add(id, number, function(updatedBasket){
			updateBasket($("#smallbasket"), updatedBasket, id);
			$('.productillustration img', elProduct).eq(0).effect('transfer', { to: '#item' + id, className:'transfer' + id }, 500);
		});	
	});
}
// Will increase number element by one
function activateChangeOneUp(button){
	$(button).unbind("click");
	$(button).click(function(event){
		var elNumber = $(event.target).parents(".product").find("input[name=number]");
		var newVal = parseInt($(elNumber).val(), 10) + 1;
		$(elNumber).val(newVal);
		animateValueChange(elNumber);
		$(event.target).parents(".product").attr({number: newVal});
		priceUpdate($(event.target).parents(".product"));
	});
}
// Will reduce number element by one
function activateChangeOneDown(button){
	$(button).unbind("click");
	$(button).click(function(event){
		var elNumber = $(event.target).parents(".product").find("input[name=number]");
		var newVal = parseInt($(elNumber).val(), 10) - 1;
		if (newVal < 1) {
			$(elNumber).val(1);
		} else {
			$(elNumber).val(newVal);
		}
		animateValueChange(elNumber);
		$(event.target).parents(".product").attr({number: newVal});
		priceUpdate($(event.target).parents(".product"));
	});
}
// Will change the displayed price
function activatePriceUpdate(eventName, element, elProduct) {
	$(element).bind(eventName, function(event){
		priceUpdate($(event.target).parents(".product"));
	});
}

function priceUpdate(elProduct) {
	
	var tiers        = $(".priceTiersJson", elProduct).text(),
		number       = parseInt($(elProduct).find("input[name=number]").val(), 10),
		elBigPrice   = $("#price" + $(elProduct).attr("id"), elProduct),
		elSmallPrice = $("#priceExVat" + $(elProduct).attr("id"), elProduct),
		vatMode      = $('#shopVatMode').text(),
		oldPrice     = $(elBigPrice).text();
	
	// Eval tiers
	
	tiers = eval(tiers);
	
	// If there are not tiers return
	
	if (typeof(tiers) == 'undefined') {
		return;
	}
	
	// Find matching tier
	
	var matchingTier = null;
	
	for (var i = 0; i < tiers.length; i++) {
		var tier = tiers[i],
			from = tier[4],
			to   = tier[5];
		
		if (parseInt(from, 10) <= number && (to == '*' || number <= parseInt(to, 10))) {
			matchingTier = tier;
			break;
		}
	};
	
	var newPrice = formatPrice(matchingTier[1]),
		newPriceExVat = formatPrice(matchingTier[3]);
	
	if (context.forceVat == 'incl') {
		elBigPrice.text(newPrice);
		elSmallPrice.text(newPriceExVat + ")");
	} else if (context.forceVat == 'excl') {
		elBigPrice.text(newPriceExVat);
		elSmallPrice.text(newPrice + ")");
	} else {
		if (context.universe == 'business') {
			elBigPrice.text(newPriceExVat);
			elSmallPrice.text(newPrice + ")");
		} else {
			elBigPrice.text(newPrice);
			elSmallPrice.text(newPriceExVat + ")");
		}
	}
	
	if (newPrice != oldPrice && !(oldPrice == null || oldPrice == "")) {
		animateValueChange(elBigPrice);
		animateValueChange(elSmallPrice);
	}
}

function activateAddOne(elBasket){
	$(".add", elBasket).each(function(i){
		$(this).click(function(event){
			event.preventDefault();
			var elId = $(this).prev().prev();
			var id = $(elId).val();
			basket.add(id, 1, function(updatedBasket){
				updateBasket($(elBasket), updatedBasket, id);
			});
		});
		
	});
}
function activateRemoveOne(elBasket){
	$(".sub", elBasket).each(function(i){
			$(this).click(function(event){
			event.preventDefault();
			var elId = $(this).prev();
			var id = $(elId).val();
			basket.remove(id, 1, function(updatedBasket){
				updateBasket(elBasket, updatedBasket, id);
			});
		});
	});
}
// Will preload the big product picture when hovering the product
// FIXME the img urls has changed
function activatePreloadImage(elProduct){
	var config = {
		    sensitivity: 1,
			interval: 100,
			over: function(){
				var elImg = $(".productillustration img", elProduct);
				if (elImg.attr("src") && elImg.attr("state") != 'preload') {
					$.preloadImages($(elImg).attr("src").replace("_81x72", "_200x177"));
					$(elImg).attr({state:'preload'});
				}	
			}, 
			timeout: 100, 
			out: function(){} 
	};
	$(elProduct).hoverIntent(config);
}

function updateBasket(elBasket, updatedBasket, id){
	$('.content', elBasket).html(updatedBasket);
	elBasket = $('#smallbasket');

	if(BrowserDetect.browser!='Explorer'){ // TODO remove this condition when bug fixed in jQuery 1.4.2
		if ($("input[value=" + id + "]", elBasket).size()) {
			$("input[value=" + id + "]", elBasket).parents('.basketline').stop().effect("highlight", {}, 3000);
		}
	}

	var total = $('.totalline .total', elBasket).text();
	if(total.length != 0){
		$('#totalflash', elBasket).text(total);
	} else {
		$('#totalflash', elBasket).text('0,00');
	}

	activateAddOne(elBasket);
	activateRemoveOne(elBasket);
}

// Displays simple view of product
function showSimple(productId, type, callback){
	$.get(
		root + type + ".php",
		{
			id: productId,
			mode: "simple"
		}, 
		function(productRendering){
			var elProduct = $(".brands .product[id=" + productId + "]");
			
			// Fadein and activate
			$(elProduct).fadeTo("fast", 0.5, function(){
				$(elProduct).removeClass("productlong").addClass("productshort").html(productRendering).ready(function(){
					var photoLoaded = $(".productillustration .img").eq(0).attr('loaded');
					if (parseInt(photoLoaded, 10) == 0) {
						$(".productillustration img").attr({src: "kontorartikler/productimages/" + $(elProduct).attr("pcode") + "-1_81x72.jpg"});
					}
					$('input[name=number]', elProduct).val($(elProduct).attr('number'));
					activateShowMore(elProduct);
					activatePreloadImage(elProduct);
					activateCommonProductButtons(elProduct);
					insertThumbnail(elProduct);
					$(elProduct).fadeTo("normal", 1.0);
					if ($.isFunction(callback)){
						callback();
					}
				});
			});
	 	}
 	);
}
// Displays detailed view of product
function showDetailed(productId, type, callback){
	$.get(
		'/' + type + ".php",
		{
			id: productId,
			mode: "detailed"
		}, 
		function(productRendering){
			var elProduct = $(".brands .product[id=" + productId + "]");
			var imgDir = '/kontorartikler/productimages/';
			
			// Fadein and activate
			$(elProduct).fadeTo("fast", 0.5, function(){
				$(elProduct).removeClass("productshort").addClass("productlong").html(productRendering);
				var photoLoaded = $(".productillustration .img").eq(0).attr('loaded');
				if (parseInt(photoLoaded, 10) == 0) {
					var imgPath = imgDir + $(elProduct).attr("pcode") + "-1_200x177.jpg";
					$(".productillustration img").attr({src: imgPath});
				}
				$('input[name=number]', elProduct).val($(elProduct).attr('number'));
				priceUpdate(elProduct);
				activateShowLess(elProduct);
				activateProductThumbnails(elProduct);
				activateProductZoom(elProduct);
				activateCommonProductButtons(elProduct);
				activatePlayer(elProduct);
				$(elProduct).fadeTo("normal", 1.0);
				if ($.isFunction(callback)){
					callback();
				}
			});
 		}
 	);
}

function activateProductZoom(elProduct) {
	if ($(elProduct).hasClass('officeproduct') == false) {
		return;
	}
	$('.productillustration img', elProduct).css({cursor:'pointer'});
	$('.productillustration img', elProduct).click(function(){
		
		$('body').append('<div id="lightbox"><img src="resources/gfx/ajax-loader.gif" alt="Henter" style="margin-top:200px;margin-bottom:-7px;"/> Henter</div>');
		
		var coverPop = $('#lightbox');
		
		var width = 490;
		var height = 509;

		$(coverPop).css({
			width: width + "px", 
			height: height + "px", 
			marginTop: "-" + (height/2) + "px",
			marginLeft: "-" + (width/2) + "px"
			});

		$(coverPop).before('<div id="welcome-overlay" class="modal-overlay"></div>');
		$(coverPop).addClass("modal-window");
		$(coverPop).show();
		
		var id = $(elProduct).attr('id');
		var firstImage = 1;
		
		if ($(this).hasClass('thumb')) {
			firstImage = $(this).attr('alt');
		}
		
		$(coverPop).load('funktioner/ajax.zoom.php', { id: id, first_image: firstImage }, function(){
			
			/* Select image */
			$("#lightbox .thumb").click(function(){
				var width = $("#lightbox #lb-zoomed").attr("width"),
					height = $("#lightbox #lb-zoomed").attr("height"),
					code = $("#lightbox #lb-code").text(),
					number = $(this).attr("alt"),
					image;

				image = "/kontorartikler/productimages/" + code + "-" + number + "_" + width + "x" + height + ".jpg";

				$("#lightbox #lb-img-num").text(number);

				$("#lightbox #lb-zoomed").attr("src", image);
			});
			
			/* Previous image */
			$("#lightbox #lb-left").click(function(){
				var currentImage = parseInt($("#lightbox #lb-img-num").text(), 10),
					maxImage = $("#lightbox #lb-img-max").text(),
					width = $("#lightbox #lb-zoomed").attr("width"),
					height = $("#lightbox #lb-zoomed").attr("height"),
					code = $("#lightbox #lb-code").text(),
					nextNumber,
					nextImage;

				nextNumber = currentImage - 1;

				if (nextNumber == 0) {
					nextNumber = maxImage;
				}

				$("#lightbox #lb-img-num").text(nextNumber);

				nextImage = "/kontorartikler/productimages/" + code + "-" + nextNumber + "_" + width + "x" + height + ".jpg";

				$("#lightbox #lb-zoomed").attr("src", nextImage);

			});
			
			/* Next image */
			$("#lightbox #lb-right").click(function(){
				var currentImage = parseInt($("#lightbox #lb-img-num").text(), 10),
					maxImage = $("#lightbox #lb-img-max").text(),
					width = $("#lightbox #lb-zoomed").attr("width"),
					height = $("#lightbox #lb-zoomed").attr("height"),
					code = $("#lightbox #lb-code").text(),
					nextNumber,
					nextImage;
					
				nextNumber = currentImage + 1;
				
				if (nextNumber > maxImage) {
					nextNumber = 1;
				}
				
				$("#lightbox #lb-img-num").text(nextNumber);
				
				nextImage = "/kontorartikler/productimages/" + code + "-" + nextNumber + "_" + width + "x" + height + ".jpg";
				
				$("#lightbox #lb-zoomed").attr("src", nextImage);
				
			});
			
			/* Close box */
			
			$("#lightbox #lb-close").add('#welcome-overlay').click(function(){ closeModal(); });
			
			var width = $("#lightbox #lb-zoomed").attr("width"),
				height = $("#lightbox #lb-zoomed").attr("height");
				
			$('#lightbox #lb-thumbs img').each(function(){
				var newSrc = stripThumb($(this).attr('src'), width + "x" + height);
				$.preloadImages(newSrc);
			});
		});
	});
}

function activatePlayer(elProduct) {
	if ($(elProduct).hasClass('filmproduct') && $('.player', elProduct).size() == 1) {
		var id = '#trailer' + $(elProduct).attr("id");
		$(id).flowplayer("/flowplayer/flowplayer-3.2.7.swf",
		{
			clip: {
				autoPlay: false,
				autoBuffering: true
			}
		});
		$(id).flowplayer(0).load();
	}
}

// Flashes a color to indicate value change
function animateValueChange(element){
	var oldBackground = $(element).css("backgroundColor");
	$(element).stop(true, true).effect("highlight", {}, 2000);
}

function formatPrice(price){
	var formater = new NumberFormat(price);
	formater.setPlaces(2);
	formater.setSeparators(true, formater.PERIOD, formater.COMMA);
	return formater.toFormatted();
}

function renderCampaign(campaignId, callback){
	var root = 'http://' + $.url.attr('host') + $.url.attr('directory');
	$.post("/funktioner/ajax.cp.php",
		{
			id: campaignId,
			a: "gui"
		},
		function(data){ callback(data); },
		"json"
	);
}

function trim(str, chars) {
	return ltrim(rtrim(str, chars), chars);
}
 
function ltrim(str, chars) {
	chars = chars || "\\s";
	return str.replace(new RegExp("^[" + chars + "]+", "g"), "");
}
 
function rtrim(str, chars) {
	chars = chars || "\\s";
	return str.replace(new RegExp("[" + chars + "]+$", "g"), "");
}
// returns longlat and name of options
function activateGLSOptions(street, zipcode, callback) {
		$.get(
			'/src/php/gls_proxy.php', 
			{
				street: street,
				zipcode: zipcode,
				Amount: 3
			},
			function(json){
				if (json == false || json == null || typeof(json) == 'undefined') {
					// TODO redirect to error page
					alert('Beklager der opstod en fejl - prøv venligst igen om et øjeblik (GLS)');
					return;
				}

				// Build options HTML
				var options = '';
				for (var i = 0, json_len = json.length; i < json_len; i++) {
					var shop = json[i];
					var option_value = shop.Number;
					var option_content = '<strong>' + trim(shop.CompanyName) + '</strong><br/>';
					option_content += trim(shop.Streetname) + '<br/>';
					option_content += trim(shop.Streetname2) + '<br/>';
					option_content += trim(shop.ZipCode) + ' ' + trim(shop.CityName) + '<br/>';
					option_content += '<input type="hidden" name="possible_delivery_address_name" value="'+trim(shop.CompanyName)+'" class="possible_delivery_address_name">';
					option_content += '<input type="hidden" name="possible_delivery_address_id" value="'+trim(shop.Number)+'" class="possible_delivery_address_id">';
					option_content += '<input type="hidden" name="possible_delivery_address_street1" value="'+trim(shop.Streetname)+'" class="possible_delivery_address_street1">';
					option_content += '<input type="hidden" name="possible_delivery_address_street2" value="'+trim(shop.Streetname2)+'" class="possible_delivery_address_street2">';
					option_content += '<input type="hidden" name="possible_delivery_address_zipcode" value="'+trim(shop.ZipCode)+'" class="possible_delivery_address_zipcode">';
					option_content += '<input type="hidden" name="possible_delivery_address_city" value="'+trim(shop.CityName)+'" class="possible_delivery_address_city">';
					option_content += '<input type="hidden" name="possible_delivery_address_phone" value="'+trim(shop.Telephone)+'" class="possible_delivery_address_phone">' + "\n";
					
					var ohs = shop.OpeningHours;
					var openinghours_content = '';
					for(var j = 0, ohs_len = ohs.length; j < ohs_len; j++){
						var oh = ohs[j];
						openinghours_content += "<span class='day'>" + oh.days + "</span><span class='hours'>" + oh.hours + "</span><br/>\n";
					}
					
					options += ('<input type="radio" tabindex="17" name="delivery_site_option" class="delivery_site_option" value="{value}" /><img src="resources/gfx/google_map_markers/red_Marker' + String.fromCharCode(i+65) + '.png" /><div class="address"><div class="addressdata">{content}</div><div class="openinghours">{openinghours}</div></div><br/><br/>').replace("{value}", trim(option_value)).replace("{content}", option_content).replace("{openinghours}", openinghours_content);
				}
				$('#gls-data .notice').remove();
				$('#parcel-shop-list').html(options);
				$('<div id="point_data" style="display:none">' + escape(JSON.stringify(json).replace(/(\s{2,})/g, '')) + '</div>').appendTo('#parcel-shop-list');
				
				// FIXME: eventhough inputs have same name the group seems to be different so checked will be removed manually.
				var delivery_site_elements = $('#checkout-delivery .delivery_site_option');
				$('#checkout-delivery .delivery_site_option').click(function(e){
					$('#delivery_site').val($(this).val());

					for (var i = 0; i < delivery_site_elements.length; i++) {
						if ($(e.target).val() != $(delivery_site_elements[i]).val()) {
							$(delivery_site_elements[i]).removeAttr('checked');
						}
					}
					
					if ($(this).val() == 'door') {
						$('#delivery_address_name').val('');
						$('#delivery_address_id').val('');
						$('#delivery_address_street1').val('');
						$('#delivery_address_street2').val('');
						$('#delivery_address_zipcode').val('');
						$('#delivery_address_city').val('');
						$('#delivery_address_phone').val('');
					} else {
						var delivery_address = $(this).nextAll('.address').eq(0);
						$('#delivery_address_id').val($('.possible_delivery_address_id', delivery_address).val());
						$('#delivery_address_name').val($('.possible_delivery_address_name', delivery_address).val());
						$('#delivery_address_street1').val($('.possible_delivery_address_street1', delivery_address).val());
						$('#delivery_address_street2').val($('.possible_delivery_address_street2', delivery_address).val());
						$('#delivery_address_zipcode').val($('.possible_delivery_address_zipcode', delivery_address).val());
						$('#delivery_address_city').val($('.possible_delivery_address_city', delivery_address).val());
						$('#delivery_address_phone').val($('.possible_delivery_address_phone', delivery_address).val());
					}
				});
				// $('#delivery-option-door .delivery_site').focus(function(){
				// 	var customerType = $('#customer-type');
				// 	if (customerType && customerType.val() == 'private') {
				// 		$('#lgade2').val($('#delivery-option-door .street2').text());
				// 	}
				// });
				callback(json);
			},
			'json'
		);
}

function updateGLSoption() {
	var street = $('#lgade1').val();
	var zipcode = $('#lzip').val();
	if (street != '' && zipcode != '') {
		activateGLSOptions(street, zipcode, function(pointData){
			activateGoogleMap(
					street, 
					zipcode, 
					'google-map', // id of element
					pointData
					
			);		
			$('#map strong').remove();
			$('<strong><a href="map.php?' /*data=+ $('#point_data').text() &*/ + 'street=' + escape(street) + '&zipcode=' + zipcode + '"><img style="vertical-align: middle;" alt="" src="resources/gfx/linkpil.jpg"> Vis på stort kort</a></strong>').appendTo('#map');

			$('#map strong a').popupWindow({
				centerBrowser:1,
				height:430,
				width:530
			});
		});
		
		// update door option
		$('#delivery-option-door .address .name strong').text($('#lname').val());
		$('#delivery-option-door .address .zipcode').text($('#lzip').val()); 
		$('#delivery-option-door .address .city').text($('#lcity').val());
		$('#delivery-option-door .address .street').text($('#lgade1').val());
	}
}

function activateGoogleMap(street, zipcode, googleMap, pointData){	
	// Build google map
	var mcs_home  = new google.maps.LatLng(55.488592648080264, 8.465802669525146);
	var myOptions = {
		zoom: 11,
		center: mcs_home,
		//disableDefaultUI: true,
		mapTypeId: google.maps.MapTypeId.ROADMAP
	};
	var map    = new google.maps.Map(document.getElementById(googleMap), myOptions);
	var bounds = new google.maps.LatLngBounds();
		
	// Find location of customer address
    geocoder = new google.maps.Geocoder();
  	geocoder.geocode( { 'address': street + ', ' + zipcode + ', Danmark'}, function(results, status) {
  		var image = 'resources/gfx/google_map_markers/green_MarkerA.png';
		if (status == google.maps.GeocoderStatus.OK) {
		    var marker = new google.maps.Marker({
		        map: map, 
		        icon: image,
		        title: 'Her bor du',
		        position: results[0].geometry.location
		    });
		    bounds.extend(results[0].geometry.location);
		} else {
			//alert("Geocode was not successful for the following reason: " + status);
		}
	});
  	
	// Build markers for shops
  	for (i = 0; i < pointData.length; i++) {
  		image = 'resources/gfx/google_map_markers/red_Marker' + String.fromCharCode(i+65) + '.png';
  		var parcel_loc = new google.maps.LatLng(pointData[i].Latitude, pointData[i].Longitude); // iBob.dk Falkevej 3A, Esbjerg
		var marker = new google.maps.Marker({
	    	map: map,
	    	position: parcel_loc,
	    	icon: image,
	    	title: pointData[i].CompanyName
	    });
	    bounds.extend(marker.getPosition());
	}
	map.fitBounds(bounds);
}


function PackingInfoBox(path, callback) {
	var self = this;

	self.path = path;
	
	self.callback = callback;
		
	self.setPath = function(path) {
		self.path = path;
		return self;
	};
	
	self.setCallback = function(callback) {
		self.callback = callback;
		return self;
	};
	
	self.setEaseInAnim = function(anim) {
		self.ease_in_anim = anim;
		return self;
	};
	
	self.setEaseOutAnim = function(anim) {
		self.ease_out_anim = anim;
		return self;
	};
	
	self.setEaseTime = function(ease_time) {
		self.ease_time = ease_time;
		return self;
	};
	
	self.setDelay = function(delay) {
		self.delay = delay;
		return self;
	};
	
	self.setTtl = function(ttl) {
		self.ttl = ttl;
		return self;
	};
	
	self.setPackingTimeLimit = function(time_limit) {
		self.packing_time_limit = time_limit;
		return self;
	};
	
	self.setFromTime = function(from_time) {
		self.from_time = from_time;
		return self;
	};

	self.setToTime = function(to_time) {
		self.to_time = to_time;
		return self;
	};
	
	self.setOffDays = function() {
		self.off_days = Array.prototype.slice.call(arguments);
		return self;
	};
	
	self.start = function() {
		var delay     = self.delay     ? self.delay     :    2000, // default delay 2 sec
			ttl       = self.ttl       ? self.ttl       :   10000, // default time to live 10 sec
			ease_time = self.ease_time ? self.ease_time :    1000, // default ease in/out time 1 sec
			from_time = self.from_time ? self.from_time : '17:00', // default from time 5pm
			to_time   = self.to_time   ? self.to_time   : '21:00', // default to time 9pm
			off_days  = self.off_days  ? self.off_days  : [6,0],   // default off days saturday (6) and sunday (0)
			now       = new Date(),
			from_hours, from_minutes, to_hours, to_minutes;
			
		from_time = new Date(now.getFullYear(), now.getMonth(), now.getDate(), from_time.split(':')[0], from_time.split(':')[1]);
		to_time   = new Date(now.getFullYear(), now.getMonth(), now.getDate(), to_time.split(':')[0], to_time.split(':')[1]);
			
		if (from_time.getTime() < now.getTime() && now.getTime() < to_time.getTime() // within hours
			&& $.inArray(now.getDay(), off_days) < 0) {                              // and not on off days
			setTimeout(function() {
				$(self.path).animate(self.ease_in_anim, ease_time, self.callback);
				setTimeout(function() {	
					$(self.path).animate(self.ease_out_anim, ease_time);
				}, ttl );
			}, delay );
		}
	}
}

/**
 * Constructs a new Basket object
 */
function Basket(sid){
	this.sid = sid;
	this.root = 'http://' + $.url.attr('host') + "/"; // $.url.attr('directory');
}

/**
 * Adds an item to the basket.
 */
Basket.prototype.add = function(id, quantity, callback){
	$.post(this.root + "funktioner/ajax.basket.php",
		{
			forceVat: context.forceVat,
			sid: this.sid,
			add: id,
			quantity: quantity
		}, 
		function(result){ callback(result); }
	);
};
Basket.prototype.addOne = function(id, callback){
	this.add(id, 1, callback);
};

/** 
 * Removes an item from the basket.
 */
Basket.prototype.remove = function(id, quantity, callback){
	$.post(this.root + "funktioner/ajax.basket.php",
		{
			forceVat: context.forceVat,
			sid: this.sid,
			remove: id,
			quantity: quantity
		}, 
		function(result){ callback(result); }
	);	
};
Basket.prototype.removeOne = function(id, callback){
	this.remove(id, 1, callback);
};

/**
 * Clears the content of the basket.
 */
Basket.prototype.clear = function(callback){
	$.post(this.root + "funktioner/ajax.basket.php",
		{ 
			sid: this.sid,
			clear: 1 
		}, 
		function(result){ callback(result); }
	);
};

/**
 * Resets the basket but does not clear the items.
 */
Basket.prototype.reset = function(callback){
	$.post(this.root + "funktioner/ajax.basket.php",
		{
			sid: this.sid,
			reset: 1
		},
		function(result){ callback(result); }
	);
};
/**************** SEARCH SCRIPT ********************/

var ENTER = 13;
var TAB = 9;
var ESC = 27;
var KEYUP = 38;
var KEYDN = 40;

var suggestions = null;
var highlighted = -1;

var root = 'http://' + $.url.attr('host') + $.url.attr('directory');

$(document).ready(function(){

	var $search = $("#search");
	var timer = 0;
	
	if($search){
		$suggestions = $search.find("#suggestions");
		$suggestions.hide();
		var suggestions = null;
		var highlighted = -1;
		var $q = $(":input[name=q]", $search);
		$q.attr("autocomplete","off");
		$q.click(function(){ highlighted = -1; });
		var inputText = null;
				
		$q.keydown(function(event){
			switch(event.which){
				case TAB:
					// Use suggestion
					$q.val(suggestions[highlighted]);
					$q.focus();
					break;
				case ENTER:
					// Use suggestion
					//event.preventDefault();
					if(suggestions){
						$q.val(suggestions[highlighted]);
					}
					break;
				case ESC:
					// Hide
					$suggestions.empty();
					$suggestions.hide();
					$q.val("");
					highlighted = -1;
					break;
				case KEYUP:
					if (highlighted > 0){
						highlighted--;
					}
					changeHighlight($search, highlighted);
					break;
				case KEYDN:
					if(highlighted < (suggestions.length - 1)){
						highlighted++;
					}
					changeHighlight($search, highlighted);
					break;
				default:
					if (timer){
						window.clearTimeout(timer);
					}
					return;
			}
		});
		
		$q.keyup(function(event){
			switch(event.which){
				case ENTER:
				case TAB:
				case ESC:
				case KEYUP:
				case KEYDN:
					window.clearTimeout(timer);
					return;
				default:
					if($q.val() != inputText && $q.val().length > 0){
						inputText = $q.val();

						var callback = {
							query: $(this).val(),
							reqSuggestions: function(){
								$.get(root + "funktioner/ajax.search.php",
									{
										q: this.query,
										sid: Math.random()
									},
									function(result){
										//window.clearTimeout(timer);
										suggestions = result;
										if (suggestions != null && suggestions.length > 0){
											var $list = $("<ul></ul>");
											for(i=0;i<suggestions.length;i++){
												var $li = $("<li><a href='"+root+"soeg.php?q=" + suggestions[i] + "'>" + suggestions[i] + "</a></li>");
												$li.hover(function(){
													$(this).addClass("selected");
													$(this).siblings().removeClass("selected");
													highlighted = i;
												});
												$list.append($li);
											}
											$suggestions.html("<p>Søgeforslag til '" + $q.val() + "'</p>");
											$tip = $("<p class='tip'>Du kan anvende &uarr; og &darr; tasterne for at vælge søgeforslag</p>");
											$suggestions.append($tip);
											$suggestions.append($list);
											$suggestions.slideDown();
											$tip.css("font-weight", "bold");
											$tip.effect("highlight", {}, 5000, function(){
												$(this).slideUp("slow");
											});
										} else {
											$suggestions.empty();
											$suggestions.hide();
										}
										highlighted = -1;
									},
									"json"
								);	
							}	
						};

						timer = window.setTimeout(function(){ callback.reqSuggestions(); },	900);
						$suggestions.empty();
						$suggestions.hide();
					}
			}
		});
	}
;});

function changeHighlight($search, highlighted){
	$search.find("#suggestions").find("li").each(function(i){
		if(i == highlighted){
			$(this).addClass("selected");
		} else {
			$(this).removeClass("selected");
		}
	});
}
/**************** OLD SCRIPT ***********************/
function submitRabatForm() { document.rabatform.submit(); } 
function checkAll(formId, cName, check ) {
    for (i=0,n=formId.elements.length;i<n;i++)
        if (formId.elements[i].className.indexOf(cName) !=-1)
            formId.elements[i].checked = check;
}
function toggleKommune(formId, kval, check ) {
    for (i=0,n=formId.elements.length;i<n;i++)
        if (formId.elements[i].value.indexOf(kval) !=-1) {
            if (formId.elements[i].checked == false) {
                    formId.elements[i].checked = check;
            }
            else formId.elements[i].checked = false;
            }
}
function pop(url, name, w, h) {
        window.open(url, name, "fullscreen=no,toolbar=no,status=no,menubar=no,scrollbars=yes,resizable=no,directories=no,location=no,width="+w+",height="+h+",left=8,top=8");
}

function SwapImage(element)
{
  if (element.src.indexOf('-over') != -1)
  element.src = element.src.replace('-over', '-out');
  else if (element.src.indexOf('-out') != -1)
  element.src = element.src.replace('-out', '-over');
}

var regPhone = /\b[1-9]{1}\d{7}\b/;
var regPhoneGreenland = /\b((\+299)|(00299)){1}[1-9]{1}[0-9]{5}\b/;

//var reg_phone_dk = /\b[1-9]{1}\d{7}\b/;
//var reg_phone_se = /\b0[1-9]{1}\d{6,8}\b/;
//var reg_phone_gl = /\b((\+299)|(00299)){1}[1-9]{1}[0-9]{5}\b/;

function validateForm(b, f){
	$('#payment_method').val($(b).attr('name'));
	//var shop_language = $("#shop_country", f).val();
	var x = f.elements;
	var valid = true;
	var emailvalid = true;
	var cm;
	for (var i=0;i<x.length;i++){
		cm = x[i].className;
		if (cm.substring(0, 8)=="required" && !x[i].value) {
			x[i].style.border = "1px solid red";
			if (valid) alert('Alle felter markeret med * skal udfyldes');
			valid = false;
		}
		if (cm.substring(0, 9)=="email_val" && !isValidEmail(x[i].value)) {
			x[i].style.border = "1px solid red";
			if (valid) alert('Den indtastede emailadresse er ikke gyldig');
			valid = false;
		} 
		if (cm.substring(0, 10)=="requiredrb") {
			var cnt = -1;
			var group = f[x[i].name];
			for (var rbi=group.length-1; rbi > -1; rbi--) {
				if (group[rbi].checked) {cnt = rbi; rbi = -1;}
			}
			if (cnt < 0){
				x[i].style.border = "1px solid red";
				if (valid) alert('Alle felter markeret med * skal udfyldes');
				valid = false;
			}
		}
	}
	if (x.phone){
		var phone = x.phone.value;
		if(phone){
			var reg = null;
			if (x.lzip.value < 4000 && x.lzip.value > 3899){
				reg = regPhoneGreenland;
			} else {
				reg = regPhone;
			}
			if(!reg.test(phone)){
				alert('Ugyldigt telefonnummer');
				valid = false;
			}
/* merge code
		} else if (shop_language == 'SE') {
			reg = reg_phone_se;
		}
		*/
		}
	}
	// If COD delivery site does not apply
	if ($(b).attr('name') != 'topaycod') {
		if ($('#checkout-delivery .delivery_site_option:checked').length == 0){
			$.scrollTo('a[name=delivery]', 300);
			alert('Du skal udfylde leveringinformation før du går videre');
			valid = false;
		}
	}
	return valid;
}

function isValidEmail(str) {
   return (str.indexOf("@") > 0);
}
function minus(id) {
  var el = document.getElementById("number"+id.name);
  var antal = el.value;
  antal = parseInt(antal)-1;
  if (antal<0) {
    antal=0;
  }
  el.value = antal;
}
function plus(id) {
  var el = document.getElementById("number"+id.name);
  var antal = el.value;
  antal = (parseInt(antal)+1);
  if (antal<0) {
    antal=0;
  }
  el.value = antal;
}
function validatorkredit(button, theForm, partial)
{
	var valid = validateForm(button, theForm);
	if (valid && $(button).attr('name') == 'topaycod' && $('.cod-notice-displayed').length == 0) {
		result = $('#cod-modal-template').html();
		$('#cod-modal-template').remove();
		var height = 250;
		var width = 400;
		var modal = "";
		modal += "<div class=\"modal-overlay\"></div>";  
		modal += "<div class=\"modal-window\" id='cod-modal' style=\"width:" + width + "px; height:" + height + "px; margin-top:-" + (height / 2) + "px; margin-left:-" + (width / 2) + "px;\">";
		modal += result;
		modal += "</div>";
		
		$("body").append(modal);
		
		// Activate continue
		$('#cod-continue').click(function(e){
			$(button).addClass('cod-notice-displayed');
			setTimeout("continueCod()", 1000);
			return false;
		});
		$('#credit-continue').click(function(e){
			closeModal();
			setTimeout("continueCredit()", 1000);
			return false;
		});
		valid = false;
	}
	if (valid == true && (typeof(partial) === 'undefined' || partial == false)) {
		theForm.submit();
	}
	return valid;
}
function continueCredit(){
	$('input[name=topay]').click();
}
function continueCod(){
	$('input[name=topaycod]').click();
}
function closeModal()
{
	$(".modal-overlay").remove(); $(".modal-window").remove();
}
function validatorcvr(button, theForm)
{
	try {

		var valid = validatorkredit(button, theForm, true); // partial == true

		valid = valid && validatePhoneAtt();

		if (theForm.cvrnr.value == "") {
			alert("Indtast CVR-nummer");
			theForm.cvrnr.focus();
			valid = false;
		} else if (theForm.cvrnr.value.length !=8) {
			alert("CVR-nummer skal være 8 cifre. Du har kun indtastet "+theForm.cvrnr.value.length);
			theForm.cvrnr.focus();
			valid = false;
		}

		var val = parseInt(theForm.cvrnr.value, 10);

		if (isNaN(val)) {
			alert("CVR-nummer må kun indeholde tal");
			theForm.cvrnr.focus();
			valid = false;
		}

		if (valid === true) {
			theForm.submit();
		}

	} catch(e) {
		if (typeof(console) !== 'undefined') {
			console.log(e.message);
		} else {
			alert('An error has occurred: ' + e.message);
		}
		return false;
	}
	return false;
}
function validatoroff(button, theForm)
{
	try {

			var valid = validatorkredit(button, theForm, true); // partial == true

			valid = valid && validatePhoneAtt();

		  if (theForm.offean.value =="")
		  {
		    alert("Indtast EAN-nummer");
		    theForm.offean.focus();
		    valid = false;
		  }
		  else if (theForm.offean.value.length !=13)
		  {
		    alert("EAN-nummer skal være 13 cifre. Du har kun indtastet "+theForm.offean.value.length);
		    theForm.offean.focus();
		    valid = false;
		  }
		  // if (theForm.offkontakt.value =="")
		  // {
		  //   alert("Indtast kontaktperson");
		  //   theForm.offkontakt.focus();
		  //   valid = false;
		  // }
		  if (theForm.offreknr.value =="")
		  {
		    alert("Indtast ordre-/rekvisitionsnummer");
		    theForm.offreknr.focus();
		    valid = false;
		  }

		    // valid = validatorkredit(button, theForm);
		    // valid = valid && validatePhoneAtt();
		    if (valid == true) {
				theForm.submit();
			}
	
	} catch(e) {
		if (typeof(console) !== 'undefined') {
			console.log(e.message);
		} else {
			alert('An error has occurred: ' + e.message);
		}
		return false;
	}
	
	
	return false;
}

