﻿$(document).ready(function () {

    var hoverPopupVisible = false;
    var hoverTrackTimer = null;

    //Nav hover states
    $('#mainnav_home').bind('mouseenter', { nav: 'home' }, selectNav);
    $('#mainnav_home').bind('mouseleave', { nav: 'home' }, deselectNav);

    $('#mainnav_recipes, #recipes_subnav').bind('mouseenter', { nav: 'recipes' }, showSubNav);
    $('#mainnav_recipes, #recipes_subnav').bind('mouseleave', { nav: 'recipes' }, hideSubNav);

    $('#mainnav_testkitchen, #testkitchen_subnav').bind('mouseenter', { nav: 'testkitchen' }, showSubNav);
    $('#mainnav_testkitchen, #testkitchen_subnav').bind('mouseleave', { nav: 'testkitchen' }, hideSubNav);
     
    $('#mainnav_products, #products_subnav').bind('mouseenter', { nav: 'products' }, showSubNav);
    $('#mainnav_products, #products_subnav').bind('mouseleave', { nav: 'products' }, hideSubNav);

    $('#mainnav_offers').bind('mouseenter', { nav: 'offers' }, showSubNav);
    $('#mainnav_offers').bind('mouseleave', { nav: 'offers' }, hideSubNav);

    $('#mainnav_ourstory, #ourstory_subnav').bind('mouseenter', { nav: 'ourstory' }, showSubNav);
    $('#mainnav_ourstory, #ourstory_subnav').bind('mouseleave', { nav: 'ourstory' }, hideSubNav);
    
    $('#external_url_screen a#ok_btn').click(function (event) {
        /*window.location = this.href;*/
        window.open(this.href, '_blank');

        event.preventDefault();
        $('#eu_pop_up_background').fadeTo(100, 0, function (event) {
            $(this).css('display', 'none');
            $('#external_url_screen').css('display', 'none');
        });

    });

    //Nav click events
    targetClick('home');
    targetClick('recipes');
    targetClick('testkitchen');
    targetClick('products');
    targetClick('offers');
    targetClick('ourstory');

    selectActiveNav();

    configureHomeFeatures();

    activateExternalLinkPopups();

    activeFancyboxCloseLinks();

    //doing this on the backend instead and caching
    //loadFacebookStatus();

    
});

function selectNav(event) {
    $('#mainnav_' + event.data.nav).stop(true).addClass("hover");
}


function showSubNav(event) {
    selectNav(event);
    $('#searchinput').autocomplete("close");
    $('#' + event.data.nav + '_subnav').stop(true).fadeTo(300, 1);


    if (event.data.nav == 'products') {
        hoverPopupVisible = true;
        clearTimeout(hoverTrackTimer);
        var hoverTrackTimer = setTimeout("trackHoverPopup()", 900);
    }
}

function deselectNav(event) {
    $('#mainnav_' + event.data.nav).delay(10).fadeTo(0, 1, function (event) { $(this).removeClass('hover'); });
}

function hideSubNav(event) {
    deselectNav(event);
    $('#' + event.data.nav + '_subnav').stop(true).delay(10).fadeTo(10, 0, function (event) { $(this).hide(); });

    if (event.data.nav == 'products') {
        hoverPopupVisible = false;
        clearTimeout(hoverTrackTimer);
    }
}

function activeFancyboxCloseLinks() {
    $('.closeFancybox').click(function () { $.fancybox.close() });
}

function trackHoverPopup() {
    if ( hoverPopupVisible == true )
        _gat._getTrackerByName()._trackEvent('Nav_Dropdown_Visble', 'Products', '', 0, true);
    
    return;
}

/*
function loadFacebookStatus() {
FB.api('/' + $('input[id$=fb_page]').val() + '/posts', function (response) {
if (!response || response.error) {
//Do nothing. Still showing the visit facebook link
} else {
$('#current_status').html(response.data[0].message);
$('#current_status_link').html('Read More');
}
});
}
*/
function activateExternalLinkPopups() {
    /*screens for external link pop-ups*/
    $('a[href^="http"]').
    add('a[href^="https"]').
    not('a[href^="http"].no_popup').
    click(function (event) {

        event.preventDefault();

        $('#external_url_screen').css('display', 'block');
        $('#eu_pop_up_background').css('display', 'block');
        $('#eu_pop_up_background').css('opacity', 0).fadeTo(300, .9);
        $('#external_url_screen').css('opacity', 0).delay(60).fadeTo(300, 1);

        $('#external_url_screen a#ok_btn').attr("href", this.href);

        $('#external_url_screen a#close_btn, #eu_pop_up_background').click(function (event) {
            event.preventDefault();
            $('#eu_pop_up_background').fadeTo(100, 0, function (event) {
                $(this).css('display', 'none');
                $('#external_url_screen').css('display', 'none');
            });
        });

    });

}




function selectActiveNav() {
    var path = location.pathname;
    if (path == "/") {
        $('#mainnav_home').addClass("selected");
    }
    else if (path.match(/^\/recipe(s)?\//i) != null) {
        $('#mainnav_recipes').addClass("selected");
    }
    else if (path.match(/^\/testkitchen\//i) != null) {
        $('#mainnav_testkitchen').addClass("selected");
    }
    else if (path.match(/^\/product(s)?\//i) != null) {
        $('#mainnav_products').addClass("selected");
    }
    else if (path.match(/^\/offers\//i) != null) {
        $('#mainnav_offers').addClass("selected");
    }
    else if (path.match(/^\/ourstory/i) != null) {
        $('#mainnav_ourstory').addClass("selected");
    }

}

function targetClick(navitem) {
    $('#mainnav_' + navitem).click(function (event) {
        var target = $("a", this).first().attr("href");
        window.location.href = target;
    });
}

var homeFeaturePageCount = 0;
var homeFeaturePage = 0;
var homeFeatureMoveDuration = 300;
var homeFeatureMoveDistance = 990;
var enableFeatureNav = false;

function configureHomeFeatures() {

    //disable in admin mode
    if ($(".theWrapper #features").length > 0) {
        return;
    }

    var foundEnd = false;
    var pages = 0;
    while (!foundEnd && pages < 10) {
        if ($("#features .page" + pages).length > 0) {

            $("#features .page" + pages).css('display', 'block').wrapAll("<div id='pageContainer" + pages + "' style='position:absolute;'/>");
            if (pages > 0) {
                $("#features #pageContainer" + pages).css('display', 'none');

            }

            pages++;
        }
        else {
            foundEnd = true;
        }
    }
    homeFeaturePageCount = pages;

    $('#homeFeatures #featureLeft').click(function (event) { homePageMove('left') });
    $('#homeFeatures #featureRight').click(function (event) { homePageMove('right') });
    enableFeatureNav = true;
}


function homePageMove(direction) {

    if (!enableFeatureNav) {
        return;
    }
    enableFeatureNav = false;

    var lastPage = homeFeaturePage;
    var moveDist = homeFeatureMoveDistance;

    if (direction == 'left') {
        moveDist = 0 - moveDist;
        homeFeaturePage--;
    }
    else {
        homeFeaturePage++;
    }

    if (homeFeaturePage >= homeFeaturePageCount) {
        homeFeaturePage = 0;
    }
    else if (homeFeaturePage < 0) {
        homeFeaturePage = homeFeaturePageCount - 1;
    }

    $("#features #pageContainer" + lastPage + " .featureElement")
        .css('opacity', 1)
        .fadeTo(homeFeatureMoveDuration, 0);
    $("#features #pageContainer" + lastPage)
            .css('left', "0px")
            .css('z-index', "49")

            .animate(
                { 'left': (0 - moveDist) + "px" },
                {
                    'duration': homeFeatureMoveDuration,
                    'complete': function () {
                        $(this).css('display', 'none');
                        enableFeatureNav = true;
                    }
                });

    $("#features #pageContainer" + homeFeaturePage + " .featureElement")
        .css('opacity', .5)
        .fadeTo(homeFeatureMoveDuration, 1);
    $("#features #pageContainer" + homeFeaturePage)
            .css('left', (moveDist) + "px")
            .css('z-index', "50")
            .css('display', 'block')
            .animate(
                { 'left': "0px" },
                {
                    'duration': homeFeatureMoveDuration,
                    'complete': function () {
                        enableFeatureNav = true;
                        $("#features #pageContainer" + lastPage).css('display', 'none');


                        //bug fix - force search widget to display on top (it's css gets dynamically rewritten on every search - can't be set in css)
                        $(this).css('z-index', 0);

                    }
                });



}


var browserGUID = readCookie("browserGUID");
if (browserGUID == null || browserGUID == "") {
    browserGUID = generateGuid();
    createCookie("browserGUID", browserGUID, 1000);  //save guid for 1000 days
}

function generateGuid() {
    var result, i, j;
    result = '';
    for (j = 0; j < 32; j++) {
        if (j == 8 || j == 12 || j == 16 || j == 20)
            result = result + '-';
        i = Math.floor(Math.random() * 16).toString(16).toUpperCase();
        result = result + i;
    }
    return result;
}

function createCookie(name, value, days) {
    if (days) {
        var date = new Date();
        date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
        var expires = "; expires=" + date.toGMTString();
    }
    else var expires = "";
    document.cookie = name + "=" + value + expires + "; path=/";
}

function readCookie(name) {
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for (var i = 0; i < ca.length; i++) {
        var c = ca[i];
        while (c.charAt(0) == ' ') c = c.substring(1, c.length);
        if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length);
    }
    return null;
}

function eraseCookie(name) {
    createCookie(name, "", -1);
}


function enablePrintCSS(setenabled) {
    $('.subnav').removeAttr('style');
    $('link').each(function () {

        if (setenabled) {
            if ($(this).attr('media') == 'screen') {
                this.disabled = true;
            }
            else if ($(this).attr('media') == 'print') {
                $(this).attr('media', 'print,screen');
            }
        }
        else {
            if ($(this).attr('media') == 'screen') {
                this.disabled = false;
            }
            else if ($(this).attr('media') == 'print,screen') {
                $(this).attr('media', 'print');
            }
        }

    });
    return false;
}

function htmlEncode(value) {
    return $('<div/>').text(value).html();
}

function htmlDecode(value) {
    return $('<div/>').html(value).text();
}


