﻿if (!Array.indexOf) {
    Array.prototype.indexOf = function(obj) {
        for (var i = 0; i < this.length; i++) {
            if (this[i] == obj) { return i; }
        }
        return -1;
    }
}

$(document).ready(function() {
    //Fixes link hasLayout bug in IE with the images within block elements within anchors.  Applies to FMA link boxes.

    $('a[rel]').click(function(e) {
        if (OpenREL($(this)))
            document.location = $(this).attr("href");
        return false;
    });

    //REL linking
    $('a[rel=] div img').click(function() {
        window.location = $(this).parent().parent().attr('href');
    });

    //Fixes drop down sizing with size attribute present.
    $('select[size]').css('height', 'auto');
});


function OpenREL(obj) {
    switch ($(obj).attr('rel')) {
        case 'external':
            window.open($(obj).attr('href'));
            break;
        case 'share':
            shareTHATClick(obj);
            break;
        case 'facebook':
            if(openFacebook) openFacebook();
            break;
        case 'twitter':
            if(openTwitter) openTwitter();
            break;
        case 'email':
            loadEmailModal($(obj).attr('href'));
            //window.open($(obj).attr('href'), '', 'width=400,height=550,status=no,scrollbars=yes,resizable=yes,menubar=no,directories=no,toolbar=no,location=no');
            break;
        case 'print':
            window.print();
            break;
        case 'fma':
            if ($(obj).attr('href').indexOf('://') > -1)
                window.open($(obj).attr('href'), '', '');
            else
                return true;
            break;
        default:
            return true;
    }
    return false;
}
function loadEmailModal(href) {
    $('#commonModal').jqm({ modal: true, title: "Send an Email to a Friend", width: 500, height: 500 }).jqmShow();
    $('#commonModal div.modalContent').html("<iframe src='" + href + "' frameborder='0' style='width: 100%; height: 100%;'></iframe>");
}

$(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();
    setupSideNav();
}

/* 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 setupSideNav() {
    $('#sidebar ul li ul li[class=current]').each(function() {
        if($(this).find('ul').length > 0)
            $(this).find('a').first().css('background-image', $(this).find('a').first().css('background-image').replace('.gif', '-open.gif'));
    });
}

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).find('a').addClass('hover');
    $(this).find('ul').show();
}
function hideSubnav(e) {
    $(this).find('a').removeClass('hover');
    $(this).parent().find('ul').stop(true, true);
    $(this).find('ul').hide();
}

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();
    });
});

function bindMessage(hash, message) {
    $(function() {
        if (window.location.hash == hash) {
            messageBoxId = 'messageBox' + hash.replace('#', '');
            ($("#content").length > 0 ? $("#content") : $("#content-single-column")).prepend('<div id="' + messageBoxId + '" class="confirmation_message round-both">' + message + '<a href="#" class="close"><img src="/_images/thankyou_close.png" alt="Close" /></a></div>')
            $('#' + messageBoxId).slideDown('fast');
            $('#' + messageBoxId + ' a.close').click(function() { $('#' + messageBoxId).slideUp('fast'); window.location.hash = ''; });
        }
    });
}

function limitInputLength(display, field, maxlimit) {
    if (maxlimit - $(field).val().length <= 0)
        $(field).val($(field).val().substring(0, 256));
    $(display).text(maxlimit - $(field).val().length);
}

function HighlightInvalidFields() {
    for (var i = 0; i < Page_Validators.length; i++) {
        var controlToValidate = $("[id$='" + Page_Validators[i].controltovalidate + "']");
        if (controlToValidate.length > 0) controlToValidate[0].multivalid = true;
    }
    for (var i = 0; i < Page_Validators.length; i++) {
        var controlToValidate = $("[id$='" + Page_Validators[i].controltovalidate + "']");
        if (!Page_Validators[i].isvalid)
            controlToValidate.add(Page_Validators[i]).addClass('invalid')[0].multivalid = false;
        else if (controlToValidate.length > 0 && controlToValidate[0].multivalid)
            controlToValidate.add(Page_Validators[i]).removeClass('invalid');
    }
}
function enableAdvancedValidators() {
    window._ValidatorOnChange = window.ValidatorOnChange;
    window._ValidatorCommonOnSubmit = window.ValidatorCommonOnSubmit;
    window._ValidatorOnLoad = window.ValidatorOnLoad;
    window.ValidatorOnChange = function(ev) {
        window._ValidatorOnChange(ev);
        HighlightInvalidFields();
    }
    window.ValidatorCommonOnSubmit = function(ev) {
        window._ValidatorCommonOnSubmit(ev);
        HighlightInvalidFields();
    }
    window.ValidatorOnLoad = function(ev) {
        window._ValidatorOnLoad(ev);
        HighlightInvalidFields();
    }
}