var root = 'http://' + $.url.attr('host') + $.url.attr('directory');
if($.url.attr("file") == "product.php"){
	var d = new Date();
	var templateSimple = $.createTemplateURL(root + 'funktioner/template.product_simple.php', null, null);
	//var templateSimple = $.createTemplateURL(root + 'funktioner/template.product_simple.php?s=' + d.getTime(), null, null);
	var templateDetailed = $.createTemplateURL(root + 'funktioner/template.product_detailed.php', null, null);
	//var templateDetailed = $.createTemplateURL(root + 'funktioner/template.product_detailed.php?s=' + d.getTime(), null, null);
}
var basket = new Basket();

jQuery.preloadImages = function(){
	for(var i = 0; i<arguments.length; i++){
		jQuery("<img>").attr("src", arguments[i]);
	}
};

(function($){
  $.fn.shuffle = function() {
    return this.each(function(){
      var items = $(this).children();
      return (items.length)
        ? $(this).html($.shuffle(items))
        : this;
    });
  };
 
  $.shuffle = function(arr) {
    for(
      var j, x, i = arr.length; i;
      j = parseInt(Math.random() * i, 10),
      x = arr[--i], arr[i] = arr[j], arr[j] = x
    );
    return arr;
  };
})(jQuery);


var campaignObject = null;
$(document).ready(function(){
	var root = 'http://' + $.url.attr('host') + $.url.attr('directory');
	if(BrowserDetect.browser=='Explorer' && BrowserDetect.version==6){
		$('.nav1 > li').css('text-indent', '-9000px');
		$('.nav2').hide();	
		$('.nav1 > li').mouseover(function(e){
			$('.nav2', this).show();
		}).mouseout(function(e){
			$('.nav2', this).hide();
		});
		
		$('#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'
			}
		);
	}
	
	// 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);
			}
			activateCommonProductButtons(this);
		});
	});
	
	// Lazyload images
	//$("img").lazyload({ threshold: 200, effect: "fadeIn"});
	
	// Activate basket effects
	var elSmallbasket = $("#smallbasket");
	activateAddOne(elSmallbasket);
	activateRemoveOne(elSmallbasket);
	
	// 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 ($.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').focus(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();
		});
	}


	if ($.url.attr("file") == "product.php" && $.url.attr("anchor")){
		$("a[name="+$.url.attr("anchor")+"]").remove();
	}
	
	if ($.url.attr("file") == "catalogue.php"){
		$("#catalogue .zoom").click(function(event){
			var prd = $(event.target).parents(".product");
			var officeadPath = $("#adpath").val();
			var id = $(prd).attr("id");
			var imgName = $(".imgname", prd).val();
			$.post(root + "funktioner/ajax.officead.php", 
				{
					id: id,
					img: imgName,
					path: officeadPath
				}, 
				function(result){ 
					var height = 415;
					var width = 530;
			        var modal = "";  
			        modal += "<div class=\"modal-overlay\"></div>";  
			        modal += "<div class=\"modal-window\" style=\"width:" + width + "px; height:" + height + "px; margin-top:-" + (height / 2) + "px; margin-left:-" + (width / 2) + "px;\">";  
			        modal += result;  
			        modal += "</div>";      
			  
			        $("#catalogue").append(modal);  
			        
			        var elProduct = $(".modal-window .product");
			        activateCommonProductButtons(elProduct);
			  
			        $(".close-window").click(function(){ $(".modal-overlay").remove(); $(".modal-window").remove(); });  
			        $(".modal-overlay").click(function(){ $(".modal-overlay").remove(); $(".modal-window").remove(); });  
				});
		});
	}
;});

//var intervalId = 0;
$(window).bind("load", function() { 
    //intervalId = setInterval("lazyLoadProducts()", 5000);
	if ($.url.attr("file") == "product.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 hasProductPhoto = $("#productphoto", elProduct).val();
	if(hasProductPhoto == '1'){
		$(".productillustration img", elProduct).attr({src: "kontorartikler/productimages/" + $(elProduct).attr("pcode") + "-1_81x72.jpg"});
	}
}

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(0);
		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) {
	var parts = path.split('_');
	if (parts.length == 2) {
		var sub_parts = parts[1].split('.');
		return parts[0] + '.' + 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){
		$(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);
		});
	});
}
function activateShowMore(elProduct){
	var root = 'http://' + $.url.attr('host') + $.url.attr('directory');
	$(elProduct).find('a[class=details]').each(function(i){
		$(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);
		});
	});
}
function activateCommonProductButtons(elProduct){
	activateBuyButton(elProduct);
	activateChangeOneUp($(elProduct).find(".addbutton"));
	activateChangeOneDown($(elProduct).find(".subbutton"));
	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 number = $(elProduct).find("input[name=number]").val();
		var id = $(elProduct).attr("id");
		basket.add(id, number, function(updatedBasket){
			updateBasket($("#smallbasket"), updatedBasket, id);
		});	
	});
}
// 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]");
		$(elNumber).val(parseInt($(elNumber).val(), 10) + 1);
		animateValueChange(elNumber);
		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);
		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 price = $("#dprice", elProduct).val();
	var priceExVat = $("#dpriceexvat", elProduct).val();
	var discountPrice = $("#ddiscountprice", elProduct).val();
	var discountPriceExVat = $("#ddiscountpriceexvat", elProduct).val();
	var discountMinUnits = parseInt($("#ddiscountminunits", elProduct).val(), 10);	
	var elPrice = $("#price" + $(elProduct).attr("id"), elProduct);
	var oldPrice = $(elPrice).text();
	var elPriceExVat = $("#priceExVat" + $(elProduct).attr("id"), elProduct);
	if (parseInt($(elProduct).find("input[name=number]").val(), 10) < discountMinUnits) {
		$(elPrice).text(formatPrice(price));
		$(elPriceExVat).text(formatPrice(priceExVat) + ")");
	} else {
		$(elPrice).text(formatPrice(discountPrice));
		$(elPriceExVat).text(formatPrice(discountPriceExVat) + ")");
	}
	if ($(elPrice).text() != oldPrice && !(oldPrice == null || oldPrice == "")){
		animateValueChange(elPrice);
		animateValueChange(elPriceExVat);		
	}
}

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
function activatePreloadImage(elProduct){
	var config = {
		    sensitivity: 1,  
			interval: 100,    
			over: function(){
				var elImg = $(".productillustration img", elProduct);
				if (elImg.attr("src")) {
					$.preloadImages($(elImg).attr("src").replace("_s", ""));
				}	
			}, 
			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, callback){
	$.getJSON(root + "funktioner/ajax.product.php", 
		{
			id: productId,
			mode: "0"
		}, 
		function(product){
			var elProduct = $(".brands .product[id=" + product.id + "]");
		 	$(elProduct).setTemplate(templateSimple);
			$(elProduct).slideUp("fast", function(){
				$(elProduct).removeClass("productlong").addClass("productshort").processTemplate(product).ready(function(){
					priceUpdate(elProduct);
					activateShowMore(elProduct);
					activatePreloadImage(elProduct);
					activateCommonProductButtons(elProduct);
					insertThumbnail(elProduct);
					$(elProduct).slideDown("slow");
					if ($.isFunction(callback)){
						callback();
					}
				});
			});
	 	}
 	);
}
// Displays detailed view of product
function showDetailed(productId){
	$.getJSON(root + "funktioner/ajax.product.php", 
		{
			id: productId
		}, 
		function(product){
			//alert(product.toSource());
			var elProduct = $(".brands .product[id=" + product.id + "]");
			var imgPath = 'kontorartikler/productimages/';
		 	$(elProduct).setTemplate(templateDetailed);
			$(elProduct).slideUp("fast", function(){
				$(elProduct).removeClass("productshort").addClass("productlong").processTemplate(product).ready(function(){
					$(".productillustration img", elProduct).attr({src: product.productPhoto});						
					priceUpdate(elProduct);
					activateShowLess(elProduct);
					if(product.productPhotos > 1){
						var thumbs = $('<div class="thumbs"></div>');
						for(i = 1; i <= product.productPhotos; i++){
							$(thumbs).append('<img src="' + root + imgPath + product.productCode  + '-' + i + '_48x43.jpg" alt="#' + i + '"/>');	
						}
						$(".productillustration", elProduct).append(thumbs);
					}
					activateProductThumbnails(elProduct);
					activateCommonProductButtons(elProduct);
					$(elProduct).slideDown("slow");
				});
			});
 		}
 	);
}

// 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(root + "funktioner/ajax.cp.php",
		{
			id: campaignId,
			a: "gui"
		},
		function(data){ callback(data); },
		"json"
	);
}
// 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) {
					// 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>' + shop.CompanyName + '</strong><br/>';
					option_content += shop.Streetname + '<br/>';
					option_content += shop.Streetname2 + '<br/>';
					option_content += shop.ZipCode + ' ' + shop.CityName + '<br/>';
					option_content += '<input type="hidden" name="possible_delivery_address_name" value="'+shop.CompanyName+'" class="possible_delivery_address_name">';
					option_content += '<input type="hidden" name="possible_delivery_address_id" value="'+shop.Number+'" class="possible_delivery_address_id">';
					option_content += '<input type="hidden" name="possible_delivery_address_street1" value="'+shop.Streetname+'" class="possible_delivery_address_street1">';
					option_content += '<input type="hidden" name="possible_delivery_address_street2" value="'+shop.Streetname2+'" class="possible_delivery_address_street2">';
					option_content += '<input type="hidden" name="possible_delivery_address_zipcode" value="'+shop.ZipCode+'" class="possible_delivery_address_zipcode">';
					option_content += '<input type="hidden" name="possible_delivery_address_city" value="'+shop.CityName+'" class="possible_delivery_address_city">';
					option_content += '<input type="hidden" name="possible_delivery_address_phone" value="'+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" class="delivery_site" 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}", option_value).replace("{content}", option_content).replace("{openinghours}", openinghours_content);
				}
				$('#gls-data .notice').remove();
				$('#parcel-shop-list').html(options);
				//alert(JSON.stringify(json).replace(/(\s{2,})/g, ''));
				$('<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');
				$('#checkout-delivery .delivery_site').click(function(e){
					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 ($(e.target).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 = $(e.target).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());		
					}
				});
				
				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); // MCS Data 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);
}


/**
 * 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", 
		{
			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", 
		{
			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: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)
{
	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) {
		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)
{

  var valid = validatorkredit(button, theForm);
  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);
  if (isNaN(val))
  {
          alert("CVR-nummer må kun indeholde tal");
    theForm.cvrnr.focus();
    valid = false;
  }
    if (valid == true) {
		theForm.submit();
	}
}
function validatoroff(button, theForm)
{
	var valid = null;

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