$(document).ready(function() {
    /* Clears input value on blur */
    $('.default-value').each(function() {
        var default_value = this.value;
        $(this).focus(function() {
            if (this.value == default_value) {
                this.value = '';
            }
        });
        $(this).blur(function() {
            if (this.value == '') {
                this.value = default_value;
            }
        });
    });

    /* Sets default values on form elements */
    $('.DefaultValue').each(function() {
        if (!this.disabled) {
            this.focus();
            this.blur();
        }
    });
    
    /* Hack to hide the rating window so the default labels take effect*/
    try
    {
        $("#recipe_rating_wrapper").hide();
    }
    catch(err){ }

    /* Utility Sub Nav */
    $("#for_HCP").hover(function() {
        $('#for_HCP').css('height', '135px');
        $('#for_HCP_sub').css('display', 'block');
        $(this).toggleClass("active");
    });
    $("#for_HCP").mouseleave(function() {
        $('#for_HCP').css('height', '');
        $('#for_HCP_sub').css('display', 'none');
    });

    /* Main Sub Nav */
    var rootLocation = location.pathname.split("/")[1];
    rootLocation = "/" + rootLocation;
    var activeTab = $("#main_nav").find('*[href="' + rootLocation + '"]');
    var sliding = false;
    var slideUp = false;
    $("#main_nav_container").hoverIntent(subNavIn, subNavOut);
    function subNavIn() {
        if (!sliding) {
            sliding = true;
            $('#main_nav_sub').slideDown(function() { sliding = false; if (slideUp) { subNavOut(); } });
            if (activeTab != null) {
                $(activeTab).removeClass("active");
            }
        }
    }
    function subNavOut() {
        if (!sliding) {
            slideUp = false;
            sliding = true;
            $('#main_nav_sub').slideUp(function() { sliding = false; });
            if (activeTab != null) {
                $(activeTab).addClass("active");
            }
        } else {
            slideUp = true;
        }
    }

    $('div.topBlock').click(function() {
        $('ul.dropList').slideToggle(400);
    });
    $('ul.dropList').click(function() {
        $('ul.dropList').slideToggle(400);
    });
    $('.dropList li a').click(function() { //select value from list
        var val = $(this).text();
        $('.topBlock').text(val);
    });

    $("#our_products,#our_products_sub").mouseenter(function() {
        $("#our_products").addClass("active");
        $("#our_products_sub").addClass("active");
    });
    $("#our_products,#our_products_sub").mouseleave(function() {
        $("#our_products").removeClass("active");
        $("#our_products_sub").removeClass("active");
    });
    $("#experts_on_nutrition,#experts_on_nutrition_sub").mouseenter(function() {
        $("#experts_on_nutrition").addClass("active");
        $("#experts_on_nutrition_sub").addClass("active");
    });
    $("#experts_on_nutrition,#experts_on_nutrition_sub").mouseleave(function() {
        $("#experts_on_nutrition").removeClass("active");
        $("#experts_on_nutrition_sub").removeClass("active");
    });
    $("#boost_in_your_life,#boost_in_your_life_sub").mouseenter(function() {
        $("#boost_in_your_life").addClass("active");
        $("#boost_in_your_life_sub").addClass("active");
    });
    $("#boost_in_your_life,#boost_in_your_life_sub").mouseleave(function() {
        $("#boost_in_your_life").removeClass("active");
        $("#boost_in_your_life_sub").removeClass("active");
    });
    $("#coupons_and_more,#coupons_and_more_sub").mouseenter(function() {
        $("#coupons_and_more").addClass("active");
        $("#coupons_and_more_sub").addClass("active");
    });
    $("#coupons_and_more,#coupons_and_more_sub").mouseleave(function() {
        $("#coupons_and_more").removeClass("active");
        $("#coupons_and_more_sub").removeClass("active");
    });
    $(".search_button").hover(function() {
        $(this).toggleClass("active");
    });
    $("#full_nutritional_info").click(function() {
        $(this).toggleClass("active");
        $("#boost_original_nutrition_facts").toggleClass("active");
    });

    /* Light Boxes */
    $("a#buy_online").fancybox(); /* Top Nav */
    $("a#choco_6_pack,a#choco_12_pack,a#van_6_pack,a#van_12_pack,a#straw_6_pack,a#straw_12_pack").fancybox(); /* Product Pages */
    $("a#buy_boost").fancybox(); /* Right Column Tout */
    $("a#thank_you_anchor").fancybox(); /* Ask Experts Page */
    $("a#footer_buy_online").fancybox(); /* Bottom Nav */
    //$("a#email_friend").fancybox(); /* Header */
    $("a#rate_recipe").fancybox(); /* Recipe Rating */

    /* Product Shots */
    $("body.boost_original #chocolate_bottles, body.boost_original #vanilla_bottles, body.boost_original #strawberry_bottles").click(function() {
        $(this).toggleClass("old");
    });
    $("body.calorie_smart #chocolate_bottles, body.calorie_smart #vanilla_bottles").click(function() {
        $(this).toggleClass("old");
    });
    $("body.boost_plus #chocolate_bottles, body.boost_plus #vanilla_bottles, body.boost_plus #strawberry_bottles").click(function() {
        $(this).toggleClass("old");
    });    
    $("body.high_protein_drink #chocolate_bottles, body.high_protein_drink #vanilla_bottles, body.high_protein_drink #strawberry_bottles").click(function() {
        $(this).toggleClass("old");
    });
    $("body.high_protein_mix #chocolate_bottles").click(function() {
        $(this).toggleClass("old");
    });
    $("body.glucose_control #chocolate_bottles, body.glucose_control #vanilla_bottles").click(function() {
        $(this).toggleClass("old");
    });
    
    $("#rich_chocolate,#very_vanilla,#creamy_strawberry").click(function() {
        $("#rich_chocolate,#very_vanilla,#creamy_strawberry").removeClass("active");
        $(this).toggleClass("active");
    });
    $("#chocolate,#vanilla,#strawberry").click(function() {
        $("#chocolate,#vanilla,#strawberry").removeClass("active");
        $(this).toggleClass("active");
    });
    $("#rich_chocolate,#chocolate").click(function() {
        $("#vanilla_packs,#strawberry_packs,#chocolate_12_pack").hide();
        $("#chocolate_packs,#chocolate_6_pack").show();
        $("#chocolate_12_link").removeClass("active");
        $("#chocolate_6_link").addClass("active");
    });
    $("#very_vanilla,#vanilla").click(function() {
        $("#chocolate_packs,#strawberry_packs,#vanilla_12_pack").hide();
        $("#vanilla_packs,#vanilla_6_pack").show();
        $("#vanilla_12_link").removeClass("active");
        $("#vanilla_6_link").addClass("active");
    });
    $("#creamy_strawberry,#strawberry").click(function() {
        $("#chocolate_packs,#vanilla_packs,#strawberry_12_pack").hide();
        $("#strawberry_packs,#strawberry_6_pack").show();
        $("#strawberry_12_link").removeClass("active");
        $("#strawberry_6_link").addClass("active");
    });
    $("#chocolate_6_link").click(function() {
        $("#chocolate_12_link").removeClass("active");
        $(this).addClass("active");
    });
    $("#chocolate_12_link").click(function() {
        $("#chocolate_6_link").removeClass("active");
        $(this).addClass("active");
    });
    $("#vanilla_6_link").click(function() {
        $("#vanilla_12_link").removeClass("active");
        $(this).addClass("active");
    });
    $("#vanilla_12_link").click(function() {
        $("#vanilla_6_link").removeClass("active");
        $(this).addClass("active");
    });
    $("#strawberry_6_link").click(function() {
        $("#strawberry_12_link").removeClass("active");
        $(this).addClass("active");
    });
    $("#strawberry_12_link").click(function() {
        $("#strawberry_6_link").removeClass("active");
        $(this).addClass("active");
    });

    $("#original_rm1").click(function() {
        $("#original_hellip1").css('display', 'none');
        $("#original_overflow1").css('display', 'inline');    
        $(this).css('display', 'none');
    });
    $("#original_rm2").click(function() {
        $("#original_hellip2").css('display', 'none');
        $("#original_overflow2").css('display', 'inline');
        $(this).css('display', 'none');
    });
    $("#hp_rm1").click(function() {
        $("#hp_hellip1").css('display', 'none');
        $("#hp_overflow1").css('display', 'inline');
        $(this).css('display', 'none');
    });
    $("#hp_rm2").click(function() {
        $("#hp_hellip2").css('display', 'none');
        $("#hp_overflow2").css('display', 'inline');
        $(this).css('display', 'none');
    });
    $("#hp_rm3").click(function() {
        $("#hp_hellip3").css('display', 'none');
        $("#hp_overflow3").css('display', 'inline');
        $(this).css('display', 'none');
    });
    $("#plus_rm1").click(function() {
        $("#plus_hellip1").css('display', 'none');
        $("#plus_overflow1").css('display', 'inline');
        $(this).css('display', 'none');
    });
    $("#plus_rm2").click(function() {
        $("#plus_hellip2").css('display', 'none');
        $("#plus_overflow2").css('display', 'inline');
        $(this).css('display', 'none');
    });
    $("#gc_rm1").click(function() {
        $("#gc_hellip1").css('display', 'none');
        $("#gc_overflow1").css('display', 'inline');
        $(this).css('display', 'none');
    });
    $("#gc_rm2").click(function() {
        $("#gc_hellip2").css('display', 'none');
        $("#gc_overflow2").css('display', 'inline');
        $(this).css('display', 'none');
    });

    /* Font size settings */
    var defaultFontSize = 16;
    $(".resetFont").click(function() {
        $('html').css('font-size', defaultFontSize + "px");
    });
    // Increase Font Size
    $(".increaseFont").click(function() {
        var currentFontSize = $('html').css('font-size');
        var currentFontSizeNum = parseInt(currentFontSize);
        var newFontSize = currentFontSizeNum + 3;
        if (newFontSize <= 22) {
            Set_Cookie("fontsize", newFontSize, 1, "/", "", "");
            $('html').css('font-size', newFontSize);
        }
        return false;
    });
    // Decrease Font Size
    $(".decreaseFont").click(function() {
        var currentFontSize = $('html').css('font-size');
        var currentFontSizeNum = parseInt(currentFontSize);
        var newFontSize = currentFontSizeNum - 3;
        if (newFontSize >= 10) {
            Set_Cookie("fontsize", newFontSize, 1, "/", "", "");
            $('html').css('font-size', newFontSize);
        }
        return false;
    });
    // Set the font size if the user has changed it
    var setFontSize = Get_Cookie("fontsize");
    if (setFontSize != null && setFontSize != "") {
        var setFontSize = Get_Cookie("fontsize");
        $('html').css('font-size', setFontSize + "px");
    }

    $.preloadCssImages();
});

function SetNutrition(link){
    $(".nutfacts").css("display","none");
    $("#" + $(link).attr("rel")).css("display","block");
}

function HideContent(d) {
	document.getElementById(d).style.display = "none";
}
function ShowContent(d) {
	document.getElementById(d).style.display = "block";
}
function ReverseDisplay(d) {
    if(document.getElementById(d).style.display == "none") { document.getElementById(d).style.display = "block"; }
    else { document.getElementById(d).style.display = "none"; }
}
function HideAll() {
	HideContent('product1');
	HideContent('product2');
	HideContent('product3');
	HideContent('product4');
	HideContent('product5');
}
function HideBottles() {
    HideContent('chocolate_bottles');
    HideContent('vanilla_bottles');
    HideContent('strawberry_bottles');
}
function HideBottles2() {
    HideContent('chocolate_bottles');
    HideContent('vanilla_bottles');
}
var passwordFields = [];
function DefaultValue(field, defaulttext) {
    if (field.disabled) {
        return;
    }
    changeInputType(field, "text", defaulttext, false, true);
}
function ExistsInArray(array, value) {
    var len = array.length;
    for (var i = 0; i < len; i++) {
        if (array[i] == value) {
            return true;
        }
    }
    return false;
}

//oldElm - a reference to the input element
//iType - value of the type property: 'text' or 'password'
//iValue - the default value, set to 'password' in the demo
//blankValue - true if the value should be empty, false otherwise
//noFocus - set to true if the element should not be given focus
function changeInputType(oldElm, iType, iValue, blankValue, noFocus) {
    if (oldElm.type == "password") {
        if (!ExistsInArray(passwordFields, oldElm.id)) {
            passwordFields.push(oldElm.id);
        }
    }

    if (!oldElm || !oldElm.parentNode || (iType.length < 4) || !document.getElementById || !document.createElement) {
        return;
    }

    var isMSIE = /*@cc_on!@*/false; //http://dean.edwards.name/weblog/2007/03/sniff/
    if (!isMSIE) {
        var newElm = document.createElement('input');
        newElm.type = iType;
    } else {
        var newElm = document.createElement('span');
        newElm.innerHTML = '<input type="' + iType + '" name="' + oldElm.name + '">';
        newElm = newElm.firstChild;
    }

    var props = ['name', 'id', 'className', 'size', 'tabIndex', 'accessKey', 'autocomplete', 'onkeypress'];
    for (var i = 0, l = props.length; i < l; i++) {
        if (oldElm[props[i]]) {
            newElm[props[i]] = oldElm[props[i]];
        }
    }

    var existingclass = oldElm["className"];
    existingclass = existingclass.replace("DefaultValue entered", "");
    existingclass = existingclass.replace("DefaultValue", "");
    existingclass = existingclass.trim();

    if (oldElm["value"] == "" && oldElm["value"] != iValue) {
        newElm["className"] = existingclass + " DefaultValue";
    } else {
        newElm["className"] = existingclass + " DefaultValue entered";
    }

    newElm.onfocus = function() {
        return function() {
            if (this.hasFocus) {
                return;
            }

            var type = "text";
            //Check and see if this is a password field
            if (ExistsInArray(passwordFields, oldElm.id)) {
                type = "password";
            }

            var newElm = changeInputType(this, type, iValue, (this.value.toLowerCase() == iValue.toLowerCase()) ? true : false);
            if (newElm) {
                newElm.hasFocus = true;
            }
        }
    } ();
    
    newElm.onblur = function() {
        return function() {
            if (this.hasFocus) {
                if (this.value == '' || (this.value.toLowerCase() == iValue.toLowerCase())) {
                    changeInputType(this, 'text', iValue, false, true);
                }
            }
        }
    } ();
    
    //hasFocus is to prevent a loop where onfocus is triggered over and over again
    newElm.hasFocus = false;
    //Some browsers need the value set before the element is added to the page
    //while others need it set after
    if (!blankValue) {
        if (oldElm["value"] == "") {
            newElm.value = iValue;
        } else {
            newElm.value = oldElm["value"];
        }
    }
    oldElm.parentNode.replaceChild(newElm, oldElm);
    if (!isMSIE && !blankValue) {
        if (oldElm["value"] == "") {
            newElm.value = iValue;
        } else {
            newElm.value = oldElm["value"];
        }
    }
    if (!noFocus || typeof (noFocus) == 'undefined') {
        window.tempElm = newElm;
        setTimeout("tempElm.hasFocus=true;tempElm.focus();", 1);
    }
    return newElm;
}

String.prototype.trim = function() {
	return this.replace(/(?:(?:^|\n)\s+|\s+(?:$|\n))/g,"").replace(/\s+/g," ");
}

function Search(type) {
    if ($("#SearchInput").val() != "undefined" && $("#SearchInput").val() != "Search Here" && $("#SearchInput").val() != "") {
        var previousSearchTerms = [];
        var previousSearchTermsJSON = Get_Cookie("previousSearchTerms");
        if (previousSearchTermsJSON != null && previousSearchTermsJSON != "") {
            previousSearchTerms = JSON.parse(previousSearchTermsJSON);
        }
        previousSearchTerms.push($("#SearchInput").val());
        previousSearchTermsJSON = JSON.stringify(previousSearchTerms);
        Set_Cookie("previousSearchTerms", previousSearchTermsJSON, 1, "/", "", "");
        var searchQuery = "/search?q=" + $("#SearchInput").val();
        if (type != null && type == "hcp") {
            searchQuery += "&hcp=true";
        }
        window.location = searchQuery;
    }
}
function OnEnterSearch(e) {
    if (window.event) { e = window.event; }
    if (e.keyCode == 13) {
        //Search();
        $("#search_button").click();
    }
    return (e.keyCode != 13);
}
function postBackOnEnter(e, UniqueButtonID) {
    if (window.event) { e = window.event; }
    if (e.keyCode == 13) {
        __doPostBack(UniqueButtonID, "");
    }
    return (e.keyCode != 13);
}
var starHover = false;
function starmousein(star) {
    starHover = true;
    var starData = star.id.split("_");
    var currentRecipeID = parseInt(starData[0]);
    var currentRating = parseInt(starData[1]);
    var currentHoverStar = parseInt(starData[2]);
    for (var i = 1; i <= currentHoverStar; i++) {
        var changestar = document.getElementById(currentRecipeID + "_" + currentRating + "_" + i);
        changestar.setAttribute("src", "/images/gold-star.png");
    }
    var fillerStart = currentHoverStar + 1;
    for (var i = fillerStart; i <= 5; i++) {
        var changestar = document.getElementById(currentRecipeID + "_" + currentRating + "_" + i);
        changestar.setAttribute("src", "/images/empty-star.gif");
    }
}
function starmouseout(star, rating) {
    starHover = false;
    setTimeout(function() { startmouseout_callback(star, rating) }, 100);
}
function startmouseout_callback(star, rating) {
    if (starHover == false) {
        var starData = star.id.split("_");
        var currentRecipeID = parseInt(starData[0]);
        var currentRating = parseInt(starData[1]);
        var currentHoverStar = parseInt(starData[2]);
        for (var i = 1; i <= currentRating; i++) {
            var changestar = document.getElementById(currentRecipeID + "_" + currentRating + "_" + i);
            changestar.setAttribute("src", "/images/star.png");
        }
        for (var i = currentRating + 1; i <= 5; i++) {
            var changestar = document.getElementById(currentRecipeID + "_" + currentRating + "_" + i);
            changestar.setAttribute("src", "/images/empty-star.gif");
        }
    }
}


// ####################
// Cookie Manipulation
// ####################

function Set_Cookie(name, value, expires, path, domain, secure) {
    // set time, it's in milliseconds
    var today = new Date();
    today.setTime(today.getTime());

    /*
    if the expires variable is set, make the correct 
    expires time, the current script below will set 
    it for x number of days, to make it for hours, 
    delete * 24, for minutes, delete * 60 * 24
    */
    if (expires) {
        expires = expires * 1000 * 60 * 60 * 24;
    }
    var expires_date = new Date(today.getTime() + (expires));

    document.cookie = name + "=" + escape(value) +
		((expires) ? ";expires=" + expires_date.toGMTString() : "") +
		((path) ? ";path=" + path : "") +
		((domain) ? ";domain=" + domain : "") +
		((secure) ? ";secure" : "");
}

// this function gets the cookie, if it exists
function Get_Cookie(name) {
    var start = document.cookie.indexOf(name + "=");
    var len = start + name.length + 1;
    if ((!start) && (name != document.cookie.substring(0, name.length))) {
        return null;
    }
    if (start == -1) return null;
    var end = document.cookie.indexOf(";", len);
    if (end == -1) end = document.cookie.length;
    return unescape(document.cookie.substring(len, end));
}

// this deletes the cookie when called
function Delete_Cookie(name, path, domain) {
    if (Get_Cookie(name)) document.cookie = name + "=" + ((path) ? ";path=" + path : "") + ((domain) ? ";domain=" + domain : "") + ";expires=Thu, 01-Jan-1970 00:00:01 GMT";
}

function checkEmail(address) {
    if (/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(address)) {
        return true;
    }
    return false;
}
function DefaultValue(field, defaulttext) {
    if (field.disabled) {
        return;
    }
    changeInputType(field, "text", defaulttext, false, true);
}

function queryString(key) {
    hu = window.location.search.substring(1);
    gy = hu.split("&");
        for (i=0;i<gy.length;i++) {
            ft = gy[i].split("=");
            if (ft[0] == key) {
            return ft[1];
        }
    }
}
