﻿(function($) {
    
    $.fn.rollover = function(options) {
        var opts = $.extend({}, $.fn.rollover.defaults, options);
        return this.each(function(){
            $(this).hover(function(){$(this).attr("src", $(this).attr("src").split(opts.strOff).join(opts.strOn))}, function(){$(this).attr("src", $(this).attr("src").split(opts.strOn).join(opts.strOff))});
        });    
    };

    $.fn.rollover.defaults = {
        strOn: '_on',
        strOff: '_off'
    };

})(jQuery);

function triviaResult(){
    if (!document.getElementById) alert("This test requires a modern browser such as Firefox or Internet Explorer");
    var questionBlock = document.getElementById("sweetTrivia");
    var resultBlock = document.getElementById("sweetTriviaResults");
    var questions = document.getElementById("sweetTrivia").getElementsByTagName("input");
    var result = 0;
    for (i=0; i<questions.length; i++){
        if (questions[i].checked) {
		    result += parseInt(questions[i].value);
	    }
    }
    var num = result;
    //var result = Math.round((result/15)*100);
    if (result<60){
        resultBlock.innerHTML = "<h4>Below 60 Not Sweet Enough.</h4>\n<p>Your score needs a healthy improvement to achieve sweet results. Get motivated and start your improvement plan today.</p>";
    } else if ((result>=60)&&(result<85)) {
        resultBlock.innerHTML = "<h4>60 - 85 Could be sweeter.</h4>\n<p>You've got most of the right answers - but you could push yourself further for an even healthier life-style score.</p>";
    } else if ((result>=60)&&(result<100)) {
        resultBlock.innerHTML = "<h4>85 – 95 Looking sweet!</h4>\n<p>Your score shows you know what to do to lead a pretty healthy life-style. Just make sure you do them!</p>";
    } else if (result==100) {
        resultBlock.innerHTML = "<h4>100 The sweetest result.</h4>\n<p>Your score is in perfect health – it shows you know just about all there is to know about leading a healthy life-style. Well done.</p>";
    } else {
        resultBlock.innerHTML = "<h4>Wow wow wee waa!</h4>\n<p>Something's not right.</p>";
    }
    resultBlock.innerHTML += '<p>Not sweet enough? <a href="/Promotion/Trivia.aspx" class="link">Take the test again</a></p>'
    questionBlock.style.display = "none";
    resultBlock.style.display = "block";
    //alert(num+","+result);
}

function sugarTest(){
    if (!document.getElementById) alert("This test requires a modern browser such as Firefox or Internet Explorer");
    var drink = parseInt(document.getElementById("testSugarBeverages")[document.getElementById("testSugarBeverages").selectedIndex].value);
    var freq = parseInt(document.getElementById("testNumberBeverages")[document.getElementById("testNumberBeverages").selectedIndex].value);
    var cereal = parseInt(document.getElementById("testSugarCereal")[document.getElementById("testSugarCereal").selectedIndex].value);
    var disp = document.getElementById("sugarTestResults");
    var total = ((drink==0)||(freq==0))?cereal*365:((drink*freq)+cereal)*365;
    var kg = String(Math.round(total/211));
    document.getElementById("sugarQty").innerHTML = kg;
    disp.style.display = "block";
}


function externalLinks() {
    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";
    }
}

function validateCheck(oSrc, args) {
    alert(oSrc);
    args.IsValid = (args.checked == true);
    
}

sfHover = function() {
	var sfEls = document.getElementById("nav").getElementsByTagName("LI");
	for (var i=0; i<sfEls.length; i++) {
		sfEls[i].onmouseover=function() {
			this.className+=" sfhover";
		}
		sfEls[i].onmouseout=function() {
			this.className=this.className.replace(new RegExp(" sfhover\\b"), "");
		}
	}

	if (document.getElementById("recipebrowser")) {	
	    var rpEls = document.getElementById("recipeBrowser").getElementsByTagName("LI");
	    for (var i=0; i<rpEls.length; i++) {
		    rpEls[i].onmouseover=function() {
			    this.className+=" rphover";
		    }
		    rpEls[i].onmouseout=function() {
			    this.className=this.className.replace(new RegExp(" rphover\\b"), "");
		    }
	    }
    }
}

function getElementsByClassName(oElm, strTagName, strClassName){
    var arrElements = (strTagName == "*" && oElm.all)? oElm.all : oElm.getElementsByTagName(strTagName);
    var arrReturnElements = new Array();
    strClassName = strClassName.replace(/\-/g, "\\-");
    var oRegExp = new RegExp("(^|\\s)" + strClassName + "(\\s|$)");
    var oElement;
    for(var i=0; i<arrElements.length; i++){
        oElement = arrElements[i];      
        if(oRegExp.test(oElement.className)){
            arrReturnElements.push(oElement);
        }   
    }
    return (arrReturnElements)
}

showAllRecipes = function() {
    var fRec = getElementsByClassName(document, "div", "recipeBookItem");
    var recState = (fRec[1].style.display!="block")?"block":"none";
    var lnkState = (fRec[0].style.display!="block")?"Hide all":"Show all";
    for (var i=0; i<fRec.length; i++) {
        fRec[i].style.display=recState;
    }
    document.getElementById("recipeDisplayLink").innerHTML = lnkState;
}

init = function(){
    externalLinks();
}

if (window.attachEvent) {window.attachEvent("onload",init);}
if (document.addEventListener) {document.addEventListener("load",init,false);}
if (window.addEventListener) {window.addEventListener("load",init,false);}

if (window.attachEvent) window.attachEvent("onload", sfHover);

if (document.getElementById("downloadBox")) {
    $(function(){
	    $("#downloadPc").mouseover(function(){this.src='/Common/Images/downloadPc_over.gif';}).mouseout(function(){this.src='/Common/Images/downloadPc.gif';});
	    $("#downloadMac").mouseover(function(){this.src='/Common/Images/downloadMac_over.gif';}).mouseout(function(){this.src='/Common/Images/downloadMac.gif';});
    });
}

function openWindow(width, height, content) {
    var newWindow = window.open("", "", "resizable=no,menubar=no,scrollbars=no,status=no,titlebar=no,toolbar=no,height="+height+",width="+width+"", false);
    newWindow.document.write(content);
    return newWindow;
}

function popWindow(width, height, content) {
    window.open(content, "", "resizable=no,menubar=no,scrollbars=yes,status=no,titlebar=no,toolbar=no,height="+height+",width="+width+"", false);
}

// jQuery plugin to fix images with transparent png source.
// Requires a single pixel transparent gif
// Explicitly sets the width
// Also applies a rollover if class of image is 'rollover'
jQuery.fn.pngFix = function() {
  return this.each(function(){
    jQuery(this).css({width: jQuery(this).width(), height: jQuery(this).height(), filter: "progid:DXImageTransform.Microsoft.AlphaImageLoader(src=\'" + jQuery(this).attr('src') + "\', sizingMethod='scale')"}).attr('src', '/Common/Images/x.gif').hover(function(){if (jQuery(this).is('.rollover')){jQuery(this).css({filter: jQuery(this).css("filter").split('_off').join('_on')})}}, function(){if (jQuery(this).is('.rollover')){jQuery(this).css({filter: jQuery(this).css("filter").split('_on').join('_off')})}});
  });
};

function initTabs() {
    $('#tabs li a').click(function() {
        $('.tab').hide().eq($('#tabs li a').removeClass('selected').index(this)).show();
        $(this).addClass('selected');
        // show recipe finder search results only under first tab
        ($('#tabs li a').index(this) == 0) ? $('#recipeSearchResults').show() : $('#recipeSearchResults').hide();
        if ($.browser.msie) $('#footer').hide().show();
    });
    
    // if p.msgSubmitForm exists, then form was submitted, so show form tab
    if ($('p.msgSubmitForm').length == 0) {
        $('.tab').hide().eq(0).show();
        $('#tabs li a').eq(0).addClass('selected').show();
    }
    else {
        $('.tab').hide().eq(2).addClass('selected').show();
        $('#tabs li a').eq(2).addClass('selected').show();        
    }
    
    // fixes for IE 6 and 7
    if ($.browser.msie) { 
        $('#tabs li a').hover(function() { $(this).hide().show(); }, function() { $(this).hide().show(); });   
        $('#footer').hide().show();
    }
}

function initRecipeRater() {
    $('.recipeRating input').hover(function() {
        var i = $('.recipeRating input').index(this) + 1;
        $('.recipeRating input:lt('+i+')').attr("src", $(this).attr("src").split("_off").join("_on"));
    }, function() {
        $('.recipeRating input').attr("src", $(this).attr("src").split("_on").join("_off"));
    });
}

function initHome() {
    var p = $('#homeImages img').length - 1, interval = 6000;
    var rotateInterval = setInterval(rotate, interval);
    
    $('#homeImages img').css({opacity:0}).eq(p).css({opacity:1});
        
    function rotate() {
        $('#homeImages img').eq(p).animate({opacity:0}, 500);
        if (p == ($('#homeImages img').length - 1))
            $('#homeImages img').eq(p=0).animate({opacity:1}, 500);
        else
            $('#homeImages img').eq(++p).animate({opacity:1}, 500);
    }

    $('#home .hometabwrap').hover(function () {
        $(this).find('a.hometab').animate({height:270}, 250).find('.desc, .more').fadeIn('fast');
    }, function () {
        $(this).find('a.hometab').animate({height:189}, 250).find('.desc, .more').fadeOut('fast');
    });
}

function initProductBrowser() {
    $('#productBrowser .info').hover(function() {
        $('#productBrowser .info').each(function() { $(this).css({backgroundImage : $(this).css("background-image").split("_on").join("_off")}); });
        $(this).css({backgroundImage : $(this).css("background-image").split("_off").join("_on")});
        $(this).parent().find('.details span').text($(this).text());
    }, function() {
        $('#productBrowser .info').each(function() { $(this).css({backgroundImage : $(this).css("background-image").split("_off").join("_on")}); });
        $(this).parent().find('.details span').text('');
    });
}

	function homepageHero() {
		if ($('#herohome').length == 0) return;
		
		var speedRotation = 3000;
		var speedFade = 1000;
		
		var index = 0;
		var lastIndex = $('#hero li').length - 1;
		
		$('.herohome li').not(':eq(' + (index++) + ')').hide();
		
		setInterval(function() {
			$('#herohome li:visible').fadeOut(speedFade);
			$('#herohome li:eq(' + (index++) + ')').fadeIn(speedFade);
			if (index > lastIndex) index = 0;
		}, speedRotation);
	}
	
	function initHeader() {
		$("#header .h1").fadeIn(1500);
		
		$("#homelink").hover(
			function(){$(this).attr({ src: "/Common/Images/buttonHomeOver.gif"});},
			function(){$(this).attr({ src: "/Common/Images/buttonHome.gif"});}
		);
	}
function gaEvent(t, l) {
    try {
        pageTracker._trackPageview('/' + t + '/' + l);
    }
    catch (err) {
    }
}

$(document).ready(function() {
    $('img.rollover, input.rollover').rollover();

    $('#ctl00_holderPage_Optin_newsletter_optin_0').attr('checked', true);

    initHome();

    initHeader();
	
	homepageHero();

    initTabs();

    initProductBrowser();

    initRecipeRater();

    $("a[href][rel='external']").attr("target", "_blank");

    // Analytics tracker for files, media and internal layers
    $("a[href][rel='pdf']").attr("target", "_blank").click(function() { gaEvent('PDF', $(this).attr('href')); });

    $('#backToListing').click(function() { history.go(-1); return false });    
    
    /* ## my coffee my barista promo scripts  ## */
    
    $('#my-barista').addClass('js');
    $('#my-barista .prompt-label').each(function(index) {
        if($(this).next().val() == '') $(this).next().val($(this).html());
        
    });
        
    $('#my-barista input[type="text"]').focus(function() {
        if($(this).val() == $(this).prev().html())
            $(this).val('');
    }).blur(function() {
        if($(this).val() == '')
            $(this).val($(this).prev().html());
    });
    $('#my-barista li:odd').addClass('odd');
    

});

function trim(s) {
    return s.replace(/^\s+|\s+$/, '');
}

function validateForm()
{   
    var index = 0;
    var s ='Please enter the following:\n';
    var isValid = true;
    for(index=0;index<arguments.length;index++) {
    
    if(trim(document.getElementById(arguments[index]).value)=='') {
        isValid = false;
        var name = arguments[index].substring(arguments[index].lastIndexOf("_") + 1);
        if(name=='firstName')
            s = s + 'First name\n';
        if(name=='lastName')
            s = s + 'Las name\n';
        if(name=='address')
            s = s + 'Address\n';    
        if(name=='suburb')
            s = s + 'Suburb\n';
        if(name=='state')
            s = s + 'State\n';
        if(name=='postcode')
            s = s + 'Postcode\n';   
         if(name=='phone')
            s = s + 'Phone\n';
         if(name=='businessName')
            s = s + 'Business name\n';
         if(name=='businessType')
            s = s + 'Business type\n';
         if(name=='email')
            s = s + 'Email address\n';  
            
         if(name=='productPurchased')
            s = s + 'Product purchased\n';
            
        if(name=='dateOfPurchase')
            s = s + 'Date of purcahse\n';
        if (name == 'outletPhoneNo')
            s = s + 'Outlet phone\n';   
            
         if(name=='branch')
            s = s + 'Branch\n';
            
    }
}
if (!isValid) {
    alert(s);
    return false;
}
}

