/* spread the occasions menu out to fill the width of the page, and equalize heights in it */
$(document).ready(function() {
	// spread 'em out:
	var occasionswidth=$('#categories').width();
	// only direct children of #categories, not the nested LIs
	var categories=$('#categories > ul > li > a');
	var total_width = 0;
	targetwidth=Math.floor((occasionswidth-((categories.length)+1))/(categories.length));
	categories.each(function() {
		$(this).width(targetwidth);
		total_width += targetwidth;
	});

	var missing = occasionswidth-total_width;
	if(missing!=0){
		var last = $(categories).last();
		last.width(missing+last.width()-(categories.length+1));
	}
	// equalize heights:
	categories.equalHeights();
	// and expand #o's height to match
	$('#o').height($('#categories > ul > li.first').height());
});


/* nivo-slider (hero images on homepage) */
if (typeof(noslider)!=='undefined' || ($.browser.msie && $.browser.version<7)) {
	// Slider causes major layout issues in IE6. Since a relatively small number of people use IE6 (and ought to upgrade since it's two versions old now) we're dropping the slide as it's not essential to use the site.
}
else $(document).ready(function() {
	//alert('slider length: '+$('#slider').length);
	if ($('#slider').length>0) {
		$('#slider').nivoSlider({
			effect:'fade', //Specify sets like: 'fold,fade,sliceDown'
			slices:1, // default 15 - only need one for the fade effect
			/*animSpeed:500,*/
			pauseTime:5000, // default 3000
			/*startSlide:0, //Set starting Slide (0 index)*/
			directionNav:false, //Next & Prev. Default is 'true'
			/*directionNavHide:true, //Only show on hover*/
			controlNav:false, //1,2,3... Default is 'true'
			/*controlNavThumbs:false, //Use thumbnails for Control Nav
			controlNavThumbsFromRel:false, //Use image rel for thumbs
			controlNavThumbsSearch: '.jpg', //Replace this with...
			controlNavThumbsReplace: '_thumb.jpg', //...this in thumb Image src*/
			keyboardNav:false, //Use left & right arrows. Fires when using the arrow keys ANYWHERE (e.g. in a form input)
			/*pauseOnHover:true, //Stop animation while hovering
			manualAdvance:false, //Force manual transitions*/
			captionOpacity:1 //Universal caption opacity
			/*beforeChange: function(){},
			afterChange: function(){},
			slideshowEnd: function(){} //Triggers after all slides have been shown*/
		});
		if ($.browser.msie && $.browser.version==7) {
			// IE7 doesn;t allocate space for the hero for some reason, but does know how tall it is, so expand #b by that much.
			// the problem seems to have gone away... But I'm keeping this code in case it comes back
			// use jQuery's outerheight(true) rather than height, to count margins.
			var sidebarheight=$('#sidebar').outerHeight(true);
			var contentheight=$('#content').outerHeight(true);
			
			// seems it only happens when #content is shorter than #sidebar
			if (sidebarheight>contentheight) {
				var bheight=$('#b').outerHeight(true);
				
				// IE7 doesn't get the correct height for #b... Use the tallest of it, #sidebar and #content
				var bheight=Math.max(bheight,sidebarheight,contentheight);
				
				var heroheight=$('#hero').outerHeight(true);
				
				var targetheight=bheight+heroheight;
				$('#b').height(targetheight);
				
			} // end if (sidebarheight>contentheight)
		}
		
	} // end if ($('#slider').length>0)
});


// handle onfocus/blur removal/replacement of text in search input. But only if currently holding the default text or blank
$(document).ready(function() {
	var input=$('#quick-search .text');
	var defaultsearchtext='Search here ...';
	input.focus(function() {
		if ($(this).val()==defaultsearchtext) {
			$(this).val('');
		}
		else $(this).select();
	})
	input.blur(function() {
		if ($(this).val()=='') {
			$(this).val(defaultsearchtext);
		}
	})
});


// show/hide of collections on mouseover/out of categories list
if ($.browser.msie && $.browser.version<7) {
	// This doesn't work properly in IE6. Since a relatively small number of people use IE6 (and ought to upgrade since it's two versions old now) we're dropping the subnav as it's not essential to use the site.
}
else $(document).ready(function() {
	function show() {
		var menu = $(this);
		menu.find(".collections").fadeIn();//slideDown();
	}
	function hide() { 
		var menu = $(this);
		menu.find(".collections").fadeOut();//slideUp();
	}
	$("#categories li").hoverIntent({
		sensitivity: 1, // number = sensitivity threshold (must be 1 or higher)
		interval: 50,   // number = milliseconds for onMouseOver polling interval
		over: show,     // function = onMouseOver callback (required)
		timeout: 300,   // number = milliseconds delay before onMouseOut
		out: hide       // function = onMouseOut callback (required)
	});
});


// Make the tiled background of <body> line up neatly with the same tiled background on #ff
$(document).ready(function() {
	var bodyheight=$("body").height();
	var discrepancy=bodyheight%31; // body's baseline overhangs a tile by this much
	// if we move body's background to here, it'll still be a bit below the start of the last repetition of #ff's bg
	// need to subtract the mod of #ff's height over the tile size
	var ffheight=$("#ff").outerHeight(); // use outerHeight because we need to include the padding
	var discrepancy2=ffheight%31; // #ff's baseline overhangs a tile by this much
	discrepancy=discrepancy-discrepancy2;
	$('body').css('background-position','left '+discrepancy+'px')
});


// look for anchors with href and rel="external", and add target="_blank" to them so that they open in a new window
$(document).ready(function() {
// from http://articles.sitepoint.com/article/standards-compliant-world/3
	if (!document.getElementsByTagName) return;  
	var anchors = document.getElementsByTagName("a");  
	for (var i=0; i<anchors.length; i++) {  
		var anchor = anchors[i];  
		if (anchor.getAttribute("href") && anchor.getAttribute("rel") == "external") anchor.target = "_blank";
	}  
});

/* attach the fancybox overlay to links in #products */
$(document).ready(function() {
	//table.cart a.product
	$("#products a").fancybox({
		'titleShow'			: false,
		'titlePosition'		: 'inside',
		'overlayOpacity'	: 0.7,
		'overlayColor'		: '#ffffff',
		'height'			: 1 /* without this specified, fancybox seems unable to accomodate content taller than some particular height */
	});
});

/* attach the fancybox overlay to "add to basket" forms */
$(document).ready(function() {
	bindtoaddtobasket();
});
function bindtoaddtobasket() {
$(".addtobasket").unbind("submit.group1"); // unbind the already-bound handler before adding in, otherwise we get (n+1) additions, where n is the number of times the product "detail" overlay has been opened. See http://api.jquery.com/bind/#comment-67646923
$(".addtobasket").bind("submit.group1", function() {
	$.fancybox.showActivity();

	$.ajax({
		type	: "POST",
		cache	: false,
		url		: "/add-to-basket/",
		data	: $(this).serializeArray(),
		success	: function(data) {
			$.fancybox(data, {
				onClosed : function(){
					// update the "quick basket" area in the header
					$('#quick-basket').load('/quick-basket/');
				}	
			});
			$('.close_modal').bind('click', function(){
				$.fancybox.close();
				return false;
			});
		}
	});

	return false;
});
} // end function bindtoaddtobasket


$(document).ready(function(){
	if($('#checkout_details #country_iso2')) {
		$('#checkout_details #country_iso2').bind(
			'change',
			function () {
				if(this.value == 'US') {
					$('#checkout_details #countyContainer').hide();
					$('#checkout_details #usStateContainer').show();
					$('#checkout_details #county').removeClass('require');
					$('#checkout_details #us_state').addClass('require');

				}
				else if($('#checkout_details #countyContainer').css('display')!='block') {
					$('#checkout_details #countyContainer').show();
					$('#checkout_details #usStateContainer').hide();
					$('#checkout_details #county').addClass('require');
					$('#checkout_details #us_state').removeClass('require');
				}
				
				$('#checkout_details #us_state').val($('#checkout_details #county').val());
			}
		);
		if($('#checkout_details #usStateContainer').css('display')=='block') {
			$('#checkout_details #us_state').addClass('require');
			$('#checkout_details #county').removeClass('require');
		}

		//Force the country change event when the Postcode Anywhere select is clicked		
		$('#pcaSelectKB91').live('click select change', function(){
			setTimeout("$('#checkout_details #country_iso2').change()", 500);
		});
	}

	if($('#checkout_details #del_country_iso2')) {
		$('#checkout_details #del_country_iso2').bind(
			'change',
			function () {
				if(this.value == 'US') {
					$('#checkout_details #delCountyContainer').hide();
					$('#checkout_details #delUsStateContainer').show();
					$('#checkout_details #del_county').removeClass('require');
					$('#checkout_details #del_us_state').addClass('require');
				}
				else if($('#checkout_details #delCountyContainer').css('display')!='block') {
					$('#checkout_details #delCountyContainer').show();
					$('#checkout_details #delUsStateContainer').hide();
					$('#checkout_details #del_county').addClass('require');
					$('#checkout_details #del_us_state').removeClass('require');
				}
				
				$('#checkout_details #us_state').val($('#checkout_details #del_county').val());
			}
		);
		
		if($('#checkout_details #delUsStateContainer').css('display')=='block') {
			$('#checkout_details #del_us_state').addClass('require');
			$('#checkout_details #del_county').removeClass('require');
		}
		
		//Force the delivery country change event when the Postcode Anywhere select is clicked		
		$('#pcaSelectAE99').live('click select change', function(){
			setTimeout("$('#checkout_details #del_country_iso2').change()", 500);
		});
	}
	
	$('select#how_did_you_hear').bind('change', function(){
		howDidYouHear($(this).val());
	});
	
	howDidYouHear($('select#how_did_you_hear').val());
});

function howDidYouHear(val){
	if(val == 'other'){
		$('#how_did_you_hear_other').parent().show();
	} else {
		$('#how_did_you_hear_other').parent().hide();	
	}	
}

/**
 * Equal Heights Plugin
 * Equalize the heights of elements. Great for columns or any elements
 * that need to be the same size (floats, etc).
 * 
 * Version 1.0
 * Updated 12/10/2008
 *
 * Copyright (c) 2008 Rob Glazebrook (cssnewbie.com) 
 *
 * Usage: $(object).equalHeights([minHeight], [maxHeight]);
 * 
 * Example 1: $(".cols").equalHeights(); Sets all columns to the same height.
 * Example 2: $(".cols").equalHeights(400); Sets all cols to at least 400px tall.
 * Example 3: $(".cols").equalHeights(100,300); Cols are at least 100 but no more
 * than 300 pixels tall. Elements with too much content will gain a scrollbar.
 * 
 * 
 * TJS revision 1.1
 * 2010-06-14
 * Solves the problem of height-matching an element that has padding and/or border, with one that has no padding and/or border. 
 * It inspects the outerHeight rather than the height, but adjusts only the height by whatever shortfall was found.
 */

(function($) {
	//console.log('Defining equalHeights function');
	$.fn.equalHeights = function(minHeight, maxHeight) {
		tallest = (minHeight) ? minHeight : 0;
		this.each(function() {
			if($(this).outerHeight() > tallest) {
				tallest = $(this).outerHeight();
			}
		});
		if((maxHeight) && tallest > maxHeight) tallest = maxHeight;
		return this.each(function() {
			shortfall=tallest-$(this).outerHeight();
			targetheight=$(this).height()+shortfall;
			$(this).height(targetheight).css("overflow","auto");
		});
	}
})(jQuery);
