(function( $ ){
/* Pagination */
$.fn.simplePaginate = function() {
	function init(el) {
		el.current = 0;
		el.boxHeight = $("ul",el).height();
		el.boxItems = $("li", el).size();
		el.itemHeight = $("li:last",el).addClass("last").outerHeight(true);
		el.maxPage = Math.ceil(el.boxItems/3);
		el.padItems = (el.maxPage*3) - el.boxItems;
		$("ul", el).css("overflow","hidden");
		for(true;el.padItems>0;el.padItems--)
			$("<li/>").addClass("blank").html("&nbsp;").appendTo( "ul", el );
		$(".less").click(function(e){
			e.preventDefault();
			prevPage(el);
		});
		$(".more").click(function(e){
			nextPage(el);
			e.preventDefault();
		});
	};
	function nextPage(el) {
		if ( el.current >= el.maxPage-1 )
		    return;
		slideTo(el,++el.current);
	};
	function prevPage(el){
		if ( el.current <= 0 )
		    return;
		slideTo(el,--el.current);
	};
	function slideTo(el, num){
	    if ( num < 0 || num >= el.maxPage )
	        return;
	    $(".deadend",el).removeClass("deadend");
	    
	    if ( num >= el.maxPage-1 )
	        $(".more", el).addClass("deadend");
		if ( num <= 0 )
		    $(".less", el).addClass("deadend");
		$("ul",el).animate({
			scrollTop: num * el.boxHeight
		},900);
	};
	$.each(this,function(i,d){
		init(d);
	});
};
/* Contact Form */
$.fn.contactForm = function() {
	function init(el) {
		var fields = [
			["name", "Name", 3],
			["email", "Email", 5, true],
			["message", "Message", 5]
		];
		$.each(fields,function(i,d){
			holdText(el, d);
		});
		$(el).submit(function(e){
			e.preventDefault();
			submitContact(el, fields);
		});
	};
	function holdText( el, opts ){
		$("."+opts[0]).val(opts[1]).focus(function(){
			if ( $(this).val() == opts[1] )
			    $(this).val('');
		}).blur(function(){
			if ( $(this).val().length == 0 )
			    $(this).val(opts[1]);
		});
	};
	function doMessage( el, message, ok ) {
	    console.log( "Message: " + message );
		ok = ok || false;
		if ( $(".Message",el).size() > 0 ) {
			$(".Message",el).fadeOut("slow",function(){
				$(this).removeClass("m-ok").removeClass("m-error").addClass( ok ? "m-ok" : "m-error" ).html( message ).fadeIn("slow");
			});
		} else {
			$("<div/>").addClass("Message").addClass( ok ? "m-ok" : "m-error" ).html(message).fadeIn("slow").prependTo(el);
		}
		return false;
	};
	function submitContact(el, fields) {
		var error = false;
		var inputs = [];
		$.each(fields, function(i,d){
			var field = $("."+d[0],el).val();
			if ( field.length < d[2] || field == d[1] ) {
				error = true;
				$("."+d[0],el).focus();
			    return doMessage( el, "Please enter your " + d[1] + "!", false );
			}
            var emailreg = /^([^@]+)\@([A-Za-z0-9_\-\.]+)\.([A-Za-z]{2,4})$/;
			if ( d[3] && !field.match(emailreg) ) {
				error = true;
				$("."+d[0],el).focus();
			    return doMessage( el, "Please enter a valid email address!", false );
			}
			inputs.push( d[0] + "=" + $('<div/>').text(field).html() );
		});
		if ( !error && !$("#agreement").is(":checked") ) {
			error = true;
			return doMessage( el, "Please agree to the ToS and Privacy Policy!", false);
		}
		if ( !error ){
		    $(":input",el).attr("disabled","disabled").addClass("disabled");
			$.ajax({
	            type: "POST",
	            url: "/wp-content/themes/bossa_nova/ajax/contact.php?_=?",
	            cache: false,
	            timeout: 10000,
	            data: inputs.join("&"),
	            dataType: "jsonp",
	            success: function(data){
	                if ( data && data.message )
						doMessage(el, data.message, data.success );
	                else
						doMessage(el, "An error occurred, please try again!", false );
	            },
	            error: function(data) {
					doMessage(el, "An error occurred, please try again!", false );
				}
	        });
		}
	};
	$.each(this,function(i,d){
		init(d);
	});
};
/* Homepage Slider */
$.fn.homepageTout = function() {
	function init(el) {
		el.total = $('li',el).size();
		el.currentPos = 0;
		el.pause = false;
		el.timeout = 7000;
		el.itemWidth = $(window).width();

		/* Indicators */
		$("li",el).each(function(i,d) {
			$(d).css({
				"left": el.itemWidth*2,
				"width": el.itemWidth
			}).animate({"left": i * el.itemWidth},900).show();
		    $("<a/>").attr("href","#").click(function(e){
				selectSlide(el, i);
				e.preventDefault();
			}).appendTo("#Indicators");
		});
		$("a:first", "#Indicators").addClass("active");
		
		/* Pause on hover */
		$(el).parent().hover(function(){
			el.pause = true;
		},function(){
			el.pause = false;
		});
		
		/* Bind keys */
		$(window).bind("keydown",function(e){
			switch(e.keyCode){
				case 37:
					prevSlide(el, true);
					e.preventDefault();
				break;
				case 39:
					nextSlide(el, true);
					e.preventDefault();
				break;
			}
		});

		/* Bind arrows */
		$("a.next","#ArrowContainer").click(function(e){
			nextSlide(el,true);
			e.preventDefault();
		});
		$("a.prev","#ArrowContainer").click(function(e){
			prevSlide(el,true);
			e.preventDefault();
		});
		/* Initial routine */
		setTimeout(function(){
			initTimer(el);
		}, 5000);
	};
	function initTimer(el) {
		clearTimeout(el.timer);
		el.timer = setTimeout(function(){
			nextSlide(el);
		}, el.timeout);
	};
	function nextSlide(el) {
		selectSlide(el, (el.currentPos >= el.total-1 ? 0 : el.currentPos + 1))
	};
	function prevSlide(el) {
		if ( el.pause )
		    return;
		el.pause = true;
	    $("li",el).eq(el.currentPos).animate({
			"left": el.itemWidth
		}, 900,function(){ $(this).hide(); });
		el.currentPos = el.currentPos <= 0 ? el.total - 1 : el.currentPos - 1;
		$("li",el).eq(el.currentPos).show().css("left",-el.itemWidth).animate({
			"left": 0
		}, 900,function(){
			el.pause = false;
		});
		updateIndicator(el);
	};
	function selectSlide( el, nextPos ) {
	    initTimer(el);
		if ( el.currentPos == nextPos || el.pause )
		    return;
		el.pause = true;
        $("li",el).eq(el.currentPos).animate({
			"left": -el.itemWidth
		}, 900,function(){ $(this).hide(); });
		el.currentPos = nextPos;
		$("li",el).eq(el.currentPos).show().css("left",el.itemWidth).animate({
			"left": 0
		}, 900, function(){ el.pause = false; });
		updateIndicator(el);
	};
	function updateIndicator( el ) {
		$("a","#Indicators").removeClass("active").eq(el.currentPos).addClass("active");
	};
	$.each(this,function(i,d){
		init(d);
	});
};
$.fn.tabManager= function() {
	function init(el) {
		$(".SuperfruitTab").hide();
		$("a",el).click(function(e){
			enableTab(el, this.href);
			e.preventDefault();
		});
		if ( window.location.hash.length > 0 ) {
			enableTab(el, getHash());
		}
		if ( $(".SuperfruitTab:visible").size() == 0 ){
			$(".SuperfruitTab:first").show();
		}
		
		el.timer = setInterval(function(){ checkHistory(el); }, 100);
	};
	function enableTab(el,loc) {
		if ( loc.indexOf("#") != -1 ) {
			var tab = loc.split("#")[1];
			if ( $("#" + tab).size() > 0 ) {
				window.location.hash = tab;
				$('.SuperfruitTab').hide();
				$( "#" + tab ).show();
				$(".active", el).removeClass("active");
				$("a."+tab.toLowerCase(), el).addClass("active");
			}
		}
	};
	function checkHistory(el) {
		if ( getHash() != el.current ) {
		    el.current = getHash();
			enableTab( el, getHash());
		};
	};
	function getHash( url ) {
    	url = url || location.href;
    	return '#' + url.replace( /^[^#]*#?(.*)$/, '$1' );
	};
	$.each(this,function(i,d){
		init(d);
	});
};
$.fn.questionSlider = function() {
	function init(el) {
	    $("p",el).removeClass("open").removeClass("closed").hide();
		$("h3",el).css("cursor","pointer").click(function(e){
		    var elem = $(this).parent();
		    var item = elem.find("p");
		    if ( item.is(":hidden") )
				openSlide(el,item,elem);
			else
				closeSlide(el,item,elem);
			e.preventDefault();
		});
		$("h3").eq(0).click();
	};
	function openSlide(el,item,elem) {
		item.removeClass("closed").slideDown("slow");
        elem.find("a").addClass("FaqArrowUp");
	};
	function closeSlide(el,item,elem) {
		elem.find("a").removeClass("FaqArrowUp");
		item.removeClass("open").slideUp("slow");
	};
	$.each(this,function(i,d){
		init(d);
	});
};

/* Product Slider */

$.fn.productSlider = function() {
	function init(el) {
		$(window).bind("keydown",function(e){
			switch(e.keyCode){
				case 37:
					prevBottle(el);
					e.preventDefault();
				break;
				case 39:
					nextBottle(el);
					e.preventDefault();
				break;
				case 13:
					moreDetails(el);
					e.preventDefault();
				break;
				case 27:
					closeDetails(el);
					e.preventDefault();
				break;
			}
		});
		$("a.moreinfo",el).click(function(e){
			moreDetails(el);
			e.preventDefault();
		});
		$(".tag").click(function(e){
			if ( $(this).parent().hasClass('heroBottle') )
				moreDetails(el);
		});
		$(".bottle32").click(function(e){
			moreDetails(el);
		});
		$(".bottle",el).live("click", function(e){
			selectBottle(el, $(this).parent());
		});
		$("a.closeIcon",el).click(function(e){
		    closeDetails(el);
			e.preventDefault();
		});
		$("a.next","#ArrowContainer").click(function(e){
			nextBottle(el);
			e.preventDefault();
		});
		$("a.prev","#ArrowContainer").click(function(e){
			prevBottle(el);
			e.preventDefault();
		});
		$(".tag10").click(function(e){
			changeBottle10(el, this);
			e.preventDefault();
		});
 		$(".tag32").click(function(e){
			changeBottle32(el, this);
			e.preventDefault();
		});

		/* Sizing */

		el.rw = $('.regularBottle', el).width();
		el.heroBottle = {
			"bottle": {"left": -30, "top": 50, "width": 426, "height": 466},
			"tag": {"top": 10, "left": 290, "width": 116, "height": 114},
			"moreinfo":{"opacity":1},
			"stag":{"opacity":1},
			"tag32":{"opacity":"0.7"},

			"acai": {"top": 430, "left": 195, "height": 89},
			"mangosteen": {"top": 375, "left": 190, "height": 129},
			"acerola": {"top": 400, "left": 90, "height": 109},
			"goji": {"top": 400, "left": 50, "height": 121},

			"width": 420,
			"marginLeft": -40,
			"marginRight": -60,
			"opacity":1
		};
		el.regularBottle = {
			"bottle": {"left": 0,"top": 221,"width": 210,"height": 230},
			"tag":{"top": 150,"left": 120,"width":58,"height":57},
			
			"acai": {"top": 410, "left": 113, "height": 40},
			"mangosteen": {"top": 390, "left": 110, "height": 58},
			"acerola": {"top": 400, "left": 60, "height": 48},
			"goji": {"top": 400, "left": 45, "height": 53},

			"width": 210,
			"marginLeft": 0,
			"marginRight": 0,
			"opacity": "0.7"
		};
	};
	function redraw(el) {
		var w = $(window).width();
		var o = $('.heroBottle').position().left;
		var b = $('.heroBottle').width();
		var n = -o + (w/2) - (b/2) + 235;
		$("ul",el).css("marginLeft", n);
	};
	function moreDetails(el){
	    var elp = $('.heroBottle',el);
		if ( $('#ProductDetails',el).is(":hidden") ) {
			$('#ProductDetails',el).fadeIn(400).find(".Inside").html(elp.find(".moredetails").html());
			$('.Blurb').fadeOut();
		} else
			closeDetails(el);
	};
	function closeDetails(el){
		if ( $('#ProductDetails',el).not(":hidden") ){
			$('.Blurb').fadeIn();
			$('#ProductDetails',el).fadeOut();
		}
	};
	function changeBottle( el ){
	    var elp = $('.heroBottle');
		$('.bottle', elp ).show();
		$('.fruit',elp).fadeIn(400);
		$('.bottle32', elp ).hide();
		var nut = $(".moredetails", elp ).find(".Nutrition");
		nut.attr("src", nut.attr("src").replace(32,10));
	};
	function changeBottle32( el ){
		if ( $('.bottle32:hidden','.heroBottle') ) {
		    el.pause = true;
			var elp = $('.heroBottle');
			$( ".bottle", elp ).fadeOut(400);
			$('.fruit',elp).fadeOut(400);
			$( ".bottle32", elp).fadeIn(400,function(){
				el.pause = false;
			});
			$( ".tag10", elp ).fadeTo("slow", 0.6);
			$( ".tag32", elp ).fadeTo("slow", 1);

			var nut = $(".moredetails", elp ).find(".Nutrition");
			nut.attr("src", nut.attr("src").replace(10,32));
		}
	};
	function changeBottle10(el) {
	    if ( $('.bottle:hidden', '.heroBottle') ) {
		    el.pause = true;
			var elp = $('.heroBottle');
			$( ".bottle32", elp ).fadeOut(400);
			$( ".bottle", elp).fadeIn(400,function(){
				el.pause = false;
			});
			$(".fruit",elp).fadeIn(400);
			$( ".tag10", elp ).fadeTo("slow", 1);
			$( ".tag32", elp ).fadeTo("slow", 0.6);

			var nut = $(".moredetails", elp ).find(".Nutrition");
			nut.attr("src", nut.attr("src").replace(32,10));
		}
	};
	function selectBottle(el, bottle) {
		closeDetails(el);
		if ( bottle.hasClass("heroBottle") )
			return moreDetails(el);
		if ( el.pause )
		    return;

		changeBottle(el);
		var uel = $('ul',el);
		var hero = $('.heroBottle');
		var distance = hero.index() - bottle.index();
		var direction = ( distance < 0 );
		distance = Math.abs(distance);
		var i;
		for(i=1;i<=distance;i++) {
			el.pause = true;
			console.log(i*450);
			if ( direction ) {
				$("li",el).not(".moving").first().addClass("moving").animate({queue:false,width: 0}, 450,function(){
					$(this).css("width","").removeClass("moving").appendTo(uel);
					if ( $('.moving',el).size() == 0 ) el.pause = false;
				});
			} else {
				$('li',el).last().css('width',0).prependTo(uel);
				$('li',el).first().animate({queue:false,width: el.rw}, 450,function() {
					$(this).css("width","");
					el.pause = false;
				});
			}	
		}
		moveBottle(el,hero,bottle,(distance*450));
	};
	function prevBottle(el){
		closeDetails(el);
		if ( el.pause )
		    return;

		changeBottle(el);
		var current = $('.heroBottle',el);
		var next = current.prev();
		var uel = $('ul',el);

		if ( next.size() == 0 ) {
			var next = $('li',el).last();
		}

		el.pause = true;
		$('li',el).last().css('width',0).prependTo(uel);
		$('li',el).first().animate({queue:false,width: el.rw}, 500,function() {
			$(this).css("width","");
			el.pause = false;
		});
		moveBottle(el,current,next);
	};
	function nextBottle(el) {
		closeDetails(el);
		if ( el.pause )
		    return;

		changeBottle(el);
		var current = $('.heroBottle',el);
		var next = current.next();
		var uel = $('ul',el);
		if ( next.size() == 0 ) {
			var next = $('li',el).first();
		}
		el.pause = true;
		$("li",el).not(".moving").first().addClass("moving").animate({queue:false,width: 0}, 500,function(){
			$(this).css("width","").removeClass("moving").appendTo(uel);
			el.pause = false;
		});
		moveBottle(el,current,next);
	};
	function moveBottle(el,current, next, speed){
		speed = 450 || speed;
		/* Current */
		current.find('.stag').hide();
		current.find('.moreinfo').hide();
		current.animate(el.regularBottle, speed, function(){
			$(this).removeClass("heroBottle").addClass("regularBottle").attr("title","");
		});
		for (var key in el.regularBottle)
			if ( typeof el.regularBottle[key] == "object" )
				current.find("."+key).animate(el.regularBottle[key], !el.regularBottle[key]["speed"] ? speed : el.regularBottle[key]["speed"],function(){ $(this).attr("style","") });
		/* Next */
		next.animate(el.heroBottle, speed, function(){
			$(this).removeClass("regularBottle").addClass("heroBottle").attr("title","");
		});
        for (var key in el.heroBottle)
			if ( typeof el.heroBottle[key] == "object" )
				next.find("."+key).animate(el.heroBottle[key], !el.heroBottle[key]["speed"] ? speed : el.heroBottle[key]["speed"] ,function(){ $(this).attr("style","") });
	};
	$.each(this,function(i,d) {
		init(d);
		redraw(d);
 });
};
})( jQuery );
/* Generate the HTML */
$(document).ready(function(){
	var products = [
		["Acai-theOriginal", true, "A&ccedil;ai<br />the Original", "Antioxidant: Anthocyanins.--Our A&ccedil;ai Original is music to your mouth and pure art to your body. Bursting with a clarified, yet rich, dark berry flavor that is complimented by organic agave nectar for a taste that is exotically delicious. 100% Recyclable Bottles. Flash Pasteurized.", true ],
        ["Acai-withBlueberry", true, "A&ccedil;ai<br />with Blueberry", "Antioxidant: Anthocyanins.--Our A&ccedil;ai with Blueberry fruit beverage combines the dark berry flavors of a&ccedil;ai, a touch of organic agave nectar, and a note of blueberry to provide a cravably delicious flavor experience. 100% Recyclable Bottles. Flash Pasteurized.", true ],
        ["Acai-withRaspberry", false, "A&ccedil;ai<br />with Raspberry", "Antioxidant: Anthocyanins.--The dark berry flavors of a&ccedil;ai, a hint of agave nectar, and the fruitiness of raspberries are joined to provide a taste so exotically delicious that its music to your mouth and pure art to your body. 100% Recyclable Bottles. Flash Pasteurized.", true ],
        ["Acai-withMango", false, "A&ccedil;ai<br />with Mango", "Antioxidant: Anthocyanins.--Discover a tropically delicious twist of our dark berry a&ccedil;ai with a note of mango complimented by agave nectar for a taste so exotically delicious, its music to your mouth and pure art to your body. 100% Recyclable Bottles. Flash Pasteurized.", true ],
        ["Acai-withPassionfruit", false, "A&ccedil;ai<br />with Passionfruit", "Antioxidant: Anthocyanins.--Combine the delicious dark berry flavors of a&ccedil;ai with a bit of organic agave nectar and the sweet flavors of passionfruit and you'll get a taste so exotically delicious, its music to your mouth and pure art to your body. 100% Recyclable Bottles. Flash Pasteurized.", true ],
        ["Acerola-withRedPeach", false, "Acerola<br />with Red Peach", "Antioxidant: Vitamin C.--Take your taste buds on a delicious adventure with the flavor of citrus paired with a twist of red peach. Acerola, also known as Barbados cherry, is an immunity powerhouse, delivering generous amounts of Vitamin C with a full spectrum of flavonoids and micronutrients. 100% Recyclable Bottles. Flash Pasteurized.",false ],
        ["Mangosteen-withDragonfruit", false, "Mangosteen<br />with Dragonfruit", "Antioxidant: Xanthones.--Have a craving for something peachy, floral, and tropical? Mangosteen with Dragonfruit is the deliciously nutritious choice for you. Mangosteen, often described as the worlds best-tasting fruit, is native to Southeast Asia and contains rare and powerful xanthone antioxidants. 100% Recyclable Bottles. Flash Pasteurized.", false ],
        ["Acerola-withMango", true, "Acerola<br />with Mango", "Antioxidant: Vitamin C.--The perfect delectable balance of citrus and mango is delivered in our Acerola with Mango fruit beverage. Acerola, also known as Barbados cherry, is an immunity powerhouse, delivering generous amounts of Vitamin C with a full spectrum of flavonoids and micronutrients.", false ],
        ["Mangosteen-withPassionfruit", false, "Mangosteen<br />with Passionfruit", "Antioxidant: Xanthones.--Delectable tropical mangosteen and tangy, sweet passionfruit are combined in our Mangosteen with Passionfruit fruit beverage. Mangosteen, often described as the worlds best tasting fruit, is native to Southeast Asia and contains rare and powerful xanthone antioxidants. 100% Recyclable Bottles. Flash Pasteurized.",false ],
        ["Goji-withTartCherry", false, "Goji Berry<br />with Tart Cherry", "Antioxidant: Carotenoids.--Looking for something sweet and tart that will blow your mind? Try our Goji Berry with Tart Cherry flavor. Goji, a revered Himalayan fruit, contains an unusually broad spectrum of essential micronutrients, including 33 trace minerals and antioxidants like selenium and zeaxanthin.", false ]
    ];
	$.each(products,function(i,d){
	    var fruit = d[0].split("-")[0].toLowerCase();
		var res = "/wp-content/themes/bossa_nova";
		var html = '<li class="bottleItem ' + ( i == 0 ? 'heroBottle' : 'regularBottle' ) + '" id="'+d[0]+'">';
		html += '<img src="'+res+'/images/bottles/new/'+d[0]+'-10oz.png" class="bottle" />';
		if ( d[1] )
			html += '<img src="'+res+'/images/bottles/new/'+d[0]+'-32oz.png" class="bottle32" />';
		html += '<img src="'+res+'/images/fruits/fruit-'+fruit+'.png" class="fruit '+fruit+'" />';
		html += '<img class="tag" alt="'+d[0]+'" src="'+res+'/images/labels/'+d[0]+'.png" />';
		html += '<img class="stag tag10" src="'+res+'/images/tag-10oz.png" />';
		if ( d[1] )
			html += '<img class="stag tag32" src="'+res+'/images/tag-32oz.png" />';
		html += '<a href="#" class="moreinfo disabled">more info</a>';
		html += '<div class="moredetails">'
			+ '<img src="'+res+'/images/detail-icons/'+d[0]+'.png" class="greenIcon" />'
			+ '<img src="'+res+'/images/moreinfo-tip.png" class="sideTip" />'
			+ '<h2>'+d[2]+'</h2>'
			+ '<img src="'+res+'/images/nutrition/' + d[0] + '-10oz.png" class="Nutrition" />'
			+ '<p>' + d[3].replace('--', '</p><p>') + '</p>';
		html += '<p><img src="'+res+'/images/' + ( d[4] ? "usdainformation" : "usdainformation-organicless" ) + '.png" class="Organic" /></p>';
		html += '<br class="clearfix" /></div>';
		html += '</li>';
		if ( i % 2 )
			$('#Products ul').append(html);
		else
			$('#Products ul').prepend(html);
	});
	$("#Products").productSlider();
	$(".faq-list").questionSlider();
	$("#SuperfruitNav").tabManager();
	$("#ContactForm").contactForm();
	$(".LocatorList").simplePaginate();
});
$(window).bind('load',function(){
	$('.couponLink').each(function(i,el){
		try {
	        var axel = Math.random() * 10000000000000;
			/*$("body").append('<iframe src="http://fls.doubleclick.net/activityi;src=3066895;type=bossa917;cat=bossa404;ord=' + axel + '?" width="1" height="1" frameborder="0"></iframe><div id="floodlight"></div>');*/
			_gaq.push(['_trackEvent', 'Coupons', 'Coupon View', this.title]);
		} catch(err){};
	});
	$('.couponLink').bind("click",function(){
		try {
	    	var axel = Math.random() * 10000000000000;
			/*$('#floodlight').html('<iframe src="http://fls.doubleclick.net/activityi;src=3066895;type=bossa917;cat=bossa314;ord=' + axel + '?" width="1" height="1" frameborder="0"></iframe>');*/
			_gaq.push(['_trackEvent', 'Coupons', 'Coupon Print', this.title]);
			setTimeout('document.location = "' + this.href + '"', 100);
		} catch(err){};
		return false;
	});
	$("#HomepageSlider").homepageTout();
});
