jQuery.cookie = function(name, value, options) {
    if (typeof value != 'undefined') { // name and value given, set cookie
        options = options || {};
        if (value === null) {
            value = '';
            options.expires = -1;
        }
        var expires = '';
        if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
            var date;
            if (typeof options.expires == 'number') {
                date = new Date();
                date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
            } else {
                date = options.expires;
            }
            expires = '; expires=' + date.toUTCString(); // use expires attribute, max-age is not supported by IE
        }
        // CAUTION: Needed to parenthesize options.path and options.domain
        // in the following expressions, otherwise they evaluate to undefined
        // in the packed version for some reason...
        var path = options.path ? '; path=' + (options.path) : '';
        var domain = options.domain ? '; domain=' + (options.domain) : '';
        var secure = options.secure ? '; secure' : '';
        document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
    } else { // only name given, get cookie
        var cookieValue = null;
        if (document.cookie && document.cookie != '') {
            var cookies = document.cookie.split(';');
            for (var i = 0; i < cookies.length; i++) {
                var cookie = jQuery.trim(cookies[i]);
                // Does this cookie string begin with the name we want?
                if (cookie.substring(0, name.length + 1) == (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }
};

jQuery.fn.delegate = function(eventType, rules) {
  return this.bind(eventType, function(e) {
    var target = $(e.target);
    for(var selector in rules)
      if(target.is(selector)) 
        return rules[selector].apply(this, arguments);
  })
};

jQuery.fn.realOffset = function() {
	var that = this[0];
	var x = 0;
	var y = 0;
	do {
		x += that.offsetLeft;
		y += that.offsetTop;
	} while (that = that.offsetParent);
	return {left: x, top: y};
}

jQuery.fn.slideOutRow = function(callback) {
	row = $(this);
	if(row.is('tr'))
	{
		$('td', row).each(function(){
			var el = $(this);
			el.css({
				verticalAlign: 'top'
			});
			var o = $('<span>').addClass('wrap').css({
				display: 'inline-block',
				verticalAlign: 'top',
				overflow: 'hidden'
			});
			var d = $('<span>').addClass('slideOut').css('overflow', 'hidden');
			d.css({
				display: 'inline-block',
				verticalAlign: 'top',
				paddingTop: el.css('paddingTop'),
				paddingBottom: el.css('paddingBottom')
			});
			el.css({
				paddingTop: 0,
				paddingBottom: 0
			});
			d.html(el.html());
			el.html('');
			d.appendTo(o);
			o.appendTo(el);
		});
		
		var t = 0;
		var c = 0;
		
		$('.slideOut', row).each(function(){
			c++;
			$(this).animate({
				marginTop: -row.height(),
				opacity: 0
			}, 300, 'swing', function(){
				row.remove();
				t++;
				if(t==c){
					if(typeof callback != 'undefined')
					{
						callback();
					}
				}
			});
		});
	}
};

function setBasketSummary(number) {
   $('a#basket span.qty').text(number);
}

/* kills jumping to anchors and selecting their content */
$(function() {
	$("a[href^=#]").live('click', function(e) {
		e.preventDefault();
	}).live('selectstart', function(e) {
		e.preventDefault();
	});
});

$(function() {
	
	$(".dropdown > a").click(function(e) {
		var ul = $(this).next("ul");
		ul[ul.is(":hidden")?"slideDown":"fadeOut"]("fast");
		e.preventDefault();
	});
    $("body").delegate("click", {
		":not(.dropdown *)" : function(e) {
			$(".dropdown ul:first").fadeOut("fast");
		}
    });
	// inputs where the label is the value
	
	$('.clever-label input[type=text], .clever-label input[type=password]').cleverlabels();
	
	$('#show-range-bar').click(function(e) {
		e.preventDefault();
		if ($('#range-container #range').length == 0) {
            barLoading(true);
			$("#range-loader img").css('display', 'block').fadeIn();
			$('#range-container').load($(this).attr('href'), function() {
				if(typeof pageTracker != 'undefined') {
					pageTracker._trackEvent('Range Bar', 'Show');
				}
				$(this).slideDown(500, function() {
					setupRangeBar();
					barLoading(false);
				});
			});
		}
		else {
			$.cookie('hide_range_tip', 'true');
			$('#range-container').slideToggle(300);
		}
	});

    $('#show-range-bar').hover(function(){
        if($.cookie('hide_range_tip') != 'true'){
            var elTip = $('#range-bar-tip');
            var elBtn = $(this);
            var elWrap = $('#outer-wrapper');
            elTip.stop(true).show().fadeTo(350,1);
        }
    }, function(){
        $('#range-bar-tip').stop(true).fadeOut();
    });
	
	if($.cookie('search_terms') != null){
		$('#product-search').val($.cookie('search_terms'));
	}
	
	var si = false;
	var ps = false;

	var labelVal = $('#product-search-wrapper label').text();

	$('#product-search').keydown(function(e){
		clearTimeout(si);
	}).keyup(function(e){
		$.cookie('search_terms', $(this).val());
		if($(this).val().length > 2 && $(this).val() != labelVal){
			si = setTimeout(function(){
				if(ps != $('#product-search').val()){
					ps = $('#product-search').val();
					search($('#product-search').val());
				}
			}, (e.keyCode == 13 ? 0 : 500));
		}else if($(this).val().length == 0){
			ps = false;
			closeSearch();
		}
	}).focus(function(e){
		if($(this).val().length > 2 && $(this).val() != labelVal){
			if(ps != $('#product-search').val()){
				ps = $('#product-search').val();
				search($(this).val());
			}
		}
	});
	
	$('body').live('click', function(e){
		if(!$(e.target).is('#product-search, #search-results, #search-results *')){
			ps = false;
			closeSearch();
		}
	});
	
	$('#product-search-wrapper input').cleverlabels();
	
});

function barLoading(show){
	if(typeof show == 'undefined' || show == true){
		$('#range-loader').css('backgroundPosition', '100px 100px');
		$('#range-loader img:not(":visible")').stop(true).css('display', 'block').fadeIn();
	}else{
		$('#range-loader img:visible').fadeOut(function(e){
			$('#range-loader').css('backgroundPosition', '50% 50%');
		});
	}
}

function closeSearch(){
	$('#search-results').fadeOut();
}

function newResult(result){
	var string = '' +
	'<div class="result' + (result.url ? ' clickable-result' : '') + ' clearafter">' +
		(result.image ?
			(result.url ? '<a class="image" href="' + result.url + '">' : '') + result.image + (result.url ? '</a>' : '')
		: '' ) +
		'<div class="info' + (result.image ? ' info-image' : '') + '">' +
			'<p class="title">' + (result.url ? '<a href="' + result.url + '">' : '') + result.title + (result.url ? '</a>' : '') + '</p>' +
			'<p class="desc">' + result.desc + '</p>' +
		'</div>' +
	'</div>';
	var out = $(string);
	if(result.url){
		out.click(function(e){
			window.location = $('a:first', out).attr('href');
		}).hover(function(e){
			$(this).addClass('clickable-result-hover');
		}, function(e){
			$(this).removeClass('clickable-result-hover');
		});
	}
	return out;
}

function search(terms) {
	if(typeof pageTracker != 'undefined') {
		pageTracker._trackEvent('Product Search', 'Search', terms);
	}
	barLoading(true);
	$.post('/search', {
		'search_terms' : terms
	}, function(data){
		barLoading(false);
		if(data.payload.terms == $('#product-search').val()){
			var wrapper = $('#search-results');
			if(!wrapper.is(':visible')){
				wrapper.insertAfter('#product-search-wrapper').fadeIn();
			}
			var results = $('.results', wrapper).empty();
			for(var i in data.payload.results){
				newResult(data.payload.results[i]).appendTo(results);
			}
			if(data.payload.results.length == 1 && data.payload.results[0].url == false){
				if(typeof pageTracker != 'undefined') {
					pageTracker._trackEvent('Product Search', 'No Results', $('#product-search').val());
				}
			}
		}
	}, 'json');
}

function setupRangeBar() {
	var ul = $('#range .images');
	var lozenge = $('#range .lozenge');
	var offset = lozenge.offsetParent().offset();
	var trackwidth = $('#range .labels').outerWidth() - lozenge.outerWidth();
	var imagewidth = $('#range .images').outerWidth() - $('#range .window').innerWidth();
	var pageWidth = 6 / ($('#range .images li').length - 6);
	var currentFraction = 0;
	
	function animatePositions(fraction) {
		dx = Math.abs(fraction - lozenge.position().left / trackwidth);
		if (fraction > 1) fraction = 1;
		if (fraction < 0) fraction = 0;
		currentFraction = fraction;
		ul.stop(true).animate({
			left: -1 * imagewidth * fraction
		}, 300+700*dx, 'easeOutQuad');
		lozenge.stop(true).animate({
			left: fraction * trackwidth
		}, 300+700*dx, 'easeOutQuad');
	}

	function snapPositions(fraction) {
		if (fraction > 1) fraction = 1;
		if (fraction < 0) fraction = 0;
		currentFraction = fraction;
		ul.css({
			left: -1 * imagewidth * fraction
		});
		lozenge.css({
			left: fraction * trackwidth
		});
	}

	$('#range .lozenge, .labels span').drag(function(e) {
		lozenge.addClass('active');
	},function(e) {
		if(e.offsetX > offset.left + trackwidth){
			snapPositions(offset.left + trackwidth);
		}else if (e.offsetX > offset.left){
			snapPositions((e.offsetX - offset.left) / trackwidth);
		}else{
			snapPositions(0);
		}
	},function(e) {
		lozenge.removeClass('active');
	});
	

	$('#range').delegate('click', {
		'.labels span' : function(e) {
			left = ($(e.target).position().left - 19) / trackwidth;
			animatePositions(left);
		},
		'.labels' : function(e) {
			left = (e.pageX - offset.left - lozenge.outerWidth()/2) / (trackwidth);
			animatePositions(left);
		},
		'.slider' : function(e) {
			if (e.pageX > offset.left + trackwidth / 2 ) left = currentFraction + pageWidth;
			else left = currentFraction - pageWidth;
			animatePositions(left);
		}
	});
}
/*
function setupAjaxForm(form, url){
	var timer = false;
    $(form).ajaxForm({
        url: url,
		target: form,
        success: function(response){
			if (timer) {
				clearTimeout(timer);
				timer = false;
			}
            setupAjaxForm(form, url);
        },
		beforeSubmit: function() {
			if (timer) {
				return false;
			}
			timer = setTimeout("$('" + form + " button').addClass('button-loading')", 300);
		}
    });
}*/


