/**
 * 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() {

	/**
	 * Show ellipsis (...) where needed.
	 * Note: IE7 can't handle the live flag.
	 * Note: The live flag can also messes with performance.
	 */
	$('.ellipsis').ellipsis();

	/**
	 * Use an a-element to submit a form.
	 */
	$('a.submit').live('click', function() {
		$(this).closest('form').submit();
	});

	/**
	 * Submit a form with enter without a input type="submit" element.
	 */
	$('form input').live('focus', function() {
		$(this).data('cf_inautocomplete', false);
	}).live('keypress', function(e) {
		switch (e.keyCode ? e.keyCode : e.which) {
			case 13:
				if (!$(this).data('cf_inautocomplete') || !$(this).is('input[type=text]') || $.browser.opera) {
					e.preventDefault();
					$(this).closest('form').submit();
				}
				$(this).data('cf_inautocomplete', false);
				break;
			case 33:
			case 34:
			case 38:
			case 40:
				$(this).data('cf_inautocomplete', true);
				break;
			default:
				$(this).data('cf_inautocomplete', false);
		}
	});

	/**
	 * Find containers with class="clickable" and make them trigger
	 * the first <a> or <input> inside them.
	 */
	$('.clickable').live('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.result !== false && !event.isDefaultPrevented()) {
			if ($elm[0].tagName.toLowerCase() == 'a') {
				if (($elm.attr('target') || '').toLowerCase() == '_blank' && $elm.attr('href')) {
					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').live('click', function(e) {
		e.preventDefault();
		var me = this;
		var $form = $(this).closest('form');
		var $source = $(this).closest('.cart-animation-box');
		var $target = $('.cart-animation-target');

		if ($form.length == 0 || me.cfDisabled) return;
		me.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.outerWidth()).height($source.outerHeight())
			.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() { me.cfDisabled = false; $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 to show selected variant
	 */
	$('.variant-selector').change(
		function() {
			var stock = $(':selected', this).attr('_cfStock') || '';
			var price = $(':selected', this).attr('_cfPrice') || 0;
			var before = $(':selected', this).attr('_cfBefore') || 0;
			$(this).closest('form').find('.product-price').html(fmt_price(price));
			if (before) {
				$(this).closest('form').find('.product-before').css('display', 'block');
				$(this).closest('form').find('.product-before-price').html(fmt_price(before));
			} else {
				$(this).closest('form').find('.product-before').css('display', 'none');
				$(this).closest('form').find('.product-before-price').html('');
			}
			$(this).closest('form').find('.product-stock-left').val(stock);
		}
	).keyup(function() { $(this).change(); }).change();


	/**
	 * Find select input with class="variant-selector",
	 * and use _cfImg  to show image for selected variant
	 */
	$('.variant-selector').change(
		function() {
			var img = $(':selected', this).attr('_cfImg');
			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(); });

	/**
	 * Find input fields with a cfdefaultvalue and show that
	 * whenever the fields doesn't have focus.
	 */
	$('input[cfdefaultvalue]').live('focus blur', function(event) {
		var $this = $(this);
		if (event.type == 'focus' || event.type == 'focusin') {
			if ($this.val() == $this.attr('cfdefaultvalue')) $this.val('');
		} else {
			if ($this.val() == '') $this.val($this.attr('cfdefaultvalue'));
		}
	}).blur();
	$('input[data-default-value]').live('focus blur', function(event) {
		var $this = $(this);
		if (event.type == 'focus' || event.type == 'focusin') {
			if ($this.val() == $this.attr('data-default-value')) $this.removeClass('default-value').val('');
		} else {
			if ($this.val() == '') $this.addClass('default-value').val($this.attr('data-default-value'));
		}
	}).blur();

});
