var _slideBlockHeight;
var _searchTimer;

jQuery(document).ready(function(){
	initSlider();
	if($('.zoom_no_lbox').length){
		$(".zoom_no_lbox").gzoom({
			sW: 486,
			sH: 353,
			lW: 1024,
			lH: 768,
			lightbox: true,
			step: 10
		});
	}
	gal = new gallery({
		hold: '.gallery-zoom-wrapper',
		duration: 1000,
		fadeEl: '.zoom-wrapper ul > li',
		switcher: '.zoom-list-wrapper ul > li',
		effect: 'fade'
	});
	initPopupClick();
	initSearch();
	preInitSlideBlock();
	initSlideBlock();
	setTimeout(function(){
		initAddToCard();
	}, 500);
	doInitTabs();
	initClose();
});
function initClose(){
	$('div.search-popup').each(function(){
		var hold = $(this);
		var link = hold.find('a.close');

		link.click(function(){
			hold.hide();
			return false;
		});
	});
}
function doInitTabs(){
	$('ul.shipping-list').each(function(){
		var btn_h = $(this);
		var _btn = $(this).find('input.rad-tab');
		var _a = _btn.index(_btn.filter(':checked'));
		if(_a == -1) _a = 0;
		_btn.removeClass('active').eq(_a).addClass('active');
		_btn.each(function(_i){
			this._box = $(this).attr('alt');
			if(this._box){
				this._box = $(this._box);
				//if(_i == _a) this._box.show();
				//else this._box.hide();
				if(_i == _a) this._box.css({
					'position': 'relative',
					'left': 0,
					'top': 0
				});
				else this._box.css({
					'position': 'absolute',
					'left': -9999,
					'top': -9999
				});
			}
			this.onclick = function(){
				changeTab(_i);
				return false;
			}
		});
		function changeTab(_ind){
			if(_ind != _a){
				if(_btn.get(_a)._box) _btn.get(_a)._box.css({
					'position': 'absolute',
					'left': -9999,
					'top': -9999
				});
				if(_btn.get(_ind)._box) _btn.get(_ind)._box.css({
					'position': 'relative',
					'left': 0,
					'top': 0
				});
				_btn.eq(_a).removeClass('active');
				_btn.eq(_ind).addClass('active');
				_a = _ind;
			}
		}
	});
}
function initSearch(){
	$('#search-form').submit(function() {
		return doSearch();
	});
}

function doSearch(){
	clearTimeout(_searchTimer);
	_searchTimer = setTimeout("$('body').addClass('wait');$('#search-form').ajaxSubmit({target:'#search-popup',success:_postSearch})", 300);
	return false;
}

function _postSearch(){
	initClose();
	$('#search-popup').show();
	$('body').removeClass('wait');
	if (typeof ajax_track_search == 'function') {
		ajax_track_search();
	}
}

function initAddToCard(){
	var options = {
		target:		'#mini-cart',	// target element(s) to be updated with server response
		success:	_flashCart
	};
	$('.cart-form').ajaxForm(options);
}

function _flashCart(formData, jqForm, options) {
	var slide_wrapper = $('.nav-bar>.cart');
	var slide_link = slide_wrapper.find('.open-link');
	var close_link = slide_wrapper.find('.btn-close');
	var open_class= 'active';
	var _slideBlock = 'div.drop-box';

	if(slide_wrapper.hasClass(open_class)){
		$(_slideBlock).css({
			'height': _slideBlockHeight
		});
	}
	initSlideBlock();

	//VSA_handleResize();
	VSA_initScrollbars();
	if(!slide_wrapper.hasClass(open_class)){
		slide_link.trigger('click');
		setTimeout(function(){
			if(slide_wrapper.hasClass(open_class)){
				close_link.trigger('click');
			}
		}, 2000);
	}
	return false;
}

function preInitSlideBlock(){
	var _parentSlide = 'div.cart';
	var _slideBlock = 'div.drop-box';
	var _openClassS = 'active';
	_slideBlockHeight = $(_slideBlock).outerHeight(true);

	$(_parentSlide).each(function(){
		if (!$(this).is('.'+_openClassS)) {
			$(this).find(_slideBlock).css({
				'position': 'absolute',
				'top': -9999
			});
			setTimeout(function(){
				$(_slideBlock).css({
					'position': 'absolute',
					'top': 100+'%',
					'height': 0
				});
			}, 10);
		}
	});
}

function initSlideBlock(){
	// Slide effect
	var _parentSlide = 'div.cart';
	var _linkSlide = 'a.open-link';
	var _linkClose = 'a.btn-close';
	var _slideBlock = 'div.drop-box';
	var _openClassS = 'active';
	var _durationSlide = 500;

	$(_linkSlide,_parentSlide).click(function(){
		if ($(this).parents(_parentSlide).is('.'+_openClassS)) {
			$(this).parents(_parentSlide).find(_slideBlock).animate({
				height:0
			}, {
				duration: _durationSlide,
				complete: function(){
					$(this).parents(_parentSlide).removeClass(_openClassS);
				}
			});
		} else {
			$(this).parents(_parentSlide).find(_slideBlock).animate({
				height:_slideBlockHeight
			}, {
				duration: _durationSlide,
				complete: function(){
					$(this).parents(_parentSlide).addClass(_openClassS);
				}
			});
		}
		return false;
	});
	$(_linkClose).click(function(){
		if ($(this).parents(_parentSlide).is('.'+_openClassS)) {
			$(this).parents(_parentSlide).find(_slideBlock).animate({
				height:0
			}, {
				duration: _durationSlide,
				complete: function(){
					$(this).parents(_parentSlide).removeClass(_openClassS);
				}
			});
		}
	});
}

/*--- popup function ---*/
function initPopupClick(){
	if($('#fader').length == 0) $('body').append('<div id="fader"></div>');
	var _fader = $('#fader');
	_fader.hide();
	var _popup = -1;

	$('.with-popup').each(function(){
		var _el = this;
		if(_el.lang){
			_el._popup = $('#'+_el.lang);
			if(_el._popup.length){
				_el.lang = '';
				_el.old_onclick = (_el.onclick) ? _el.onclick : function(){return true};
				_el.onclick = function(){
					if(_el._popup){
						if (_el.old_onclick() !== false) {
							_el._popup.hide();
							_popup = _el._popup;
							showPopup();
						}
					}
					return false;
				}
				_el._popup.find('.close, .lightbox-close').click(function(){
					if($.browser.msie){
						_popup.hide();
						_fader.fadeOut(200);
						_popup = -1;
						if($.browser.version < 7) $('#wrapper select:not(".outtaHere")').css('visibility', 'visible');
					}
					else{
						_popup.fadeOut(400, function(){
							_fader.fadeOut(200);
							_popup = -1;
						});
					}
					$('div.optionsDivVisible').removeClass('optionsDivVisible').addClass('optionsDivInvisible');
					return false;
				});
			}
		}
	});
	_fader.click(function(){
		if(_popup != -1){
			if($.browser.msie){
				_popup.hide();
				_fader.fadeOut(200);
				_popup = -1;
				if($.browser.version < 7) $('#wrapper select:not(".outtaHere")').css('visibility', 'visible');
			}
			else{
				_popup.fadeOut(400, function(){
					_fader.fadeOut(200);
					_popup = -1;
				});
			}
			$('div.optionsDivVisible').removeClass('optionsDivVisible').addClass('optionsDivInvisible');
		}
		return false;
	});
	$(document).keydown(function(e){
		if(!e)evt = window.event;
		if(e.keyCode == 27 && _popup != -1){
			if($.browser.msie){
				_popup.hide();
				_fader.fadeOut(200);
				_popup = -1;
				if($.browser.version < 7) $('#wrapper select:not(".outtaHere")').css('visibility', 'visible');
			}
			else{
				_popup.fadeOut(400, function(){
					_fader.fadeOut(200);
					_popup = -1;
				});
			}
			$('div.optionsDivVisible').removeClass('optionsDivVisible').addClass('optionsDivInvisible');
		}
	});
	function showPopup(){
		replaceRadios();
		_fader.css({
			opacity: 0,
			height: initH(),
			display:'block'
		});
		_popup.css({top: $(window).scrollTop()});
		if($.browser.msie && $.browser.version < 7) if($.browser.version < 7) $('#wrapper select:not(".outtaHere")').css('visibility', 'hidden');
		_fader.fadeTo(400, 0.5, function(){
			if(_popup != -1){
				if($.browser.msie) _popup.show();
				else _popup.fadeIn(200, function(){
					if(initH() < _popup.outerHeight()+_popup.offset().top) _fader.height(_popup.outerHeight()+_popup.offset().top);
				});
				_popup.css({top: $(window).scrollTop()+ ($(window).height() - _popup.outerHeight())/2});
				if(initH() < _popup.outerHeight()+_popup.offset().top) _fader.height(_popup.outerHeight()+_popup.offset().top);
				if(typeof(replaceSelects) == 'function'){
					replaceSelects();
				}
			}
		});
	}
	function initH(){
		var _h = $('#wrapper').outerHeight();
		if(_h < $(window).height()) _h = $(window).height();
		if(_h < $('body').height()) _h = $('body').height();
		return _h;
	}
}

/* Gallery */
function gallery(_obj) {

	// defaults options
	this.options = {
		hold: 'div.gallery-slide',
		duration: 700,
		slideElement: 1,
		autoRotation: false,
		effect: false,
		fadeEl: 'ul',
		switcher: 'ul > li',
		disableBtn: false,
		nextBtn: 'a.link-next, a.btn-next, a.next',
		prevBtn: 'a.link-prev, a.btn-prev, a.prev',
		circle: true,
		direction: false
	};
	for(key in _obj) this.options[key] = _obj[key];

	var _this = this;
	var _hold = $(_this.options.hold);
	var _speed = $.browser.msie ? 0 : _this.options.duration;
	var _timer = _this.options.autoRotation;
	var _wrap = _hold.find(_this.options.fadeEl);
	var _el = _hold.find(_this.options.switcher);
	var _next = _hold.find(_this.options.nextBtn);
	var _prev = _hold.find(_this.options.prevBtn);
	var _count = _el.index(_el.filter(':last'));
	var _w = _el.outerWidth(true);
	var _h = _el.outerHeight(true);
	if (!_this.options.direction) {
		var _wrapHolderW = Math.ceil(_wrap.parent().width() / _w);
		if (((_wrapHolderW - 1) * _w + _w / 2) > _wrap.parent().width()) _wrapHolderW--;
	}
	else{
		var _wrapHolderW = Math.ceil(_wrap.parent().height()/_h);
		if (((_wrapHolderW-1)*_h + _h/2) > _wrap.parent().height()) _wrapHolderW--;
	}
	if (_timer) var _t;
	var _active = _el.index(_el.filter('.active:eq(0)'));
	if (_active < 0) _active = 0;
	var _last = _active;
	if (!_this.options.effect) var rew = _count - _wrapHolderW + 1;
	else var rew = _count;

	if (!_this.options.effect) {
		if (!_this.options.direction) _wrap.css({marginLeft: -(_w * _active)})
		else _wrap.css({marginTop: -(_h * _active)})
	}
	else {
		_wrap.css({
			opacity: 0
		}).removeClass('active').eq(_active).addClass('active').css({
			opacity: 1
		}).css('opacity', 'auto');
		_el.removeClass('active').eq(_active).addClass('active');
	}
	if (_this.options.disableBtn) {
		if (_count < _wrapHolderW) _next.addClass(_this.options.disableBtn);
		_prev.addClass(_this.options.disableBtn);
	}

	function fadeElement(){
		_wrap.eq(_last).animate({opacity:0}, {queue:false, duration: _speed});
		_wrap.removeClass('active').eq(_active).addClass('active').animate({
			opacity:1
		}, {queue:false, duration: _speed, complete: function(){
				$(this).css('opacity','auto');
			}});
		_el.removeClass('active').eq(_active).addClass('active');
		_last = _active;
	}
	function scrollEl(){
		if (!_this.options.direction) _wrap.animate({marginLeft: -(_w * _active)}, {queue:false, duration: _speed})
		else _wrap.animate({marginTop: -(_h * _active)}, {queue:false, duration: _speed})
	}
	function toPrepare(){
		if ((_active == rew) && _this.options.circle) _active = -_this.options.slideElement;
		for (var i = 0; i < _this.options.slideElement; i++){
			_active++;
			if (_active > rew) {
				_active--;
				if (_this.options.disableBtn &&(_count > _wrapHolderW)) _next.addClass(_this.options.disableBtn);
			}
		};
		if (_active == rew) if (_this.options.disableBtn &&(_count > _wrapHolderW)) _next.addClass(_this.options.disableBtn);
		if (!_this.options.effect) scrollEl();
		else fadeElement();
	}
	function runTimer(){
		_t = setInterval(function(){
			toPrepare();
		}, _timer);
	}
	_next.click(function(){
		flag=true;
		if(_t) clearTimeout(_t);
		if (_this.options.disableBtn &&(_count > _wrapHolderW)) _prev.removeClass(_this.options.disableBtn);
		toPrepare();
		if (_timer) runTimer();
		return false;
	});
	_prev.click(function(){
		flag=true;
		if(_t) clearTimeout(_t);
		if (_this.options.disableBtn &&(_count > _wrapHolderW)) _next.removeClass(_this.options.disableBtn);
		if ((_active == 0) && _this.options.circle) _active = rew + _this.options.slideElement;
		for (var i = 0; i < _this.options.slideElement; i++){
			_active--;
			if (_active < 0) {
				_active++;
				if (_this.options.disableBtn &&(_count > _wrapHolderW)) _prev.addClass(_this.options.disableBtn);
			}
		};
		if (_active == 0) if (_this.options.disableBtn &&(_count > _wrapHolderW)) _prev.addClass(_this.options.disableBtn);
		if (!_this.options.effect) scrollEl();
		else fadeElement();
		if (_timer) runTimer();
		return false;
	});
	if (_this.options.effect) _el.click(function(){
		_active = _el.index($(this));
		if(_t) clearTimeout(_t);
		fadeElement();
		if (_timer) runTimer();
		if(_this.options.fadeEl != _this.options.switcher ){
			return false;
		}
	});
	if (_timer) runTimer();

	this.stop = function(){
		if (_t) clearTimeout(_t);
	}
	this.play = function(){
		if (_t) clearTimeout(_t);
		if (_timer) runTimer();
	}
}

function initSlider(){
	if ($("#slider-range").length){
		var currency_code = $('#currency_code').val();
		$("#slider-range").slider({
			orientation: "vertical",
			range: true,
			min: parseInt($("#slider-range span.min").text()),
			max: parseInt($("#slider-range span.max").text()),
			values: [
				parseInt($("#amount_min").val()) ? parseInt($("#amount_min").val()) : parseInt($("#slider-range span.min").text()),
				parseInt($("#amount_max").val()) ? parseInt($("#amount_max").val()) : parseInt($("#slider-range span.max").text())],
			slide: function(event, ui) {
				$("#amount_min").val(ui.values[0]);
				$("#amount_max").val(ui.values[1]);
				$("#slider-range span.min").text(ui.values[0] + ' ' + currency_code);
				$("#slider-range span.max").text(ui.values[1] + ' ' + currency_code);
			},
			change: function(event, ui) {
				//doSegmentation();
				$('#segmentationForm').submit();
			}

		});
		$("#amount_min").val($("#slider-range").slider("values", 0));
		$("#amount_max").val($("#slider-range").slider("values", 1));
		$("#slider-range span.min").text($("#slider-range").slider("values", 0) + ' ' + currency_code);
		$("#slider-range span.max").text($("#slider-range").slider("values", 1) + ' ' + currency_code);
	}
}



function initPopups()
{
	initPopup({
		openEvent:'click'
	});
	initPopup({
		popupHolderClass:'popup-hover'
	});
}
if (window.addEventListener)
	window.addEventListener("load", initPopups, false);
else if (window.attachEvent)
	window.attachEvent("onload", initPopups);

function initPopup(_popup) {
	if (!_popup.popupHolderTag) _popup.popupHolderTag = 'div';
	if (!_popup.popupTag) _popup.popupTag = 'div';
	if (!_popup.popupHolderClass) _popup.popupHolderClass = 'popup-holder';
	if (!_popup.popupClass) _popup.popupClass = 'popup';
	if (!_popup.linkOpenClass) _popup.linkOpenClass = 'open';
	if (!_popup.linkCloseClass) _popup.linkCloseClass = 'close';
	if (!_popup.openClass) _popup.openClass = 'active';
	if (!_popup.openEvent) _popup.openEvent = 'hover';

	var timer = [];
	var _popupHolderTag = document.getElementsByTagName(_popup.popupHolderTag);
	if (_popupHolderTag) {
		for (var i=0; i<_popupHolderTag.length; i++) {
			if (_popupHolderTag[i].className.indexOf(_popup.popupHolderClass) != -1) {
				var _popupLink = _popupHolderTag[i].getElementsByTagName('a');
				for (var j=0; j<_popupLink.length; j++) {
					_popupLink[j].parent = _popupHolderTag[i];
					if (_popupLink[j].className.indexOf(_popup.linkOpenClass) != -1) {
						if (_popup.openEvent == 'click') {
							_popupLink[j].onclick = function(){
								if (this.parent.className.indexOf(_popup.openClass) != -1) {
									this.parent.className = this.parent.className.replace(_popup.openClass,'');
								} else {
									this.parent.className += ' '+_popup.openClass;
								}
								return false;
							}
						} else {
							var _popupTag = _popupHolderTag[i].getElementsByTagName(_popup.popupTag);
							for (var k=0; k<_popupTag.length; k++) {
								if (_popupTag[k].className.indexOf(_popup.popupClass) != -1) {
									_popupTag[k].parent = _popupHolderTag[i];
									_popupTag[k].onmouseover = function(){
										if (timer[j]) clearTimeout(timer[j]);
										if (this.parent.className.indexOf(_popup.openClass) == -1) {
											this.parent.className += ' '+_popup.openClass;
										}
									}
									_popupTag[k].onmouseout = function(){
										var _this = this;
										timer[j] = setTimeout(function(){
											_this.parent.className = _this.parent.className.replace(_popup.openClass,'');
										},2);
									}
								}
							}
							_popupLink[j].onmouseover = function(){
								if (timer[j]) clearTimeout(timer[j]);
								if (this.parent.className.indexOf(_popup.openClass) == -1) {
									this.parent.className += ' '+_popup.openClass;
								}
							}
							_popupLink[j].onmouseout = function(){
								var _this = this;
								timer[j] = setTimeout(function(){
									_this.parent.className = _this.parent.className.replace(_popup.openClass,'');
								},2);
							}
						}
					} else if (_popupLink[j].className.indexOf(_popup.linkCloseClass) != -1) {
						_popupLink[j].onclick = function(){
							if (this.parent.className.indexOf(_popup.openClass) != -1) {
								this.parent.className = this.parent.className.replace(_popup.openClass,'');
							} else {
								this.parent.className += ' '+_popup.openClass;
							}
							return false;
						}
					}
				}
			}
		}
	}
}

function color_select(what, color) {
	var w = what.closest('form');
	w.find('.sel_c').hide().attr('disabled', 'disabled');
	w.find('div.color'+color).closest('ul.colors-list').find('div.rad').each(function() {
		if($(this).attr('id').indexOf('myRadio') != -1) {
			$(this).attr('class', $(this).attr('class').replace('radioAreaChecked','').replace('radioArea','')+' radioArea');;
		}
	});
	try {
		w.find('div.color'+color).attr('class', w.find('div.color'+color).attr('class').replace('radioAreaChecked','').replace('radioArea','')+' radioAreaChecked');;
	} catch(E) {;}
	w.find('#sel_c'+color).show().removeAttr('disabled');
	var offset = w.find('#sel_c'+color).index('select.sel_c');
	w.find('#sarea'+offset).show();
	w.find('#curcolor').val(color);
	var showv = w.find('#c'+color).attr('lang');
	w.closest('.c1').find('li').each(function() {
		var l = $(this).attr('lang');
		if(l.length > 0 && l.substring(0,1) == 'v' && l != showv && l != 'v') {
			$(this).css('display','none').addClass('hidden').removeClass('shown');
		}
		else if(l.substring(0,1) == 'v') {
			$(this).css('display','block').addClass('shown').removeClass('hidden');
		}
	});
	w.closest('.c1').find('.zoom-list li.shown a:first').click();
	//replaceSelects();
}

function quickcolor_select(what, color) {
	var w = $('#lightbox3 form:first');;
	w.find('.sel_c').hide().attr('disabled', 'disabled');
	w.find('div.color'+color).closest('ul.colors-list').find('div.rad').each(function() {
		if($(this).attr('id').indexOf('myRadio') != -1) {
			$(this).attr('class', $(this).attr('class').replace('radioAreaChecked','').replace('radioArea','')+' radioArea');;
		}
	});
	try {
		w.find('div.color'+color).attr('class', w.find('div.color'+color).attr('class').replace('radioAreaChecked','').replace('radioArea','')+' radioAreaChecked');
	} catch(E) {;}
	w.find('#sel_c'+color).show().removeAttr('disabled');
	var offset = w.find('#sel_c'+color).index('select.sel_c');
	w.find('#sarea'+offset).show();
	w.find('#curcolor').val(color);
	var showv = w.find('#qc'+color).attr('lang');
	var lightboxshown = false;
	var last = false;
	w.closest('#lightbox3').find('.text ul.zoom-list li.zimage').css('display','none').removeClass('shown').addClass('hidden');
	w.closest('#lightbox3').find('.text ul.zoom-list li.zimage').each(function() {
		if(!lightboxshown) {
			var l = $(this).attr('lang');
			if(l.length > 0 && l.substring(0,1) == 'v' && (l == showv || l == 'v')) {
				$(this).css('display','block').addClass('shown').removeClass('hidden');
				lightboxshown = true;
			}
		}
	});
//	if(last.css('display')) {
//		last.css('display','block').addClass('shown').removeClass('hidden');
//	}
	//replaceSelects();
}

// onClick handler for the continue button on the checkout page.
function submitCheckout() {
	// Conditions accepted?
	var conditions = $('input[name=handelsbetingelser]');
	if (conditions.length == 0 || ! conditions.is(':checked')) {
		$("#error_conditions").show();
		$("#error_updating_customer").hide();
		return false;
	}
	$("#error_conditions").hide();
	
	// Are we creating a new customer, or accepting the currently logged in user?
	var return_var = false;
	var new_customer_form = $('form#new-customer-form');
	if (new_customer_form.length == 0) { // Customer accepted - continue
		var post_data = {};
		post_data['page_label'] = 'ajax_update_customer';
		post_data['cms_module_customer_page__personal_information'] = true;
		post_data['cms_module_customer_page__name'] = $('#name').val();
		post_data['cms_module_customer_page__street'] = $('#street').val();
		post_data['cms_module_customer_page__address2'] = $('#address2').val();
		post_data['cms_module_customer_page__zip_code'] = $('#zip_code').val();
		post_data['cms_module_customer_page__city'] = $('#city').val();
		post_data['cms_module_customer_page__phone'] = $('#phone').val();
		post_data['cms_module_customer_page__email'] = $('#email').val();
		post_data['cms_module_customer_page__gender'] = $('input[name="gender"]:checked').val();
		$.ajax({
			url:		"/",
			data:		post_data,
			type:		'POST',
			async:		false,
			success:	function(data) {
				if(data.status) {
					$("#error_updating_customer").hide();
					return_var = continueFromCheckout();
				}
				else {
					$("#error_updating_customer").html(data.error_message);
					$("#error_updating_customer").show();
					return false;
				}
			}
		});
	}
	else { // Trying to create new customer
		// Submit with AJAX, replace DIV on missing data, continue to next page on success.
		$.ajax({
			url:		"/",
			data:		new_customer_form.serialize(),
			type:		'POST',
			async:		false,
			success:	function(data) {
							// Insert the returned html
							$("#login_or_customer_page").html(data);
							// Rebind onChange handlers and restore data
							$("#login_or_customer_page input").change(saveData);
							restoreData();
							// Hide error about conditions not checked
							$("#error_conditions").hide();
							// Er der meldt fejl?
							// I så fald skal vi ikke fortsætte.
							if ($('.newuser-input-err').length) {
								return false;
							}
							// OK, continue to next page
							return_var = continueFromCheckout();
						}
		});
	}
	return return_var;
}

function continueFromCheckout() {
	if ($('input[name="payment_method"]:checked').val() == 'invoice') {
		// Disable delivery address in backend
		$.ajax({
			url:		"/",
			data:		{	page_label:			"ajax_delivery",
							mode:				"setdelivery",
							delivery_address:	"address_same_as_payer",
							handelsbetingelser:	1},
			type:		'POST',
			async:		false
		});
		// Render payment form
		return _submitPayment();
	}
	else { // Allow deliveryaddress for card payments
		window.location = '/webshop/' + netimageRessources['url.delivery'] + '/';
		return false;
	}
}

function submitDelivery() {
	var cart_form = $('form#delivery-form');
	var return_var = false;
	if (cart_form.length) {
		// prepare postdata
		var postData = cart_form.serialize()+'&handelsbetingelser=on'; // have already agreed on the previous page
		// post data
		$.ajax({url: "/?page_label=ajax_delivery", data: postData, type: 'POST', async: false, context: document.body, success: function(data){
				// Insert the returned html
				$("#delivery_content").html(data);
				doInitTabs();
				replaceRadios();
				initPopup({
					popupHolderClass:'popup-hover'
				});
				// Er der meldt fejl?
				// I så fald er der jo ingen grund til at fortsætte.
				if ($('.order_error, .newuser-input-err, .delivery-error').length) {
					return;
				}
				return_var = _submitPayment();
			}});

	}
	return return_var;
}

function _submitPayment() {
	var to_payment = $('#to_payment');
	var return_var = false;
	if (to_payment.length) {
		$.ajax({url: "/?page_label=payment_popup", type: 'GET', async: false, context: document.body, success: function(data){
				$('#lightbox2 .ajaxcontent').html(data);
				doInitTabs();
				return_var = true;
			}
		});
	}
	return return_var;
}

function submitForgotPassword() {
	var username = $('#it1') // Argh, fix those IDs!
	// @todo Some warning if there is no username?
	$('#forgot_password_username').val(username.val());
	$('#forgotten-password-form').submit();
}

function urlEncode(s) {
	return encodeURIComponent( s ).replace( /\%20/g, '+' ).replace( /!/g, '%21' ).replace( /'/g, '%27' ).replace( /\(/g, '%28' ).replace( /\)/g, '%29' ).replace( /\*/g, '%2A' ).replace( /\~/g, '%7E' );
}

function urlDecode(s) {
	return decodeURIComponent( s.replace( /\+/g, '%20' ).replace( /\%21/g, '!' ).replace( /\%27/g, "'" ).replace( /\%28/g, '(' ).replace( /\%29/g, ')' ).replace( /\%2A/g, '*' ).replace( /\%7E/g, '~' ) );
}

/* Newest products carousel */
var newestCarousel = {
	ul: null,
	timeout: null,
	itemCount: 0,
	itemWidth: 0,
	firstElementOnViewport: 1,
	
	/**
	 * Initialize the carousel
	 * @param carouselId	The ID of the carousel ul
	 * @param intervalTime	The time between each roll (in ms)
	 */
	init: function(carouselId, intervalTime) {
		intervalTime = intervalTime || 0;
		this.ul = $(carouselId);
		// Check if there are any items at all
		var items = this.ul.children();
		this.itemCount = items.length;
		if (this.itemCount == 0) {
			return;
		}
		this.itemWidth = items.outerWidth('true');
		this.firstElementOnViewPort = 1;
		// Make clones of all the elements within the viewport such that we can make a smooth transition at the end
		var shownInViewport = Math.round(this.ul.width() / this.itemWidth);
		for (i = 0; i < shownInViewport; i++) {
			$(this.ul).append(jQuery(items[i]).clone());
		}
		// Set the total width of the ul such that all items are in one line
		$(this.ul).css('width',(this.itemCount+shownInViewport)*this.itemWidth + this.itemWidth + "px");
		// Start the rolling!
		if (intervalTime) {
			this.startRolling(intervalTime);
		}
	}, // End init()
	
	/**
	 * Start the carousel timeout
	 * @param intervalTime	The time between each roll (in ms)
	 */
	startRolling: function(intervalTime) {
		this.timeout = setInterval(newestCarousel.rollNext, intervalTime);
	}, // End startRolling()
	
	/**
	 * Stop the carousel timeout
	 */
	stopRolling: function() {
		clearTimeout(this.timeout);
	}, // End stopRolling()
	
	/**
	 * Roll the carousel one item ahead
	 */
	rollNext: function() {
		// Have we reached the end of the items, then move back to the beginning and animate from there instead
		if (newestCarousel.firstElementOnViewPort > newestCarousel.itemCount) {
			newestCarousel.firstElementOnViewPort = 2;
			$(newestCarousel.ul).css('left', "0px");
		}
		else {
			newestCarousel.firstElementOnViewPort++;
		}
		$(newestCarousel.ul).animate({
			left: '-=' + newestCarousel.itemWidth,
			y: 0,
			queue: true
		}, 'swing');
	} // End rollNext()
}; // newestCarousel

