// Fire up the JS
var base = function($){

	// Cufon (lives outside the $(document).ready() block, but in its own function
	// so we can call it easily again.
	var cufon = function() {
		Cufon.replace('#nav-main>ul>li>a,#nav-featured>div.featured>a,h3>a,#feature-links>a', {hover: true});
		Cufon.replace('h1,h2,h3');
	};
	cufon();

	$(function(){

		// Galleries
		$('.gallery a.gallery-image:first-child').clone()
			.html('View gallery')
			.css({margin: '10px 0 20px 0', display: 'block'})
			.removeClass('gallery-image')
			.attr('rel','')
			.addClass('more')
			.insertAfter('.gallery')
			.click(function(){
				$('.gallery a.gallery-image:first-child').click();
				return false;
			});
		$('.gallery:not(.no-cycle)').cycle({});
		$('.gallery a.gallery-image').fancybox({
			cyclic: true,
			padding: 5,
			overlayOpacity:0.9,
			overlayColor:'#000',
			titlePosition: 'inside',
			titleFormat: function(title,els,n) {
				return $('<div>').css({'text-align': 'left', margin: '10px 0', color: '#000'}).append('Image ' + (n+1) + ' of ' + els.length + ': ' + title);
			}
		});
		$('.gallery a.thumbnail').fancybox({
			padding: 5,
			overlayOpacity:0.9,
			overlayColor:'#000',
			titlePosition: 'inside',
			titleFormat: function(title,els,n) {
				return '';
			}
		});

		// Faq list
		$('#content-blocks-faq').each(function(){
			$(this).find('a.title').css({cursor:'pointer'}).click( function() {
				if($(this).hasClass('selected'))
				{
					$(this).removeClass('selected');
					$(this).parent().find('ul.list').slideUp();
				}
				else
				{
					$(this).addClass('selected');
					$(this).parent().find('ul.list').slideDown();
				}
				
			});
			$(this).find('ul.list').hide();
		});

		// Form field labels in the function area
		$('#function-area label').css({
				color: '#6D6E70',
				position : 'absolute',
				left : '26px',
				margin : '4px 0 0 0'
		}).each(function(){
				if ( $('#' + $(this).attr('for')).val() != '') {
						$(this).hide();
				}
		});

		var functionInput = $('#function-area input, #function-area textarea').focus(function(){
				$('label[for=' + $(this).attr('id') + ']').hide();
		});
		functionInput.blur(function(){
				if ($(this).val() == ''){
						$('label[for=' + $(this).attr('id') + ']').show();
				}
		});

		// Setup the menus
		$('#nav-featured>div.featured>a, #nav-main>ul>li>a').css('background-color', 'transparent');
		$('#nav-featured>div.featured, #nav-main>ul>li')
		.css({backgroundPosition : '0 0'})
		.hover(function(){
			$(this)
			.addClass('hover')
			.stop(false, true).animate({backgroundPosition: "(0 -158px)"}, {duration: 200})
			.find('>ul, >div').stop(false, true).slideDown(200);
			
		}, function(e) {
			//console.log(e.target);
			//console.log($(e.target).is('input'));
			if ( $(this).find('input.focus').length < 1 ) {
				$(this)
				.removeClass('hover')
				.stop(false, true).animate({backgroundPosition: "(0 0)"}, {duration: 200})
				.find('>ul, >div').stop(false, false).fadeOut(200, function(){
					$(this).height('auto'); // Reset the styles since we stopped the animation early.
				});
				cufon();
			}
		});
		$('#nav-main>ul>li:last-child>ul').css('right', 0);


		$('#nav-store-locator input[type=text], #SearchForm_SearchForm_Search').focus(function(){$(this).addClass('focus')});
		$('#nav-store-locator input[type=text], #SearchForm_SearchForm_Search').blur(function(){$(this).removeClass('focus')});

		// Improve the look and feel of the search form slightly
		var $search_icon = $('<img class="icon-search" src="http://www.coffeeclub.com.au/themes/thecoffeeclub/images/icon-search.png" alt="Action: Search"/>');
		$search_icon.click(function(){
			$(this).parents('form').submit();
		});
		$('#SearchForm_SearchForm_action_results').replaceWith($search_icon);

		// Search background fade
		$('#SearchForm_SearchForm_Search').css({backgroundPosition: '0 0'}).hover(
			function() {
				$(this).stop(false, true).animate({backgroundPosition: "(0 -158px)"}, {duration: 400})
			},
			function () {
				if (!$(this).hasClass('focus')){
					$(this).stop(false, true).animate({backgroundPosition: "(0 0)"}, {duration: 300})
				}
			}
		).blur(function(){
			$(this).stop(false, true).animate({backgroundPosition: "(0 0)"}, {duration: 300})
		});

		// Try not to submit an empty search form, yeah?
		$('#SearchForm_SearchForm').submit(function() {
			if ( $('#SearchForm_SearchForm_Search').val().length < 1 ) {
				return false;
			}
			return true;
		});

		// Home page (take 2)
		if ( $('#features').length > 0 ) {
						
			if ($.browser.msie) {
				$('#feature-links a').each(function(){
					var $this = $(this);

					var $div = $('<div>').css({
						height : $this.outerHeight(),
						width : $this.outerWidth(),
						position : 'absolute',
						background : '#000',
						left : $this.position().left-6,
						top : $this.position().top-4,
						"z-index" : $this.css('z-index')-1
					});

					$div.insertBefore(this);
				});
			}
			
			$('#features').cycle({
				pager:  '#feature-links',
				pagerAnchorBuilder: function(idx, slide) {
					// return selector string for existing anchor
					return '#feature-links a:eq(' + idx + ')'; 
				},
				pauseOnPagerHover : true,
				pagerEvent: 'mouseover',
				allowPagerClickBubble: true,
				updateActivePagerLink : function (x,idx,activeClass) {
					var $link = $('#feature-links a:eq(' + idx + ')');
					var $shadow = $link.prev('div');

					// Reset other links and shadows
					$('#feature-links a').removeClass(activeClass);
					$('#feature-links div').css({height: $link.outerHeight(), top: $link.position().top-4}).removeClass(activeClass);

					// Move it along
					$link.addClass(activeClass);
					$shadow.css({height: $link.outerHeight(), top: $link.position().top-4}).addClass(activeClass);

				}
			});

			$('#person').hover(
				function () {
					if ($.browser.msie) {
						$('#speech-bubble').show();
						return;
					}
					$('#speech-bubble').stop(false, true).fadeIn();
				},
				function () {
					if ($.browser.msie) {
						$('#speech-bubble').hide();
						return;
					}
					$('#speech-bubble').stop(false, true).fadeOut();
				}
			);
		}

		// Generate the prettier file input
		$('input[type=file]').each(function(){
				var $input = $(this);
				var $related = $('<input id="browseFileName" name="browseFileName" type="text" readonly class="text"/>');
				var $container = $('<span class="file"><img src="/themes/thecoffeeclub/images/button-browse.gif" alt="browse"/></span>');

				$input.change(function() {
						var filestring = $(this).val();
						if (filestring.indexOf('\\') > 0) {
								// Trim it down if we have a path.
								filestring = filestring.substr(filestring.lastIndexOf('\\') + 1);
						}

						$related.val(filestring);
				});

				$container.prepend($related).insertAfter($input);
				$input.css({'opacity':0, cursor: 'pointer'});
		});

		// Cycle the banner images
		$('#img-banner img').css({height: '200px', width: '730px'}); // Atempted bug fix.
		$('#img-banner').cycle();

		// Drink selector
		if ( $('#function-area.HowAreYouFeeling').length ) {
			// Add select box
			var $select = $('<select>').append('<option>Select a feeling...</option>');
			$('#function-area.HowAreYouFeeling .select a').each(function(){
				var $this = $(this);
				$select.append($('<option>').val($this.attr('href')).text($this.text()).attr('selected', (window.location.hash == $this.attr('href').substr($this.attr('href').indexOf('#'))) ? 'selected' : ''));
			});
			$('#function-area.HowAreYouFeeling .select').replaceWith($select);

			$('#function-area.HowAreYouFeeling select').change(function() {
				window.location = $('#function-area.HowAreYouFeeling select').val();
				$('#categories-menu .' + window.location.hash.substr(1) + ' a').click();
			});
			
		}

		// Menu filtering
		$('#categories-menu a').click(function() {

			// Make this a jQuery object
			var $this = $(this);

			// Find the URLSegment of the category selected.
			var URLSegment = $this.attr('href').substr($this.attr('href').indexOf('#')+1);

			// Swap visible category in content panel
			$('#categories-menu a').removeClass('current');
			$this.addClass('current');                        
			$('.menu-category:not(#category-' + URLSegment + ')').slideUp('fast');
			$('#category-' + URLSegment).slideDown('fast');

			// Swap visible category image
			$('.gallery>div:not(#category-image-' + URLSegment + ')').fadeOut();
			$('#category-image-' + URLSegment).fadeIn();
			
			// Temporarily change the ID so we can change the hash
			var $target = $('#category-' + URLSegment).attr('id', 'tmp-id');
			window.location.hash = 'category-' + URLSegment;
			$target.attr('id', 'category-' + URLSegment);
			return false;
		});

		$('.gallery.no-cycle>div').css('position', 'absolute').hide();
		if (window.location.hash.length > 0) {
			$('#categories-menu .' + window.location.hash.substr(10) + ' a').addClass('current');
			$('.menu-category:not(' + window.location.hash + ')').hide();
			$('#category-image-' + window.location.hash.substr(10)).show();
		} else {
			$('#categories-menu :first-child a').addClass('current');
                        // $('.menu-category:not(:first-child)').hide();
                        $('.menu-category').hide();
                        $('.menu-category:first').show();
			$('.gallery>div:first-child').show();
		}
		

		// Equal heights for chefs corner features
		var tallest = 0;
		var $row = $([]);
		$('.PageChefsCorner div.feature').css({display: 'block', position: 'relative'}).each(function() {
			var $this = $(this);
			
			$row = $row.add(this);

			if ($this.height() > tallest) {
				tallest = $this.height();
			}

			if ($this.hasClass('col-2')) {
				$row.height(tallest);
				tallest = 0;
				$row = $([]);
			}
		});
		$row.height(tallest);
		$('.PageChefsCorner div.feature a').css({position: 'absolute', bottom: '0' , left: '0'});

	});

	// Some public functions that are used site wide.
	return {
		invalidHandler : function(e, validator) {
			var errors = validator.numberOfInvalids();
			if (errors) {

				if ( !$('form p.error').length ) {
					$('<p class="message error">').hide().prependTo(validator.currentForm);
				}

				var message = errors == 1
						? "You missed 1 field. It has been highlighted below"
						: "You missed " + errors + " fields.  They have been highlighted below.";
				$("form p.error").html(message).show();
			} else {
				$("form p.error").remove();
			}
		},
		invalidHandlerEOI : function(e, validator) {
			var errors = validator.numberOfInvalids();
			if (errors) {

				if ( !$('form p.error').length ) {
					$('<p class="message error">').hide().prependTo(validator.currentForm);
				}

				var message = errors == 1
						? "There was an error with 1 field highlighted below."
						: "There was an error with " + errors + " fields highlighted below.";
				$("form p.error").html(message).show();
			} else {
				$("form p.error").remove();
			}
		}
	}

}(jQuery);


// Some help with HTML5 for browsers who need it.
// html5shiv MIT @rem remysharp.com/html5-enabling-script
// iepp v1.5.1 MIT @jon_neal iecss.com/print-protector
/*@cc_on(function(p,e){var q=e.createElement("div");q.innerHTML="<z>i</z>";q.childNodes.length!==1&&function(){function r(a,b){if(g[a])g[a].styleSheet.cssText+=b;else{var c=s[l],d=e[j]("style");d.media=a;c.insertBefore(d,c[l]);g[a]=d;r(a,b)}}function t(a,b){for(var c=new RegExp("\\b("+m+")\\b(?!.*[;}])","gi"),d=function(k){return".iepp_"+k},h=-1;++h<a.length;){b=a[h].media||b;t(a[h].imports,b);r(b,a[h].cssText.replace(c,d))}}for(var s=e.documentElement,i=e.createDocumentFragment(),g={},m="abbr article aside audio canvas details figcaption figure footer header hgroup mark meter nav output progress section summary time video".replace(/ /g, '|'),
n=m.split("|"),f=[],o=-1,l="firstChild",j="createElement";++o<n.length;){e[j](n[o]);i[j](n[o])}i=i.appendChild(e[j]("div"));p.attachEvent("onbeforeprint",function(){for(var a,b=e.getElementsByTagName("*"),c,d,h=new RegExp("^"+m+"$","i"),k=-1;++k<b.length;)if((a=b[k])&&(d=a.nodeName.match(h))){c=new RegExp("^\\s*<"+d+"(.*)\\/"+d+">\\s*$","i");i.innerHTML=a.outerHTML.replace(/\r|\n/g," ").replace(c,a.currentStyle.display=="block"?"<div$1/div>":"<span$1/span>");c=i.childNodes[0];c.className+=" iepp_"+
d;c=f[f.length]=[a,c];a.parentNode.replaceChild(c[1],c[0])}t(e.styleSheets,"all")});p.attachEvent("onafterprint",function(){for(var a=-1,b;++a<f.length;)f[a][1].parentNode.replaceChild(f[a][0],f[a][1]);for(b in g)s[l].removeChild(g[b]);g={};f=[]})}()})(this,document);@*/

