/**
 * Javascript implementation of the equivalent php function.
 */
function number_format(number, decimals, dec_point, thousands_sep) {
	var n = !isFinite(+number) ? 0 : +number, 
		prec = !isFinite(+decimals) ? 0 : Math.abs(decimals),
		sep = (typeof thousands_sep === 'undefined') ? ',' : thousands_sep,
		dec = (typeof dec_point === 'undefined') ? '.' : dec_point,
		s = '',
		toFixedFix = function (n, prec) {
			var k = Math.pow(10, prec);
			return '' + Math.round(n * k) / k;
		};
	s = (prec ? toFixedFix(n, prec) : '' + Math.round(n)).split('.');
	if (s[0].length > 3) {
		s[0] = s[0].replace(/\B(?=(?:\d{3})+(?!\d))/g, sep);    }
	if ((s[1] || '').length < prec) {
		s[1] = s[1] || '';
		s[1] += new Array(prec - s[1].length + 1).join('0');
	}
	return s.join(dec);
}

/**
 * A set of on-dom-loaded bindings.
 */
$(function() {
	
	/**
	 * Use an a-element to submit a form
	 */
	$('a.submit').click(function() {
		$(this).closest('form').submit();
	});
	
	/**
	 * Submit a form with enter without a input type="submit" element
	 */
	$('form input').keypress(function(e) {
		if (e.keyCode == 13) {
			e.preventDefault();
			$(this).closest('form').submit();
		}
	});
	
	/**
	 * Find containers with class="clickable" and make them trigger
	 * the first <a> or <input> inside them.
	 */
	$('.clickable').click(function(e) {
		if (e.triggeredByClickable) return;
		if ($(e.target).closest('a, input, select, button').length > 0) return;
		
		var $elm = $('a[href], input[type=radio], input[type=checkbox], input[type=submit], input[type=button]', this).first();
		if ($elm.length == 0) return;
		
		var event = $.Event('click');
		event.triggeredByClickable = true;
		$elm.trigger(event);
		if (!event.isDefaultPrevented()) {
			if ($elm[0].tagName.toLowerCase() == 'a') {
				if ($elm.attr('target').toLowerCase() == '_blank') {
					window.open($elm.attr('href'));
				} else {
					window.location.href = $elm.attr('href');
				}
			} else {
				switch ($elm.attr('type').toLowerCase()) {
					case 'radio':
					case 'checkbox':
						$elm.attr('checked', 'checked');
						break;
					case 'submit':
						$elm.closest('form').submit();
						break;
				}
			}
		}
	});
	 
	/**
	 * Find elements with with class="cart-submit" and bubble up to
	 * their class="cart-animation-box". The box will be animated
	 * to move from its current position to the container with
	 * class="cart-animation-target".
	 */
	$('.cart-submit').click(function(e) {
		e.preventDefault();
		var $form = $(this).closest('form');
		var $source = $(this).closest('.cart-animation-box');
		var $target = $('.cart-animation-target');
		
		if ($form.length == 0 || this.cfDisabled) return;
		this.cfDisabled = true;
		
		if ($source.length == 1 && $target.length == 1) {
			var $shadow = $('<div>&nbsp;</div>').css({
				backgroundColor: '#ddd',
				border: '1px solid #444',
				position: 'absolute',
				zIndex: '100000',
				opacity: 0.5,
				top: $source.offset().top,
				left: $source.offset().left
			})
			.width($source.css('width')).height($source.css('height'))
			.appendTo('body')
			.animate({
				width: 0,
				height: 0,
				top: $target.offset().top + $target.innerHeight() / 2,
				left: $target.offset().left + $target.innerWidth() / 2
			}, { duration: 300, complete: function() { $shadow.remove(); $form.submit(); } });
		} else {
			$form.submit();
		}
	});
	
	/**
	 * Find containers with class="slideshow" and create a slideshow
	 * from all child elements with class="slide".
	 */
	$('a.slideshow').colorbox({
		current: 'billede {current} af {total}',
		previous: 'forrige',
		next: 'næste',
		close: 'luk'
	});
	
	/**
	 * Find containers with class="hover" and create a popup
	 * from containing elemens with class="hover-popup"
	 */
	$('.hover').hover(
		function() {
			$(this).find('.hover-popup').stop(true, true).animate({opacity: "show"}, "slow");
		},
		function() {
			$(this).find(".hover-popup").animate({opacity: "hide"}, "fast");
		}
	);
	
	/**
	 * Find select input with class="variant-selector",
	 * and use _cfPrice and _cfImg to show selected variant
	 * in 
	 */
	$('.variant-selector').change(
		function() {
			var stock = $(':selected', this).attr('_cfStock');
			var price = $(':selected', this).attr('_cfPrice');
			var before = $(':selected', this).attr('_cfBefore');
			var img = $(':selected', this).attr('_cfImg');
			$(this).closest('form').find('.product-price').html(fmt_price(price));
			if (before) {
				$(this).closest('form').find('.product-before-price').html('Normalpris ' + fmt_price(before));
			} else {
				$(this).closest('form').find('.product-before-price').html('');
			}
			$(this).closest('form').find('.product-stock-left').val(stock);
			if (img) {
				$(this).closest('form').find('.product-images img:first').attr('src', $(this).closest('form').find('.product-images img:first').attr('src').replace(/(\/\d+\/)(variants\/)?[^\/]+$/, '$1') + 'variants' + img);
			}
		}
	).keyup(function() { $(this).change(); }).change();
	
});