﻿if (!Array.indexOf) {
    Array.prototype.indexOf = function(obj) {
        for (var i = 0; i < this.length; i++) {
            if (this[i] == obj) { return i; }
        }
        return -1;
    }
}

//Fixes link hasLayout bug in IE with the images within block elements within anchors.  Applies to FMA link boxes.
$(document).ready(function() {
    $("a > div > img").each(function() {
        $(this).click(function() {
            window.location = $(this).parent().parent().attr("href");
        });
    });
});

$(document).ready(setup);

// these are set in the "global" namespace as they're used in multiple functions
var rootPrefix = './';
var currentNav = '';

function setup() {

    // figure out where we are in the site
    var folders = window.location.href.toLowerCase().split('/');
    var lastFolder = folders[folders.length - 2];
    var secondLevels = ['common', 'earn', 'learn', 'progress', 'share'];
    var thirdLevels = ['bonus', 'classessentials', 'clip', 'marketplace', 'readingroom'];

    // set our root prefix for link updating
    rootPrefix = './';
    if (secondLevels.indexOf(lastFolder) != -1) rootPrefix = '../'; 
    if (thirdLevels.indexOf(lastFolder) != -1) rootPrefix = '../../'; 

    // set our current nav for highlighting
    currentNav = '';
    if (secondLevels.indexOf(lastFolder) != -1) currentNav = lastFolder; 
    if (thirdLevels.indexOf(lastFolder) != -1) currentNav = 'earn';

    if (folders.indexOf("article.aspx") != -1 && folders.indexOf("coordinator") == -1) currentNav = 'learn';

    updateNav();
    //setupFMA();
    setupMarketplace();
    setupHoliday();
    setupRestrictions()
    setupScroller();
    setupRecipeSearch();
    setupTooltips();
    //externalLinks();
}

/* for marketplace tooltips */
function setupTooltips() {
    $('a.marketplace-tooltip').parent().hover(showTooltip, hideTooltip);
}

function showTooltip() {
    $(this).parent().find('.marketplace-tip-box').show();
}

function hideTooltip() {
    $(this).parent().parent().find('.marketplace-tip-box').stop(true, true);
    $(this).parent().find('.marketplace-tip-box').hide(); 
}

// This assumes any page that has cat filters has the MP search bar
function setupMarketplace() {
    if ($('#marketplace-categories').length == 0) return;
    $('#marketplace-categories').click(showHidePopup);

    if ($('#marketplace-filters legend').length == 0) return;
    $('#marketplace-filters legend span').click(showHideFilters);
    $('#reset').click(clearFilters);
}

function setupHoliday() {
    if ($('#holiday-search-bar').length == 0) return;
    $('#holiday-search-bar a.current').click(toggleDropdown);
    //$('#holiday-search-bar ul.sections a').click(selectCategory);

    if ($('.holiday-tabs').length == 0) return;
    $('.holiday-tabs li a').click(toggleTabs);
}

function toggleTabs(e) {
    $('.holiday-tabs li').attr('class', '');
    $(this).parent().attr('class', 'selected');
    $('.holiday-blocks').hide();
    $('#' + $(this).attr('rel')).show();
    return false;
    
}

function setupRestrictions() {
    if ($('a.restrictions').length == 0) return;
    $('a.restrictions').click(showHideRestriction);
}

function showHidePopup(e) {
    if ($('#inner-categories').css('display') == 'none') {
        $('#marketplace-categories').css('background', '#6EBC03 url(../../_images/marketplace/browse_up_arrow.png) no-repeat right 5px')
        $('#inner-categories').show()
    } else {
        $('#marketplace-categories').css('background', '#6EBC03 url(../../_images/marketplace/browse_down_arrow.png) no-repeat right 5px')
        $('#inner-categories').hide()
    }
}

function clearFilters(e) {
    $('input:checkbox').removeAttr('checked');
}

function showHideFilters(e) {
    if ($('#inner-filters').css('display') == 'none') {
        $('#marketplace-filters legend span').css('background', '#FFF url(../../_images/marketplace/minus.png) no-repeat 3px 3px')
        $('#marketplace-filters legend span').html('Hide Filters')
        $('#inner-filters').show()
    } else {
        $('#marketplace-filters legend span').css('background', '#FFF url(../../_images/marketplace/plus.png) no-repeat 3px 3px')
        $('#marketplace-filters legend span').html('Show Filters')
        $('#inner-filters').hide()
    }
}

function showHideRestriction(e) {
    if ($('#' + $(this).attr('rel')).css('display') == 'none') {
        $('#' + $(this).attr('rel')).show();
        $(this).html('Hide Restrictions');
        $(this).parent().parent().css('overflow', 'visible');
    } else {
        $('#' + $(this).attr('rel')).hide();
        $(this).html('See Restrictions');
        $(this).parent().parent().css('overflow', 'hidden');
    }
}

// Holiday function (Old marketplace)
function toggleDropdown(e) {
    e.preventDefault();
    $(this).parent().find('ul.sections').slideToggle();
}

function selectCategory(e) {
    e.preventDefault();
    $('#holiday-search-bar a.current').html($(this).html());
    $(this).parent().parent().parent().parent().slideUp('fast');
}

function setupRecipeSearch() {
    $('.recipe-search input').focus(clearBox);
    $('input.marketplace-search').focus(clearBox);
}

function clearBox() {
    if (this.value == 'search recipes' || this.value == 'search products') {
        this.value = '';
    }
}

/* Functions for implementing Carousel */
var currentItem = 0;
var itemWidth = 226;
var animateTime = 225;
function setupScroller() {
    $('.carousel a.prevPage').click(movePrev);
    $('.carousel a.nextPage').click(moveNext);
}
function movePrev(e) {
    e.preventDefault();
    if (currentItem == 0) { return; }
    currentItem--;
    $('.carousel a.nextPage').removeClass('off');
    if (currentItem == 0) { $(this).addClass('off'); }
    var moveObject = { left: '+=' + itemWidth };
    $('.carousel .item-holder .tab-link-boxes').animate(moveObject, animateTime, 'linear');
}
function moveNext(e) {
    e.preventDefault();
    var max = $('.carousel .item-holder')[0].style.width.replace(/px/g, "") / 226;
    var lastItem = $('.carousel .item-holder .tab-link-boxes li').length - max;
    if (currentItem == lastItem) { return; }
    currentItem++;
    $('.carousel a.prevPage').removeClass('off');
    if (currentItem == lastItem) { $(this).addClass('off'); }
    var moveObject = { left: '-=' + itemWidth };
    $('.carousel .item-holder .tab-link-boxes').animate(moveObject, animateTime, 'linear');
}

function updateNav() {
    // setup our menu
    $('#top-nav ul li').hover(showSubnav, hideSubnav); 
    
    // set the current nav
    if (currentNav == '') { return; }
    $('#top-nav > ul > li > a').removeClass('current');
    $('#top-nav > ul > li > a[href*=/' + currentNav + '/]').addClass('current');
}

function showSubnav(e) {
    $(this).addClass('hovered');
    $(this).find('ul').show();
}
function hideSubnav(e) {
    $(this).removeClass('hovered');
    $(this).parent().find('ul').stop(true, true);
    $(this).find('ul').hide();
}

/* used to fix the popup target=_blank issue in non-IE browsers */
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";
            anchor.onclick = "window.open(this.href); return false;";
        }
    }
}
/* h,w: in pixels; scroll=no,0,yes,1; myname: window name (some_name, or _blank for new); */
//var win;
//function showPopupWindow(mypage, myname, w, h) {
//    var winl = (window.screen.width - w) / 2;
//    var wint = (window.screen.height - h) / 2;
//    winprops = 'height=' + h + ',width=' + w + ',top=' + wint + ',left=' + winl + ',scrollbars=yes,resizable=yes,scrollable=yes'
//    win = window.open(mypage, myname, winprops)
//    if (parseInt(navigator.appVersion) >= 4) { win.window.focus(); }
//}


function getFlashCookie(c_name) {
    if (document.cookie.length > 0) {
        c_start = document.cookie.indexOf(c_name + "=");
        if (c_start != -1) {
            c_start = c_start + c_name.length + 1;
            c_end = document.cookie.indexOf(";", c_start);
            if (c_end == -1) c_end = document.cookie.length;
            return unescape(document.cookie.substring(c_start, c_end));
        }
    }
    return true;
}

var showFunc;

function removeFlash() {
    $("#myContent").hide();
    $("#myNonFlashContent").show();
    $("#flash-toggler").text("Show Flash Video");
    setFlashCookie('enabled', false, 365);
}

function enableFlash() {
    showFunc();     
    $("#myContent").show();
    $("#myNonFlashContent").hide();
    $("#flash-toggler").text("Hide Flash Video");
    setFlashCookie('enabled', true, 365);
}

function setFlashCookie(c_name, value, expiredays) {
    var exdate = new Date();
    exdate.setDate(exdate.getDate() + expiredays);
    document.cookie = c_name + "=" + escape(value) + ((expiredays == null) ? "" : ";expires=" + exdate.toGMTString());
}


function checkFlashCookie(func) {
    $(document).ready(function() {
        showFunc = func;
        enabled = eval(getFlashCookie('enabled'));
        if (!enabled) {
            removeFlash();
        }
        else {
            enableFlash();
        }
    });
}

$(document).ready(function() {
    $("#flash-toggler").click(function() {
        if ($("#myContent").is(":visible")) {
            removeFlash();
        }
        else {
            enableFlash();
        }
    });
});
