



$.fn.defaultValue = function(defaultValue) {
    var v = jQuery(this).val();
    if (v.length > 0) {
        return (v);
    } else {
        //jQuery(this).val(defaultValue)
        return defaultValue;
    }
};




$(document).ready(function() {

	initGAEvents();
	
	if($("#slideshow").exists()) {
		initSlideshow();
	}
	
	
	if($(".pg-tips-product").exists()) {
		productPicker(".pg-tips-product");
	}

	if($(".scottish-blend-product").exists()) {
		productPicker(".scottish-blend-product");
	}


	if($(".lipton-product").exists()) {
		productPicker(".lipton-product");
	}

	if($(".lyons-product").exists()) {
		productPicker(".lyons-product");
	}


	if($(".rolling-hero").exists()) {
		quoteRotation(".rolling-hero");
	}









    if ($("#logfader li").length > 0) {

        var slideshow_count = $("#homeHeroSlideshow li").length;
        var slideshow_current = 1;
		
	}
	
    //HOMEPAGE SLIDESHOW												 
    if ($("#homeHeroSlideshow li").length > 0) {

        var slideshow_count = $("#homeHeroSlideshow li").length;
        var slideshow_current = 1;

        $("li#slideshow-image-" + slideshow_current).show();
        $("li#heroThumb-" + slideshow_current).find("img").attr("src", $("li#heroThumb-" + slideshow_current).find("img").attr("src").replace("_0", "_1"));

        function slideshow_run() {
            $("li#slideshow-image-" + slideshow_current).fadeOut(1000).removeClass("active");
            $("li#heroThumb-" + slideshow_current).find("img").attr("src", $("li#heroThumb-" + slideshow_current).find("img").attr("src").replace("_1", "_0"));

            slideshow_current++;

            if (slideshow_current > slideshow_count) {
                slideshow_current = 1;
            }
            $("li#slideshow-image-" + slideshow_current).fadeIn(1000).addClass("active");
            $("li#heroThumb-" + slideshow_current).find("img").attr("src", $("li#heroThumb-" + slideshow_current).find("img").attr("src").replace("_0", "_1"));
        }

        if ($("#homeHeroSlideshow li").length > 0) {
            $("#homeHeroSlideshow").everyTime(2600, slideshow_run);
        }

        $("#homeHeroThumb li a").hoverIntent(

			function() {

			    var slideshowTarget = $(this).parent().attr("id").substr($(this).parent().attr("id").lastIndexOf("-") + 1);
			    $("#homeHeroSlideshow").stopTime();

			    $("li#slideshow-image-" + slideshow_current).fadeOut(1000).removeClass("active");
			    $("li#heroThumb-" + slideshow_current).find("img").attr("src", $("li#heroThumb-" + slideshow_current).find("img").attr("src").replace("_1", "_0"));

			    $("li#slideshow-image-" + slideshowTarget).fadeIn(1000).removeClass("active");
			    $("li#heroThumb-" + slideshowTarget).find("img").attr("src", $("li#heroThumb-" + slideshowTarget).find("img").attr("src").replace("_0", "_1"));

			    slideshow_current = slideshowTarget;

			}, function() {

			    var slideshowTarget = $(this).parent().attr("id").substr($(this).parent().attr("id").lastIndexOf("-") + 1);

			    $("#homeHeroSlideshow").everyTime(2600, slideshow_run);
			    $("li#slideshow-image-" + slideshowTarget).removeClass("active");

			    return false;
			}
		);


    }

    var quizRadioGroups = new Array("calories", "anti-oxidants", "hydration", "anti-oxidants-type", "drink", "theanine");
    var quizAnswers = new Array("14", "tea", "hydrating", "fruit and vegetables", "tea", "35 million");
    var quizResults = new Array();
    $(".msg").hide();

    //QUIZ VALIDATION
    if ($('#quiz .submit').length != 0) {
        $('#quiz .submit').click(function() {
            $(".msg").hide();
            //loop through elements
            for (var x = 0; x < quizRadioGroups.length; x++) {
                //clear previos classes				
                $("input:radio[name=" + quizRadioGroups[x] + "]").parent("li").parent("ol").parent("li").removeClass("correct");
                $("input:radio[name=" + quizRadioGroups[x] + "]").parent("li").parent("ol").parent("li").removeClass("incorrect");
                //check input against anser
                if ($("input:radio[name=" + quizRadioGroups[x] + "]:checked").val() == quizAnswers[x]) {
                    //correct answer
                    $("input:radio[name=" + quizRadioGroups[x] + "]").parent("li").parent("ol").parent("li").addClass("correct");
                    quizResults[x] = 1;
                } else {
                    //no or wrong answer
                    $("input:radio[name=" + quizRadioGroups[x] + "]").parent("li").parent("ol").parent("li").addClass("incorrect");
                    quizResults[x] = 0;
                }
            }
            //work out results
            var resultsCount = 0; ;
            for (var q = 0; q < quizResults.length; q++) {
                resultsCount = resultsCount + quizResults[q];
            }
            if (resultsCount == quizResults.length) {
                $(".msg").show();
            }
        });
    };

    //DEFINITION LISTS (FAQs & FEATURES)
    $(".toggle dt").toggle(
		function() {
		    $(this).next("dd").slideDown();
		    $(this).addClass("open");
		}, function() {
		    $(this).next("dd").slideUp();
		    $(this).removeClass("open");
		}
	);

    $(".toggle dt.open").unbind();

    $(".toggle dt").hover(
		function() {
		    $(this).addClass("hover");
		    $(this).css("cursor", "pointer");
		}, function() {
		    $(this).removeClass("hover");
		}
	);

    $(".toggle dt.open").toggle(
		function() {
		    $(this).next("dd").slideUp();
		    $(this).removeClass("open");
		}, function() {
		    $(this).next("dd").slideDown();
		    $(this).addClass("open");
		}
	);

    //TOGGLE2 DL
    $(".toggle2 dt").toggle(
		function() {
		    $(this).next("dd").slideDown();
		    $(this).addClass("open");
		}, function() {
		    $(this).next("dd").slideUp();
		    $(this).removeClass("open");
		}
	);

    $(".toggle2 dt.open").unbind();

    $(".toggle2 dt.open").toggle(
		function() {
		    $(this).next("dd").slideUp();
		    $(this).removeClass("open");
		}, function() {
		    $(this).next("dd").slideDown();
		    $(this).addClass("open");
		}
	);

    $(".toggle2 dt").hover(
		function() {
		    $(this).addClass("hover");
		}, function() {
		    $(this).removeClass("hover");
		}
	);

    $(".col647-alt dt").unbind();

    $(".col647-alt dt").toggle(
		function() {
		    $(this).next("dd").slideDown();
		    $(this).addClass("open");
		}, function() {
		    $(this).next("dd").slideUp();
		    $(this).removeClass("open");
		}
	);

    $(".col647-alt dt.open").unbind();

    $(".col647-alt dt.open").toggle(
		function() {
		    $(this).next("dd").slideUp();
		    $(this).removeClass("open");
		}, function() {
		    $(this).next("dd").slideDown();
		    $(this).addClass("open");
		}
	);

    $(".col647-alt dt").hover(
		function() {
		    $(this).addClass("hover");
		}, function() {
		    $(this).removeClass("hover");
		}
	);

    //Profit Calculator
    $('input.clearValue').val("")
    $('span.clearValue').empty();

    $('input.coffeeProfit').keyup(function() {

        var cofeeCostPerCupPence = $("input#coffeeCupCostPence").defaultValue(0);
        var cofeeCostPerCupPounds = $("input#coffeeCupCostPounds").defaultValue(0);
        var coffeeCostPerCup = parseInt(cofeeCostPerCupPounds) + parseFloat(cofeeCostPerCupPence / 100);
        var coffeeCostPriceCupPence = $("input#coffeeCupPricePence").defaultValue(0);
        var coffeeCostPriceCupPounds = $("input#coffeeCupPricePounds").defaultValue(0);
        var coffeeCupCost = parseInt(coffeeCostPriceCupPounds) + parseFloat(coffeeCostPriceCupPence / 100);
        var coffeeProfitValue = coffeeCupCost - coffeeCostPerCup;
        coffeeProfitValue = parseFloat(Math.round(coffeeProfitValue * 100) / 100);
        $("span#coffeeProfitValue").empty();
        $('span#coffeeProfitValue').append(formatCurrency(coffeeProfitValue));
    });

    $('input.teaProfit').keyup(function() {
        var teaCostPerCupPounds = $("input#teaCupCostPounds").defaultValue(0);
        var teaCostPerCupPence = $("input#teaCupCostPence").defaultValue(0);
        var teaCostPerCup = parseInt(teaCostPerCupPounds) + parseFloat(teaCostPerCupPence / 100);
        var teaCostPriceCupPounds = $("input#teaCupPricePounds").defaultValue(0);
        var teaCostPriceCupPence = $("input#teaCupPricePence").defaultValue(0);
        var teaCostPriceCup = parseInt(teaCostPriceCupPounds) + parseFloat(teaCostPriceCupPence / 100);
        var teaProfitValue = teaCostPriceCup - teaCostPerCup;
        var profit20Cups = Math.ceil(Math.round((((teaProfitValue + 0.5) * 20) * 365) * 100) / 100);
        var profit30Cups = Math.ceil(Math.round((((teaProfitValue + 0.5) * 30) * 365) * 100) / 100);
        var profit50Cups = Math.ceil(Math.round((((teaProfitValue + 0.5) * 50) * 365) * 100) / 100);
        var profit100Cups = Math.ceil(Math.round((((teaProfitValue + 0.5) * 100) * 365) * 100) / 100);
        var profit150Cups = Math.ceil(Math.round((((teaProfitValue + 0.5) * 150) * 365) * 100) / 100);
        var current20Cups = Math.ceil(Math.round(((teaProfitValue * 20) * 365) * 100) / 100);
        var current30Cups = Math.ceil(Math.round(((teaProfitValue * 30) * 365) * 100) / 100);
        var current50Cups = Math.ceil(Math.round(((teaProfitValue * 50) * 365) * 100) / 100);
        var current100Cups = Math.ceil(Math.round(((teaProfitValue * 100) * 365) * 100) / 100);
        var current150Cups = Math.ceil(Math.round(((teaProfitValue * 150) * 365) * 100) / 100);
        var roundedTeaProfit = (Math.round((teaProfitValue) * 100) / 100)
        $('span.clearValue').empty();
        $('span#teaProfitValue').append(formatCurrency(roundedTeaProfit));
        $('span#profit20Cups').append(formatCurrency(profit20Cups));
        $('span#profit30Cups').append(formatCurrency(profit30Cups));
        $('span#profit50Cups').append(formatCurrency(profit50Cups));
        $('span#profit100Cups').append(formatCurrency(profit100Cups));
        $('span#profit150Cups').append(formatCurrency(profit150Cups));
        $('span#current20Cups').append(formatCurrency(current20Cups));
        $('span#current30Cups').append(formatCurrency(current30Cups));
        $('span#current50Cups').append(formatCurrency(current50Cups));
        $('span#current100Cups').append(formatCurrency(current100Cups));
        $('span#current150Cups').append(formatCurrency(current150Cups));
    });

});



function formatCurrency(value) {
    var str = String(value);
    if (str.length > 2) {
        if (str.indexOf(".") == (str.length - 2)) str += "0";
    }
    return String(str).replace(/(\d+)(\d{3})/, "$1,$2");

}


function defaultIfBlank(value, defaultValue) {
    if (value.length == 0) {
        return value;
    } else {
        return defaultValue;
    }
}




//////////----- GA TRACKING -----------------------------------//////////
//---------------------------------------------------------------------//
function GATrackEvent(category, action, label) {
	_gaq.push(["_trackEvent", category, action, label]);
	//alert(category + " " + action + " " + label);
}

function GATrackPageView(page) {
	_gaq.push(["_trackPageview", page]);
	//alert(page);
}

function initGAEvents() {
	
	$("a").each(
		function() {
			var destinationURL = $(this).attr("href");
			if(destinationURL.indexOf(".pdf") > -1) {
				var category = "Link";
				var action = "Download";
				var label = destinationURL;
				$(this).bind("click", function() {
					GATrackEvent(category, action, label);
				});
			} else if(destinationURL.indexOf("mailto") > -1) {
				var category = "Link";
				var action = "Mailto";
				var label = destinationURL;
				$(this).bind("click", function() {
					GATrackEvent(category, action, label);
				});
			} else if(destinationURL.indexOf("http") > -1 && destinationURL.indexOf("teatips.co.uk") == -1) {
				var category = "Link";
				var action = "Exit";
				var label = destinationURL;
				$(this).bind("click", function() {
					GATrackEvent(category, action, label);
				});
			}
		}
	);

}

/* ----- HERO SLIDESHOW ------------------------------------------------------------------- */
/* ---------------------------------------------------------------------------------------- */
/* ---------------------------------------------------------------------------------------- */
jQuery.fn.exists = function() {
	return jQuery(this).length > 0;
}


function initSlideshow() {
	slideshowLength = $("#slideshow li").length;
	slideshowCurrent = 1;
	$("#slideshow").everyTime(5000, function() {
		runSlideshow();
	});
}
function runSlideshow() {
	if(slideshowCurrent < slideshowLength) {
		$("#slideshow li.current").next("li").css({ "z-index": "3" }).fadeIn(500, function() {
			$("#slideshow li.current").removeClass("current");
			$(this).addClass("current");
			$("#slideshow li").hide();
			$("#slideshow li.current").show();
			$(this).css({ "z-index": "1" });
			slideshowCurrent++;
		});
	} else if(slideshowCurrent == slideshowLength) {
		$("#slideshow li:first").css({ "z-index": "3" }).fadeIn(500, function() {
			$("#slideshow li.current").removeClass("current");
			$(this).addClass("current");
			$("#slideshow li").hide();
			$("#slideshow li.current").show();
			$(this).css({ "z-index": "1" });
			slideshowCurrent=1;
		});
	}	
}


/* ----- Mercahnise product picker ------------------------------------------------------------------- */
/* ---------------------------------------------------------------------------------------- */
/* ---------------------------------------------------------------------------------------- */

function productPicker(className) {
	$(className+ " .product-pick").hide();
	$(className+ " .product-pick:first").show();
	$(className+ " .merchandise-product-nav a").click( function(){
		$(className+ " .product-pick").hide();
		var i = $(className+ " .merchandise-product-nav a").index(this);
		$(className+ " .product-pick").eq(i).fadeIn(500);
		return false;
	});
}



/* ----- Quote fader ------------------------------------------------------------------- */
/* ---------------------------------------------------------------------------------------- */
/* ---------------------------------------------------------------------------------------- */
function quoteRotation(className) {
	$(className+ " .quote").hide();
	$(className+ " .quote:first").show();
	
	var currentQuote = 0;
	
	setInterval(function(){ 	
		quoteRotate(className,currentQuote)
		currentQuote = currentQuote+1
		
		if (currentQuote > $(className+ " .quote").length-1 ) currentQuote = 0;	  
	
	}, 5000);	
}


function quoteRotate(className, current) {
	$(className+ " .quote").eq(current).fadeOut("slow", function () {
	
		var next = current+1;		
		if (next > $(className+ " .quote").length-1 ) next = 0;	
		$(className+ " .quote").eq(next).fadeIn("slow");
	
	});
}





(function($){$.fn.hoverIntent=function(f,g){var cfg={sensitivity:7,interval:100,timeout:0};cfg=$.extend(cfg,g?{over:f,out:g}:f);var cX,cY,pX,pY;var track=function(ev){cX=ev.pageX;cY=ev.pageY;};var compare=function(ev,ob){ob.hoverIntent_t=clearTimeout(ob.hoverIntent_t);if((Math.abs(pX-cX)+Math.abs(pY-cY))<cfg.sensitivity){$(ob).unbind("mousemove",track);ob.hoverIntent_s=1;return cfg.over.apply(ob,[ev]);}else{pX=cX;pY=cY;ob.hoverIntent_t=setTimeout(function(){compare(ev,ob);},cfg.interval);}};var delay=function(ev,ob){ob.hoverIntent_t=clearTimeout(ob.hoverIntent_t);ob.hoverIntent_s=0;return cfg.out.apply(ob,[ev]);};var handleHover=function(e){var p=(e.type=="mouseover"?e.fromElement:e.toElement)||e.relatedTarget;while(p&&p!=this){try{p=p.parentNode;}catch(e){p=this;}}if(p==this){return false;}var ev=jQuery.extend({},e);var ob=this;if(ob.hoverIntent_t){ob.hoverIntent_t=clearTimeout(ob.hoverIntent_t);}if(e.type=="mouseover"){pX=ev.pageX;pY=ev.pageY;$(ob).bind("mousemove",track);if(ob.hoverIntent_s!=1){ob.hoverIntent_t=setTimeout(function(){compare(ev,ob);},cfg.interval);}}else{$(ob).unbind("mousemove",track);if(ob.hoverIntent_s==1){ob.hoverIntent_t=setTimeout(function(){delay(ev,ob);},cfg.timeout);}}};return this.mouseover(handleHover).mouseout(handleHover);};})(jQuery);

