﻿var TARGET_FLASH_VERSION = "9.0.0"
var FLAVOR_DEFAULT = "Tangerine";
var DEEPLINK_URL = "";
var PRETEXT = 'all-natural protein';
var deepLinkTab;
var $tabs;
var FLOWPLAYER_VIDEO_PATH = '/resources/flowplayer/flowplayer.commercial-3.1.5.swf';
var FLOWPLAYER_LICENSE_KEY = '#@2352127c8879a1ea191';



jQuery.preloadImages = function() {
    for (var i = 0; i < arguments.length; i++) {
        jQuery("<img>").attr("src", arguments[i]);
    }
}

function embedFlash() {


    //    // hash doesn't contain the first # character.
    //    var doc_location = document.location.pathname;
    //    //    ////////////////alert(doc_location);
    //    //    if (!hasFlash() && doc_location != '/home.aspx') {
    //    //        document.location = "/home.aspx";
    //    //        return;
    //    //    }

    //    $(document).ready
    //    (
    //        function() {
    //            var flashvars = { preloaderText: PRETEXT, flavorName: getLastTheme(), resourceDirectory: "/", playIntro: 1 };
    //            var params = {};
    //            var attributes = {};
    //            params.wmode = "transparent";

    //            //insertSwf("/App_RIA/Mix1_BottleHero.swf", params, flashvars, attributes);
    //        }
    //    )
}

function insertSwf(swfPath, params, flashvars, attributes) {

    //    swfobject.embedSWF(swfPath, "content_flash", "100%", "100%", TARGET_FLASH_VERSION,
    //                        "expressInstall.swf", flashvars, params, attributes);
}

function setRandomTheme() {

    //insertSwf("dummy.swf", {}, {}, {});    //this is just to clear any contents


    var url = "/Sitefinity/Default.aspx?flavor=" + FLAVOR_DEFAULT + "&getnutritioninfo=2";

    $.get(url, {},
          function(data) {
              if ($.cookie('last_flavor') == null || $.cookie('last_flavor') == '') {
                  $.cookie('last_flavor', data.toString());
              }


              embedFlash();
          });
}

$(document).ready
(
    function() {

        //$.historyInit(pageload);
        setupRIAMenu();
        setLastTheme();
        setUpLocationFinder();
        setUpVideoCalls(false);


    }
);

function checkNoFlash() {

}

function hasFlash() {

    //return swfobject.hasFlashPlayerVersion(TARGET_FLASH_VERSION);
    return false;
}


//play any video with an html element with id of "player"
//using the url atrribute of that element
function playVideoDefault() {
    if (swfobject.hasFlashPlayerVersion(TARGET_FLASH_VERSION)) {
    		if ($('#player').length) {
            flowplayer("player", FLOWPLAYER_VIDEO_PATH, {
                clip: { autoPlay: false }, key: FLOWPLAYER_LICENSE_KEY
            });
        }
    	
        if ($('.flowplayer').length) {
            flowplayer("div.flowplayer", FLOWPLAYER_VIDEO_PATH, {
                clip: { autoPlay: false }, key: FLOWPLAYER_LICENSE_KEY
            });
        }
    }
}


//play any video with an html element with id of "player",
// passing url of flv (mainly for the what and why mix1 sections)
function playVideo(videoUrl) {

    if (swfobject.hasFlashPlayerVersion(TARGET_FLASH_VERSION)) {
        if ($('#player-mini').length) {
            $('#player-mini').fadeIn();
            flowplayer("player-mini", FLOWPLAYER_VIDEO_PATH, {
                clip: {
                    autoPlay: true
                },
                playlist: [
                    videoUrl
                ],
                key: FLOWPLAYER_LICENSE_KEY,
                plugins: {

                    controls: {

                        autoHide: 'always',
                        backgroundGradient: 'low',
                        borderRadius: 13,
                        bottom: 5,
                        hideDelay: 1000,
                        left: '50%',
                        width: '90%'

                    }

                }
            });
        }
    }



    //    try {
    //        if (hasFlash()) {
    //            var doc = window.parent ? window.parent.document : window.document;
    //            //x:int = 30, y:int = 180, height:int = 216, width:int = 291
    //            doc.getElementById('content_flash').playVideo(videoUrl, 10, 230, 146, 265);
    //        }
    //    }
    //    catch (e) { }
}

function stopVideo() {
    ////////////////alert("stopVideo");
    try {
        if (hasFlash()) {
            var doc = window.parent ? window.parent.document : window.document;
            doc.getElementById('content_flash').stopVideo();
        }
    }
    catch (e) { }
}

function setUpVideoCalls(tabs) {

    playVideoDefault();

    if (!tabs) {
        //hotspots on compare
        $("#hs_protein_protein_shake").click(function() { stopVideo(); playVideo('/resources/vid/MIX_1_Web_05_ProRes.flv'); });
        $("#hs_protein_antioxidant_fiber").click(function() { stopVideo(); playVideo('/resources/vid/MIX_1_Web_05_ProRes.flv'); });
        $("#hs_carbohydrates_protein_shake").click(function() { stopVideo(); playVideo('/resources/vid/MIX_1_Web_07_ProRes.flv'); });
        $("#hs_carbohydrates_antioxidant_fiber").click(function() { stopVideo(); playVideo('/resources/vid/MIX_1_Web_07_ProRes.flv'); });
        $("#hs_fiber_protein_shake").click(function() { stopVideo(); playVideo('/resources/vid/MIX_1_Web_08_ProRes.flv'); });
        $("#hs_fiber_antioxidant_fiber").click(function() { stopVideo(); playVideo('/resources/vid/MIX_1_Web_08_ProRes.flv'); });
        $("#hs_fat_antioxidant_fiber").click(function() { stopVideo(); playVideo('/resources/vid/MIX_1_Web_09_ProRes.flv'); });
        $("#hs_fat_protein_shake").click(function() { stopVideo(); playVideo('/resources/vid/MIX_1_Web_09_ProRes.flv'); });
        $("#hs_sugars_protein_shake").click(function() { stopVideo(); playVideo('/resources/vid/MIX_1_Web_10_ProRes.flv'); });
        $("#hs_sugars_antioxidant_fiber").click(function() { stopVideo(); playVideo('/resources/vid/MIX_1_Web_10_ProRes.flv'); });
        $("#hs_antioxidants_antioxidant_fiber").click(function() { stopVideo(); playVideo('/resources/vid/MIX_1_Web_06_ProRes.flv'); });
        $("#hs_antioxidants_protein_shake").click(function() { stopVideo(); playVideo('/resources/vid/MIX_1_Web_06_ProRes.flv'); });
    }

}

var loading = false;
var lastIeUrl = '';

function pageload(hash) {
    //alert('pageload');
    //fix for a screwed up bug in ie6, where querystring pages are getting forced back to same url with no qrystring!!!
    if (jQuery.browser.msie && jQuery.browser.version < 7) {
        if (lastIeUrl.indexOf(hash) >= 0 && lastIeUrl.indexOf("?") >= 0) {
            ////////alert(hash + ' ' + lastIeUrl);

            lastIeUrl = '';
            return;
        }
    }

    //end ie6 fix!!!

    var doc_location = document.location.pathname;


    if (hash && !firstLoad) {
        loadOverlayData(hash);
        if (hash == "" || hash.indexOf("/home.aspx") >= 0) {
            clearOverlay();
        }
    }
    else {
        if (DEEPLINK_URL == '') {

            if (doc_location == '/home.aspx') {
                clearOverlay();
            }
        }
    }

    lastIeUrl = hash;
    DEEPLINK_URL = '';
    firstLoad = false;
    lastThemeType = '';
}


function setUpLink(thisLink, event) {

    var thisUrl = thisLink.attr("href").toLowerCase();

    if (thisLink.attr("target") != "_blank" && thisLink.attr("ignore") != "true" && thisUrl.indexOf(".flv") < 0 && thisUrl.indexOf("mailto:") < 0) {

        sendRIACall(thisLink.attr("href"), event);

        return false;
    }

    if (thisUrl.indexOf(".flv") >= 0) {
        event.preventDefault(); //String, x:int = 30, y:int = 180, height:int = 216, width:int = 291
        playVideo(thisUrl);
        return false;
    }
}


/**display menu flash is fully loaded**/
var flashLoaded = false;
function preloaderComplete() {
    //alert("preloaderComplete");
    $("#nav").fadeIn("slow", handleDeepLink());
    //$("#search").fadeIn("slow");
    $("#copyright").fadeIn("slow");
    if (isHomePage()) showNewsTicker();
    flashLoaded = true;
}

//add toolip to location finder if exists on page
function setUpLocationFinder() {
    if ($("#location_finder_container").length > 0) {

        $("map *").tooltip({ showURL: false, track: true, transparency: .8 });
    }
}

//set up function calls for bottle menu to change site theme (this is for html version)
function setupImageMap() {
    ////alert("setupImageMap");
    var tooltipCss = "url('" + $("#hf_toolipimage").attr("value") + "')";

    $("map *").tooltip({
        delay: 0,
        showURL: false,
        track: true,
        top: -20,
        bodyHandler: function() {
            var tooltipText = "<h1 class='" + $.cookie('last_flavor') + "'>" + $(this).attr("label") + "</h1>";
            return $("<div/>").attr("class", "bubble").css("background-image", tooltipCss).html(tooltipText);
        }
    });

    $("#map_protein_shake > area").click(
             function(event) {
                 event.preventDefault();
                 nutritionSwap($(this).attr("id"), $(this).attr("nuttype"));


             }
        );

    $("#map_antioxidant_fiber > area").click(
             function(event) {
                 event.preventDefault();
                 nutritionSwap($(this).attr("id"), $(this).attr("nuttype"));

             }
        );
}

var lastType = "";
function nutritionSwap(id, type) {

    ////alert(id);

    $("#nut_title").html("Loading...");
    $("#nut_container").slideUp("fast");

    var lastTheme = getLastTheme();

    //tabs
    if (type == "protein_shake") {
        $("#" + type).attr({ src: "/Images/nutrition/protein_shake_tab_on.gif" });
        $("#antioxidant_fiber").attr({ src: "/Images/nutrition/anti_fiber_tab_off.gif" });
        if (lastThemeType == 'antioxidant') lastTheme = "tangerine";
        if (type != lastType) {
            window.setTimeout("playInitialVideo('/resources/vid/MIX_1_Web_07_ProRes.flv')", 500);
        }
    }
    else {
        $("#protein_shake").attr({ src: "/Images/nutrition/protein_shake_tab_off.gif" });
        $("#" + type).attr({ src: "/Images/nutrition/anti_fiber_tab_on.gif" });
        if (lastThemeType == 'protein') lastTheme = "dark berry";
        if (type != lastType) {
            window.setTimeout("playInitialVideo('/resources/vid/MIX_1_Web_06_ProRes.flv')", 500);
        }
    }

    var name = id.replace("hs_", "").replace("_" + type, "");
    var displayDivId = id.replace("hs_", "#nd_");
    var divData = $(displayDivId).html();
    ////alert(displayDivId);

    $("#nut_title").html(name);
    $("#nut_title").attr("class", lastFlavorClass); //this is to init the class

    $("#nut_container").html(divData);
    $("#nut_container").slideDown("fast");
    ////////alert('setBottleTheme:nutritionswap');
    setBottleTheme(lastTheme);

    $("#nut_bottle img").attr({ useMap: "#map_" + type });
    $("#nut_bottle img").slideDown("fast");

    lastType = type;
}


function setBottleTheme(lastTheme) {
    $("#nut_bottle img").attr({ src: "/Images/nutrition/" + lastTheme + "_bottle.gif" });
}

//set up the main nav menu as jquery calls, if flash is installed (this should probably be called from the swf itself...)
function setupRIAMenu() {
    if (hasFlash()) {
        $("#main_nav_menu_container > div > ul > li > a").click(
             function(event) {
                 setUpLink($(this), event);
             }
        );
        $("#nav").css("display", "none");
        //$("#search").css("display", "none");
        $("#co/pyright").css("display", "none");
    }
    else {

        handleNonFlashVersion();

    }
}

//handle logic if no flash is enabled
function handleNonFlashVersion() {

    $("#content_right").addClass("htmlOnly");

    $("#nav").css("display", "block");
    //$("#search").css("display", "block");

    $("#bottle-picker ul").hover(
          function() {
              $("#bottle_menu").animate({ top: "384px" }, 250);
              //$(this).css("opacity", "0.5");
          },
          function() {
              $("#bottle_menu").animate({ top: "394px" }, 250);
              //$(this).css("opacity", "1.0");
          }
        );

    $("#bottle-picker ul li a").hover(
          function() {
              //$("#bottle_menu").animate({ top: "384px" }, 250);
              $(this).css("opacity", "0.5");
          },
          function() {
              //$("#bottle_menu").animate({ top: "394px" }, 250);
              $(this).css("opacity", "1.0");
          }
        );

    $("#bottle-picker ul li a").click(
           function(evt) {
               var pos = $(this).position();
               //console.log('click');
               evt.preventDefault();
               var requestedMenu = $(this).attr('href').split('-');

               //alert("theme " + requestedMenu[0]);
               setTheme(requestedMenu[0]);
               //alert(FLAVOR_OPERATION);
               var urlBase = getUrlBase(requestedMenu[0]) + FLAVOR_OPERATION + "&menuLayout="
                                        + requestedMenu[1];
               $.get(urlBase, {},
                   function(data) {
                       ////////alert("img call " + data);
                       //if interior page, set the interior menu image
                       if (FLAVOR_OPERATION == 3)
                           $("#secondary_menu_image_container img").attr("src", data);
                       else if (FLAVOR_OPERATION == 4)
                           $(".home img").attr("src", data);
                   });

               //               var pos = $(this).position();
               //               //////alert(pos.left);
               $("#bottle_arrow_container img").css("padding-left", pos.left + "px");

               //$(".hidden-current-flavor").attr("value", requestedMenu[0]);


           }
        );

    var agent = navigator.userAgent.toLowerCase();
    var is_iphone = agent.indexOf('iphone') != -1;
    if (is_iphone) {
        $("#download_flash").css('display', 'none');
    }

    $("#copyright").css('display', 'block');
    if (isHomePage()) showNewsTicker();
}

function handleNonFlashVersionTabs() {
    addDivNav();
    $("#content_right_flash_divnav").css('margin-left', '17px');
    //setupMainNavDiv();
}

function isHomePage() {
    if (!hasFlash()) return document.location.toString().indexOf('home.aspx') > 0;

    if (DEEPLINK_URL != '') return false;
    if (window.document.location.hash == '' || window.document.location.hash == '/home.aspx') {
        return true;
    }

    return false;
}


//handle deeplink when site first hit
function handleDeepLink() {

    //alert("handleDeepLink");
    //if flash  installed AND this is the first time coming in
    ////////////////alert(DEEPLINK_URL);
    if (hasFlash()) {

        //firstLoad = true;

        if (window.document.location.hash) {
            //DEEPLINK_URL = window.document.location.hash;
            setUpHistory(window.document.location.hash);
        }
        else if (DEEPLINK_URL != '') {
            ////alert(DEEPLINK_URL);
            loadOverlayData(DEEPLINK_URL);
        }

        //DEEPLINK_URL = '';
    }
}

function setUpHistory(hash) {

    ////////alert("hash " + hash);
    hash = hash.replace(/^.*#/, '');
    //$.historyLoad(hash);

}

function getSection(link) {
    var sections = link.split("/");
    if (sections.length >= 3)
        return sections[2];
    return "";
}

var lastSection = '';
var firstMenu = true


function loadOverlayData(link) {

    ////////alert();
    //alert("loadOverlay");

    //update the flash menu, so the right menu node is highlighted
    ////////////////alert(link.substring(0, link.indexOf('?')));
    var linkCopy = link.indexOf('category-list.aspx') >= 0 ?
                     link.indexOf('&') >= 0 ? link.substring(0, link.indexOf('&')) :
                     link : link.indexOf('?') >= 0 ? link.substring(0, link.indexOf('?')) : link;

    //hack - blog detail page
    if (link.indexOf('blog-detail.aspx') >= 0)
        linkCopy = '/home/community/blog.aspx';

    var domain = document.domain;
    //////////////alert(domain);

    if (domain != undefined)
        linkCopy = linkCopy.replace("http://" + domain, "");


    var trig = lastSection == getSection(link) ? 500 : 2500;
    loadContent(link)
    //window.setTimeout("loadContent('" + link + "')", trig);
    lastSection = getSection(link);

}

function loadContent(link) {
    //////////////alert("loadContent " + link);
    //update the highlighted html menu
    $("#main_nav_menu_container > div > ul > li > a").each(
        function() {
            ////////////////alert($(this).attr("href").replace('.aspx', ''));
            ////////////////alert(link);
            if (link.indexOf($(this).attr("href").replace('.aspx', '')) > -1)
                $(this).addClass("selected");
            else
                $(this).removeClass("selected");
        }
    );
    ////////////////alert(link);
    if (link.indexOf('ajax=1') < 0)
        link += link.indexOf('?') >= 0 ? '&ajax=1' : '?ajax=1';

    $('#' + MIX1_DIV_ID).empty();
    mix1_loadurl(link, false);

    //rset div style (need fix for chrome)
    $("#content_right_flash").addClass("reset_right_flash");
    $("#content_right_flash_divnav").hide();
}

function playInitialVideo(url) {
    setUpVideoCalls(true);
    stopVideo();
    playVideo(url);
}

//send call to flash to bring trigger display of partial content
function sendRIACall(link, event) {

    ////////////////alert(link);
    if (event != null) {
        event.preventDefault();
    }

    //setUpHistory(link);
    loadOverlayData(link);

}

//set up function calls for bottle menu to change site theme (this is for html version)
function setupColorPicker() {
    $("#bottle_menu > div > a").click(
             function(event) {
                 switchTheme($(this).attr("href"), event);
             }
        );
}

//send call to flash to bring trigger display of partial content, store in cookie for next page visit
function switchTheme(link, event) {
    link = link.replace("#", "");
    $.cookie('last_flavor', link);
    setTheme(link);
    event.preventDefault();
}


//set the theme based on the cookie value, set default if cookie not set
function setLastTheme() {
    var lastTheme = getLastTheme();
    //console.log('setLastTheme: ' + lastTheme);
    setTheme(lastTheme);
}

function getLastTheme() {
    var lastTheme = $.cookie('last_flavor');
    if (lastTheme == null || lastTheme == '') {
        lastTheme = FLAVOR_DEFAULT;
    }
    //alert(lastTheme);
    return lastTheme;
}

var themeInited = false;

//here we will change the elements for the html:
//get the associated class for this flavor via ajax call and
//set the css class of the items on the page
//render nutrition info if exists
function setTheme(val) {

    if (val.length > 0) {
        //alert("settheme " + val);

        var valCopy = val.toLowerCase();
        var urlBase = getUrlBase(valCopy);
        var url = urlBase + "0";
        $.get(url, {},
          function(data) {
              //alert(data);
              appThemeToElements(data.toString());
              $.cookie('last_flavor', val);
              ////////alert($("#antioxidant_fiber").attr('src').indexOf('_on'));
              if ($("#antioxidant_fiber").attr('src') != undefined &&
                  $("#antioxidant_fiber").attr('src').indexOf('_on') > 0) {
                  if (lastThemeType == 'protein') val = 'Dark Berry';
              }
              else if ($("#antioxidant_fiber").attr('src') != undefined &&
                       $("#antioxidant_fiber").attr('src').indexOf('_on') < 0) {

                  if (lastThemeType == 'antioxidant') val = 'Tangerine';
              }

              ////////alert(val);
              setBottleTheme(val);

          });

        //for compare bottle
        ////////alert('setBottleTheme:settheme-a');

        if (!renderFirstLoad)
            setDefaultNutTab(val);


    }

}

function getUrlBase(val) {
    var valCopy = val.toLowerCase();
    return "/Sitefinity/Default.aspx?flavor=" + valCopy + "&getnutritioninfo=";
}

var lastFlavorClass = '';
var currentFlavorClass = '';

function appThemeToElements(flavorClass) {

    //////////alert("apptheme");


    $("#main_nav_menu_container").attr("class", flavorClass);

    setSelectedMenuItem(flavorClass);
    $("h1").each(

        function() {
            if ($(this).attr("class") != "profiles_title") {
                $(this).attr("class", flavorClass);
            }
        }
    );

    //blog special formatting
    $("#blog_posts_list #container #paging b").attr("class", flavorClass);
    $("#blog_posts_list #container #paging a").attr("class", "");

    //gen.content
    $("#generic_content h2").attr("class", flavorClass);

    //fans page
    $("#fan_links div a").attr("class", "");
    $("#contest_title").attr("class", flavorClass);

    //press
    $("#pressitem_list h2").attr("class", flavorClass);
    $("#pressitem_list #pressitem #item_container h3").attr("class", flavorClass);


    //mixology
    $("#cat #name").attr("class", flavorClass);
    //$("#pressitem_list #pressitem #item_container h3").attr("class", flavorClass);

    $("#val_summary").attr("class", flavorClass);

    //order online
    $("#order_online h2").attr("class", flavorClass);

    //event detail
    $('#event_date').attr("class", flavorClass);

    //news ticker
    $('#news_ticker a').attr("class", '');



    //compare section
    $('.mix1_data_big').each(
        function() { $(this).attr("class", "mix1_data_big " + flavorClass); }
    )
    $('.mix1_data_sm').attr("class", "mix1_data_sm ", flavorClass).each(
        function() { $(this).attr("class", "mix1_data_sm " + flavorClass); }
    )

    ////////////alert("appThemeToElements");
    $("#nut_title").attr("class", flavorClass);



    lastFlavorClass = flavorClass;

}

function setSelectedMenuItem(flavorClass) {
    ////////////////alert("setSelectedMenuItem");
    $("a").each(
            function() {
                if ($(this).attr("class") != "header" && $(this).attr("class").indexOf("ui-slider") < 0) {

                    var flavorClassTemp = $(this).attr("class").indexOf("selected") > 0 ? flavorClass + " selected" : flavorClass;
                    $(this).attr("class", flavorClassTemp)
                }
            }
        );
}

function clearMainMenu() {

    flavor = getLastTheme();
    $("#main_nav_menu_container > div > ul > li > a").each(
            function() { $(this).attr("class", flavor.toLowerCase()) }
     );
}


//call ajax load funtions to populate nutrition info display page (compare)
//these calls are handled in the UIController class in mix1.web.ui (the physical .aspx is just a stub to trigger the page handler)
var lastLink = '';
var firstLoad = true;
var renderFirstLoad = true;
function renderNutritionInfo(link) {

    //////alert("renderNutritionInfo");

    renderFirstLoad = true;
    if ($("#nut_container").length > 0) {
        ////////////////alert("render nut :" + link);
        lastLink = link;
        var url = "/Sitefinity/Default.aspx?flavor=" + getLastTheme() + "&getnutritioninfo=" + 1;
        ////alert(url);
        $.get(url, {},
          function(data) {

              var dataChunks = data.split("||");

              $("#nut_bottle").html(dataChunks[1]);
              $("#bottle_map").html(dataChunks[2]), setupImageMap();
              $("#hidden_data").html(dataChunks[3]), setDefaultNutTab(getLastTheme()), renderFirstLoad = false;

              //////alert(dataChunks[3]);

              $("#nut_bottle img").slideDown("fast");

              setUpVideoCalls(false);

          });
    }
    else {
        //////////////alert("clear last type");
        lastType = "";
    }
}


function getThemeType(theme) {
    if (theme == "Orange Carrot" || theme == "Dark Berry") {
        return "antioxidant";
    }
    else {
        return "protein";
    }
}

var lastThemeType = "";
var themeType = "";
var trackThemeType = "";

function setDefaultNutTab(theme) {
    //////alert("setDefaultNutTab");
    themeType = getThemeType(theme);
    if (themeType != lastThemeType) {
        //setLastTheme();

        if (themeType == "antioxidant") {
            nutritionSwap('hs_antioxidants_antioxidant_fiber', 'antioxidant_fiber');
            lastThemeType = "antioxidant";
        }
        else {
            nutritionSwap("hs_protein_protein_shake", "protein_shake");
            lastThemeType = "protein";
            ////////alert(currentFlavorClass);
            //setBottleTheme(currentFlavorClass);
        }
    }

}

//resizes columns (for compare nutrition info layout)
function setExpandCols() {
    $("#content_flash").attr("class", "xpand");
}


//test functions from flash

var MIX1_DIV_ID = "content_right_flash";
var MIX1_DIVNAV_ID = "content_right_flash_divnav";
var MIX1_PARENT_DIV_ID = "#container_main";
var THIS_DOMAIN = "localhost"; //should make server-side config...

$(document).ready(function() {
    $(MIX1_PARENT_DIV_ID).append("<div id='" + MIX1_DIV_ID + "' style='display:none;'></div>");
    addDivNav();
});

function addDivNav() {
    $(MIX1_PARENT_DIV_ID).append("<div id='" + MIX1_DIVNAV_ID + "' style='display:none;'></div>");

}

/**
* Load a content page over the flash.
*/
function mix1_loadurl(showUrl, modNavClick) {
    //////////////alert('load url');
    ////////////////alert(showUrl);
    //bit of a hack, but works for now, expand the div, if it's on the compare page...
    if (showUrl.toLowerCase().indexOf('compare.aspx') > 0) {
        $('#' + MIX1_DIV_ID).attr('class', 'xpand');
        lastLink = '';
    }
    else
        $('#' + MIX1_DIV_ID).attr('class', '');

    //load the page into the div, via ajax call and redisplay
    stopVideo();
    $('#' + MIX1_DIV_ID).append("<div class='loadingdisplay'><img src='/images/ajax-loader.gif' width='220' height='19' alt='Loading'/></div>");
    $('#' + MIX1_DIV_ID).load(showUrl, function() { setLastTheme(); setupOvervlayDiv(); renderNutritionInfo(valCopy); setAnalytics(showUrl); });

    if (!modNavClick) {
        $('#' + MIX1_DIV_ID).slideDown("slow");
    }

    var valCopy = getLastTheme().toLowerCase();
    //var url = "/Sitefinity/Default.aspx?flavor=" + valCopy + "&getnutritioninfo=" + 0;

}

//set up all tab links in the overlay div to be ajaxified...
function setupMainNavDiv() {
    ////////////////alert("setupMainNavDiv");
    ////////////////alert($("#content_right_flash_divnav a").length);
    $("#content_right_flash_divnav").css("display", "block");
    if (hasFlash())
        $("#content_right_flash_divnav a").click(function(event) { setUpModNavLink($(this), event); });
}




//set up all links in the overlay div to be ajaxified...
function setupOvervlayDiv() {

    //    ////////////////alert("setupOvervlayDiv");
    //    $("#content_right_flash a").click(function(event) {
    //        setUpLink($(this), event);
    //    });

    //    $("#content_right_flash area").click(function(event) {
    //        setUpLink($(this), event);
    //    });

    //set up the inline flowplayer videos
    playVideoDefault();

}


function clearOverlay() {
    //alert('clearOverlay');
    ////alert(flashLoaded);
    $('#' + MIX1_DIV_ID).slideUp("fast");
    $("#content_right_flash_divnav").slideUp("fast");
    stopVideo();
    clearMainMenu();
    themeInited = false;
    lastThemeType = '';
    lastSection = '';
    if (flashLoaded)
        showNewsTicker();
    //setSelectedMenuItem("")
}

function setUpModNavLink(thisLink, event) {

    var thisUrl = thisLink.attr("href").toLowerCase();
    if (thisLink.attr("target") != "_blank" && thisUrl.indexOf("http") <= 0) {
        sendModNavCall(thisUrl, event);
    }
}

function sendModNavCall(link, event) {
    ////////////////alert("sendModNavCall");
    if (event != null) {
        event.preventDefault();
    }

    if (link.indexOf('ajax=1') < 0)
        link += link.indexOf('?') >= 0 ? '&ajax=1' : '?ajax=1';

    $('#' + MIX1_DIV_ID).empty();
    mix1_loadurl(link, true);
}

function mix1_removeurl() {
    $('#' + MIX1_DIV_ID).empty();
    //$('#' + MIX1_DIV_ID).slideUp();
}

/* form validation */
function validZip(zip) {
    var len = zip.length
    var digits = "0123456789"
    if (len != 5)
    { return false; }

    for (i = 0; i < 5; i++) {
        if (digits.indexOf(zip.charAt(i)) < 0)
        { return false; }
    }
    return true;
}

function validEmail(str) {

    var at = "@"
    var dot = "."
    var lat = str.indexOf(at)
    var lstr = str.length
    var ldot = str.indexOf(dot)
    if (str.indexOf(at) == -1) {
        return false
    }

    if (str.indexOf(at) == -1 || str.indexOf(at) == 0 || str.indexOf(at) == lstr) {
        return false
    }

    if (str.indexOf(dot) == -1 || str.indexOf(dot) == 0 || str.indexOf(dot) == lstr) {
        return false
    }

    if (str.indexOf(at, (lat + 1)) != -1) {
        return false
    }

    if (str.substring(lat - 1, lat) == dot || str.substring(lat + 1, lat + 2) == dot) {
        return false
    }

    if (str.indexOf(dot, (lat + 2)) == -1) {
        return false
    }

    if (str.indexOf(" ") != -1) {
        return false
    }

    return true
}

function setAnalytics(showUrl) {

    showUrl = showUrl.replace('?ajax=1', '').replace('&ajax=1', '');
    ////////alert('analytics : ' + showUrl);
    pageTracker._trackPageview(showUrl)
}

function setAnalyticsDynamic(showUrl, doc_location) {

    //var doc_location = document.location.pathname;
    var rootUrl = '';

    if (doc_location.indexOf("blog.aspx") >= 0 ||
        doc_location.indexOf('blog-detail.aspx') >= 0)
        rootUrl = "/home/community/blogs/";
    else if (doc_location.indexOf("category-list.aspx?id=5") >= 0)
        rootUrl = "/home/thedrink/mixology101/faq/";
    else if (doc_location.indexOf("category-list.aspx?id=3") >= 0)
        rootUrl = "/home/thedrink/mixology101/glossary/";
    else if (doc_location.indexOf("category-list.aspx?id=4") >= 0)
        rootUrl = "/home/thedrink/mixology101/referencelibrary/";
    else if (doc_location.indexOf("category-list.aspx?id=1") >= 0)
        rootUrl = "/home/thedrink/mixology101/wellnesstips/";

    ////alert(doc_location);

    showUrl = removeBadChars(showUrl.replace('?ajax=1', '').replace('&ajax=1', ''));

    showUrl = rootUrl + showUrl;
    ////alert('wtf' + showUrl);

    pageTracker._trackPageview(showUrl)
}

function removeBadChars(str) {
    return str.replace(/[^a-zA-Z 0-9]+/g, '').split('  ').join(' ').split(' ').join('-');
}



$.extend({ URLEncode: function(c) {
    var o = ''; var x = 0; c = c.toString(); var r = /(^[a-zA-Z0-9_.]*)/;
    while (x < c.length) {
        var m = r.exec(c.substr(x));
        if (m != null && m.length > 1 && m[1] != '') {
            o += m[1]; x += m[1].length;
        } else {
            if (c[x] == ' ') o += '+'; else {
                var d = c.charCodeAt(x); var h = d.toString(16);
                o += '%' + (h.length < 2 ? '0' : '') + h.toUpperCase();
            } x++;
        }
    } return o;
},
    URLDecode: function(s) {
        var o = s; var binVal, t; var r = /(%[^%]{2})/;
        while ((m = r.exec(o)) != null && m.length > 1 && m[1] != '') {
            b = parseInt(m[1].substr(1), 16);
            t = String.fromCharCode(b); o = o.replace(m[1], t);
        } return o;
    }
});


/**store locator**/

//toggles visibile on a row of store elements

function paginateStores(itemClass, currentPage, itemsPer, itemCount) {
    var currentItem = 0;
    var endItem = currentPage * itemsPer;
    var startItem = ((currentPage - 1) * itemsPer) + 1;

    if (endItem > itemCount) {
        endItem = itemCount;
        startItem = endItem - itemsPer + 1;
    }

    $('#random-container .' + itemClass).each(
           function() {
               currentItem++;
               if (currentItem >= startItem && currentItem <= endItem)
                   $(this).css('display', 'block');
               else
                   $(this).css('display', 'none');
           }
    );
}


/**news ticker**/
function paginateNewsTicker(currentPage, itemCount) {
    var currentItem = 0;

    $('#news_ticker p').each(
           function() {
               currentItem++;
               if (currentItem == currentPage)
                   $(this).css('display', 'block');
               else
                   $(this).css('display', 'none');
           }
    );
}

function showNewsTicker() {
    setNewsTicker();
    $("#news_ticker_container").fadeIn("slow");
}

function hideNewsTicker() {
    clearTimers();
    $("#news_ticker_container").fadeOut("slow");
}

function setNewsTicker() {
    clearTimers();
    var firstItemCount = $('#news_ticker p').size();

    if (firstItemCount > 1) {
        var firstCurrentPage = 2;
        var refreshId =
                setInterval(
                    function() {
                        if ($.browser.msie && $.browser.version < 7) $('#news_ticker p').css('background-color', 'White');
                        $('#news_ticker #items').fadeOut(1500,
                            function() {
                                paginateNewsTicker(firstCurrentPage, firstItemCount);
                                firstCurrentPage++;
                                if (firstCurrentPage > firstItemCount) firstCurrentPage = 1;
                            }).fadeIn(1500,
                                    function() {
                                        if ($.browser.msie && $.browser.version < 7) $('#news_ticker p').css('background-color', '');
                                    }
                          );
                    }, 5000);

        timers.push(refreshId);
    }
}

/**generic code for timer functions**/

var timers = new Array();

function clearTimers() {
    for (var i = 0; i < timers.length; i++) {
        ////alert(timers[i]);
        clearInterval(timers[i]);
    }
    resetTimeouts();
}

function resetTimeouts() {
    timers = new Array();
}