﻿/// <reference path="jquery-1.4.2.js"/>
jQuery.noConflict();

/** New/Consolidated Stuff **/

/* Global Doc Ready - Add any function that needs to run on all page loads */

jQuery(document).ready(function () {
    TrimModules();
    SetupHintText();
    SetTopNavBG();
    WireBadgeSmallPopups();
    WireBadgeMediumPopups();
    SetHoverContent();

});

function sizeIFrame() {
//    var resizeiFrameContainer = jQuery('iframe');
//    var innerDoc = (resizeiFrameContainer.get(0).contentDocument) ? resizeiFrameContainer.get(0).contentDocument : resizeiFrameContainer.get(0).contentWindow.document;
//    resizeiFrameContainer.height(innerDoc.body.scrollHeight + 35);
}

var badge_wire_run = false
function WireBadgePopups() {
    if (!badge_wire_run) {

        jQuery('.badge_image').each(function () {
            var badge_pop = jQuery('.badge_pop', jQuery(this));
            var inner_img = jQuery('img', jQuery(this));
            var targ_left = ((inner_img.width() - badge_pop.width()) / 2) - 30;
            var targ_bottom = (inner_img.height() / 2) + 20;
            jQuery('.badge_pop', jQuery(this)).css({ bottom: targ_bottom + "px", left: targ_left + "px" });
            var spacer;
            //var spacer = jQuery("<div class='badge_spacer'>").css({ height: "15px", width: badge_pop.width() });
            jQuery('.badge_pop div').after(spacer);
        });
        jQuery('.badge_image').hover(function () {
            jQuery(this).parent().find('.badge_pop').show();
            var badge_pop = jQuery('.badge_pop', jQuery(this));
            var inner_img = jQuery('img', jQuery(this));
            var targ_left = ((inner_img.width() - badge_pop.width()) / 2) - 30;
            var targ_bottom = (inner_img.height() / 2) + 20;
            jQuery('.badge_pop', jQuery(this)).css({ bottom: targ_bottom + "px", left: targ_left + "px" });
            var spacer;
            jQuery('.badge_pop div').after(spacer);

        }, function () {
            jQuery(this).parent().find('.badge_pop').hide();
        });
    }
    badge_wire_run = true;
}

var badge_wire_medium_run = false
function WireBadgeMediumPopups() {
    if (!badge_wire_medium_run) {
        jQuery('.badge_medium_image').each(function () {
            var badge_pop = jQuery('.badge_medium_pop', jQuery(this));
            var inner_img = jQuery('img', jQuery(this));
            var targ_left = ((inner_img.width() - badge_pop.width()) / 2) - 10;
            var targ_bottom =   - 40;
            jQuery('.badge_medium_pop', jQuery(this)).css({ bottom: targ_bottom + "px", left: targ_left + "px" });
            var spacer;
            jQuery('.badge_medium_pop div').after(spacer);
            //}
        });
        jQuery('.badge_medium_image').hover(function () {
            jQuery(this).parent().find('.badge_medium_pop').show();
            var badge_pop = jQuery('.badge_medium_pop', jQuery(this));
            var inner_img = jQuery('img', jQuery(this));
            var targ_left = ((inner_img.width() - badge_pop.width()) / 2) - 10;
            var targ_bottom =  - 40;
            jQuery('.badge_medium_pop', jQuery(this)).css({ bottom: targ_bottom + "px", left: targ_left + "px" });
            var spacer;
            jQuery('.badge_medium_pop div').after(spacer);

        }, function () {
            jQuery(this).parent().find('.badge_medium_pop').hide();
        });
    }
    badge_wire_medium_run = true;
}

function SetHoverContent() {
    if (typeof imageiconhoverBakeOff !== 'undefined') {
     jQuery("div.badge_small_image:has(img[rel='hover_bakeoff'])").find('.badge_small_pop .badge_small_content div').html(imageiconhoverBakeOff);
     jQuery("div.badge_small_image:has(div[rel='hover_bakeoff'])").find('.badge_small_pop .badge_small_content div').html(imageiconhoverBakeOff);
     jQuery("div.badge_medium_image:has(img[rel='hover_bakeoff'])").find('.badge_medium_pop .badge_medium_content div').html(imageiconhoverBakeOff);
 }
 if (typeof imageiconhoverIdeasMadeEasy !== 'undefined') {
     jQuery("div.badge_small_image:has(img[rel='hover_ideasmadeeasy'])").find('.badge_small_pop .badge_small_content div').html(imageiconhoverIdeasMadeEasy);
     jQuery("div.badge_small_image:has(div[rel='hover_ideasmadeeasy'])").find('.badge_small_pop .badge_small_content div').html(imageiconhoverIdeasMadeEasy);
     jQuery("div.badge_medium_image:has(img[rel='hover_ideasmadeeasy'])").find('.badge_medium_pop .badge_medium_content div').html(imageiconhoverIdeasMadeEasy);
 }
 if (typeof imageiconhoverStateFair !== 'undefined') {
     jQuery("div.badge_small_image:has(img[rel='hover_statefair'])").find('.badge_small_pop .badge_small_content div').html(imageiconhoverStateFair);
     jQuery("div.badge_small_image:has(div[rel='hover_statefair'])").find('.badge_small_pop .badge_small_content div').html(imageiconhoverStateFair);
     jQuery("div.badge_medium_image:has(img[rel='hover_statefair'])").find('.badge_medium_pop .badge_medium_content div').html(imageiconhoverStateFair);
 }
 if (typeof imageiconhoverrookiebakeoffwinner !== 'undefined') {
     jQuery("div.badge_small_image:has(img[rel='hover_rookiebakeoffwinner'])").find('.badge_small_pop .badge_small_content div').html(imageiconhoverrookiebakeoffwinner);
     jQuery("div.badge_small_image:has(div[rel='hover_rookiebakeoffwinner'])").find('.badge_small_pop .badge_small_content div').html(imageiconhoverrookiebakeoffwinner);
     jQuery("div.badge_medium_image:has(img[rel='hover_rookiebakeoffwinner'])").find('.badge_medium_pop .badge_medium_content div').html(imageiconhoverrookiebakeoffwinner);
 }
 if (typeof imageiconhoverrookiebakeofffinalist !== 'undefined') {
     jQuery("div.badge_small_image:has(img[rel='hover_rookiebakeofffinalist'])").find('.badge_small_pop .badge_small_content div').html(imageiconhoverrookiebakeofffinalist);
     jQuery("div.badge_small_image:has(div[rel='hover_rookiebakeofffinalist'])").find('.badge_small_pop .badge_small_content div').html(imageiconhoverrookiebakeofffinalist);
     jQuery("div.badge_medium_image:has(img[rel='hover_rookiebakeofffinalist'])").find('.badge_medium_pop .badge_medium_content div').html(imageiconhoverrookiebakeofffinalist);
 }
 if (typeof imageiconhoverMembersRecipe !== 'undefined') {
     jQuery("div.badge_small_image:has(img[rel='hover_memberrecipe'])").find('.badge_small_pop .badge_small_content div').html(imageiconhoverMembersRecipe);
     jQuery("div.badge_small_image:has(div[rel='hover_memberrecipe'])").find('.badge_small_pop .badge_small_content div').html(imageiconhoverMembersRecipe);
     jQuery("div.badge_medium_image:has(img[rel='hover_memberrecipe'])").find('.badge_medium_pop .badge_medium_content div').html(imageiconhoverMembersRecipe);
 }
 if (typeof imageiconhoverMembersOnly !== 'undefined') {
     jQuery("div.badge_small_image:has(img[rel='hover_membersonly'])").find('.badge_small_pop .badge_small_content div').html(imageiconhoverMembersOnly);
     jQuery("div.badge_small_image:has(div[rel='hover_membersonly'])").find('.badge_small_pop .badge_small_content div').html(imageiconhoverMembersOnly);
     jQuery("div.badge_medium_image:has(img[rel='hover_membersonly'])").find('.badge_medium_pop .badge_medium_content div').html(imageiconhoverMembersOnly);
 }
}


var badge_wire_small_run = false
function WireBadgeSmallPopups() {
    if (!badge_wire_small_run) {
        jQuery('.badge_small_image').each(function () {
            // if (jQuery("div.badge_small_image:has(img[rel])")) {
            var badge_pop = jQuery('.badge_small_pop', jQuery(this));
            var inner_img = jQuery('img', jQuery(this));
            var targ_left = -(((inner_img.width() * .15) * 2) + 10);
            var targ_bottom = (inner_img.height() -(inner_img.height() * .8));
            jQuery('.badge_small_pop', jQuery(this)).css({ bottom: targ_bottom + "px", left: targ_left + "px" });
            var spacer;
            jQuery('.badge_small_pop div').after(spacer);
            //alert(inner_img.val());
           // alert("targ_left: " + targ_left + ", inner_img.width: " + inner_img.width() + ", targ_bottom: " + targ_bottom + "inner_img.height(): " + inner_img.height());
            //}
        });
        jQuery('.badge_small_image').hover(function () {
            // if (jQuery("div.badge_small_image:has(img[rel])")) 
            // {
            jQuery(this).parent().find('.badge_small_pop').show();
            var badge_pop = jQuery('.badge_small_pop', jQuery(this));
            var inner_img = jQuery('img', jQuery(this));
            var targ_left = -(((inner_img.width() * .15) * 2) + 10);
            var targ_bottom = (inner_img.height() * .8);
            jQuery('.badge_small_pop', jQuery(this)).css({ bottom: targ_bottom + "px", left: targ_left + "px" });
            var spacer;
            jQuery('.badge_small_pop div').after(spacer);
            // }

        }, function () {
            jQuery(this).parent().find('.badge_small_pop').hide();
        });
    } 
    badge_wire_small_run = true;
}

// Set up Hint text display
function SetupHintText() {
    jQuery('.hintText').live('focus', function () {
        if (jQuery(this).data('default') == undefined) { jQuery(this).data('default', jQuery(this).val()) }
        jQuery(this).addClass("hintTextOver");
        if (jQuery(this).val() == jQuery(this).data('default')) {
            jQuery(this).val("");
        }
    });

    jQuery('.hintText').live('blur', function () {
        if (jQuery(this).val() == "") {
            jQuery(this).val(jQuery(this).data('default'));
            jQuery(this).removeClass("hintTextOver");
        }
    });
}

//Generic Function to adjust heights
function equalHeight(group) {
    var tallest = 0;
    group.each(function () {
        var thisHeight = jQuery(this).height();
        if (thisHeight > tallest) {
            tallest = thisHeight;
        }
    });
    group.height(tallest);
}

// Strip bottom border and margin off last module in column
function TrimModules() {
    jQuery('.three_middle .module:last').css({ 'border-bottom': 0, 'margin-bottom': '0px' });
    jQuery('.three_right .module:last').css({ 'border-bottom': 0, 'margin-bottom': '0px' });
    jQuery('.three_right_full .module:last').css({ 'border-bottom': 0, 'margin-bottom': '0px' });
    jQuery('.two_left .module:last').css({ 'border-bottom': 0, 'margin-bottom': '0px' });
    jQuery('.two_right .module:last').css({ 'border-bottom': 0, 'margin-bottom': '0px' });
    jQuery('.activity .module:last').css({ 'border-bottom': 0, 'margin-bottom': '0px' });
    jQuery('.inlineModule .module:last').css({ 'border-bottom': 0, 'margin-bottom': '0px' });
    jQuery('#VideoBrowse li.column_item:last').css({ 'border-bottom': 0, 'margin-bottom': '0px' });
}

function TrimHomePageModules() {
    jQuery('.homepage_column').each(function () {
        jQuery(this).find('.module:last').css({ 'border-bottom': 0, 'margin-bottom': '0px' });
    });
}

// Top Nav background - needed to allow opacity for bg without fading nav itself
function SetTopNavBG() {
    var w = jQuery('div.topNavAbove ul').outerWidth(false);
    jQuery('div.topNavBehind').css({ width: w });
};


// Sets items that match 'selector' to the same height - does not factor in padding/margin
function setToEqualHeight(selector) {
    var tallest = 0
    var check_tall = 0

    jQuery(selector)
    .each(function () {
        check_tall = jQuery(this).height()
        if (check_tall > tallest) { tallest = check_tall; }
    })
    .each(function () {
        jQuery(this).height(tallest)
    });
}

// Scroll open hidden content 
function setupReveal(filter, container, content, button, speed) {
    jQuery(button, filter).click(function () { 
        if (jQuery(container,filter).data('state') == undefined) {
            jQuery(container,filter).data('state', 'up');
        }
        if (jQuery(container, filter).data('state') != 'moving') {
            if (jQuery(container, filter).data('state') == 'up') {
                jQuery(container, filter).data('state', 'moving');
                jQuery(this).addClass('revealed');
                jQuery(container, filter).data('closed', jQuery(container, filter).outerHeight());
                jQuery(container, filter).data('open', jQuery(content, filter).outerHeight());
                jQuery(container, filter).animate({ height: jQuery(container, filter).data('open') }, speed,
                    function () { jQuery(container, filter).data('state', 'down'); });
            }
            else {
                jQuery(container, filter).data('state', 'moving');
                jQuery(this).removeClass('revealed');
                jQuery(container, filter).animate({ height: jQuery(container, filter).data('closed') }, speed,
                function () { jQuery(container, filter).data('state', 'up'); });
            }
        }
    });
}

// Two Column List Handling
// Set row items to equal height and add vertical separator, 
// strip margin on top row, strip bottom border on last row
function parseTwoColumn() {
    jQuery('ul.two_column_list').each(function () {
        var sibCount = jQuery(this).children().length;        
        var sep_top = false;
        jQuery(this).children().each(function (index) {
            if (index % 2 != 0) {
                if (index == 1) {
                    jQuery(this).css({ 'margin-top': 0 });
                    jQuery(this).prev().css({ 'margin-top': 0 });
                }
                if (index == sibCount - 1) {
                    jQuery(this).css({ 'border-bottom': 0 });
                    jQuery(this).prev().css({ 'border-bottom': 0 });
                }
                var tall = 0;
                tall = jQuery(this).height() >= jQuery(this).prev().height() ? jQuery(this).height() : jQuery(this).prev().height()
                jQuery(this).height(tall).addClass('item_right');
                jQuery(this).prev().height(tall);
                jQuery(this).prev().after('<li class="list_sep" style="height:' + tall + 'px; margin-top:' + jQuery(this).css("margin-top") + '"></li>');
            }
            else {
                jQuery(this).addClass('item_left');
                if (index == 0) {
                    jQuery(this).css({ 'margin-top': 0 });
                }
                if (index == sibCount - 1) {
                    jQuery(this).css({ 'border-bottom': 0 });
                    jQuery(this).after('<li class="list_sep" style="height:' + jQuery(this).height() + 'px; margin-top:' + jQuery(this).css("margin-top") + '"></li>');
                }
            }
        });
    });
}

function parseMultipleTwoColumn(){
    jQuery('ul.two_column_list').each(function () {
        var sibCount = jQuery(this).children().length;
        var sep_top = false;
        jQuery(this).children().each(function (index) {
            if (index % 2 != 0) {
                if (index == 1) {
                    jQuery(this).css({ 'margin-top': 0 });
                    jQuery(this).prev().css({ 'margin-top': 0 });
                }
                var tall = 0;
                tall = jQuery(this).height() >= jQuery(this).prev().height() ? jQuery(this).height() : jQuery(this).prev().height()
                jQuery(this).height(tall).addClass('item_right');
                jQuery(this).prev().height(tall);
                jQuery(this).prev().after('<li class="list_sep" style="height:' + tall + 'px; margin-top:' + jQuery(this).css("margin-top") + '"></li>');
                if (index == sibCount - 1) {
                    jQuery(this).css({ 'border-bottom': '0px' });
                }
            }
            else {
                jQuery(this).addClass('item_left');
                if (index == 0) {
                    jQuery(this).css({ 'margin-top': 0 });
                }
                if (index == sibCount - 1) {
                    jQuery(this).after('<li class="list_sep" style="height:' + jQuery(this).height() + 'px; margin-top:' + jQuery(this).css("margin-top") + '"></li>');
                    jQuery(this).css({ 'border-bottom': '0px' });
                }
                if (index == sibCount - 2) {
                    jQuery(this).css({ 'border-bottom': '0px' });
                }
            }
        });
    });
    jQuery('.two_column_list:last li').css({ 'border-bottom': '0px' });
}

function parseTwoColumnThumbs(context) {
    jQuery('ul.two_column_thumbs', context).each(function () {
        jQuery(this).children().each(function (index) {
            if (index % 2 != 0) {
                jQuery(this).after('<li class="full_clear"></li>');
            }
            else {
                jQuery(this).addClass('leftMargined');
            }
        });
    });
}

/* Scrollers */
var init_run = false;
function InitScroller() {
    if (!init_run) {
        jQuery('.full_column .carousel_container .carousel_set').each(function () {
            jQuery(this).children('.scroller_view').pillspager({ visibleItems: 6, scrollItems: 6, nextButton: jQuery(this).find('.scroller_next'), prevButton: jQuery(this).find('.scroller_prev'), hideControls: true, disabledClass: 'grayedOut' });
        });
        jQuery('.two_left .carousel_container .carousel_set').each(function () {
            jQuery(this).children('.scroller_view').pillspager({ visibleItems: 4, scrollItems: 4, nextButton: jQuery(this).find('.scroller_next'), prevButton: jQuery(this).find('.scroller_prev'), hideControls: true, disabledClass: 'grayedOut' });
        });
        jQuery('.three_middle .carousel_container .carousel_set').each(function () {
            jQuery(this).children('.scroller_view').pillspager({ visibleItems: 3, scrollItems: 3, nextButton: jQuery(this).find('.scroller_next'), prevButton: jQuery(this).find('.scroller_prev'), hideControls: true, disabledClass: 'grayedOut' });
        });
        jQuery('#scroll_select').change(function () {
            var index = parseInt(jQuery(this).val()) - 1;
            jQuery('.carousel_container .carousel_set', jQuery(this).parent().parent().parent()).hide().eq(index).show();
            return false;
        });
        init_run = true;
    }
}


jQuery(function () {
    if (typeof (jQuery('.communityCloud .content').pillspager) != "undefined") {
        jQuery('.communityCloud .content').pillspager({ visibleItems: 1, nextButton: '.communityNext', prevButton: '.communityPrev', hideControlsContainer: true, disabledClass: 'grayedOut' });
    }
    if (typeof (jQuery('.videoModuleRight .content').pillspager) != "undefined") {
        jQuery('.videoModuleRight .content').pillspager({ visibleItems: 1, nextButton: '.videoNext', prevButton: '.videoPrev', hideControls: true, disabledClass: 'grayedOut' });
    }
    if (typeof (jQuery('.winnersScrollerCarousel').pillspager) != "undefined") {
        jQuery('.winnersScrollerCarousel').pillspager({ visibleItems: 1, nextButton: '.scroller_next', prevButton: '.scroller_prev', hideControls: true, disabledClass: 'grayedOut' });
    }
    if (typeof (jQuery('.avatarScroller').pillspager) != "undefined") {
        jQuery('.avatarScroller').pillspager({ visibleItems: 3, scrollItems: 3, nextButton: '.avatarNext', prevButton: '.avatarPrev', hideControls: true, disabledClass: 'grayedOut' });
    }
});


/**** HERO ****/
var videoReadyTimeout;
var videoSwapped = false;

function InitHero(selector, context, startingSlideNumber) {
    WireBadgePopups();
    var initial = true;
    jQuery(selector).cycle({
        timeout: 6000,            //Time between slides
        speed: 500,          // Transition time
        fx: 'fade',
        pager: context + '#hero_pager',
        next: context + '#hero_next',
        prev: context + '#hero_prev',
        startingSlide: startingSlideNumber,
        pagerAnchorBuilder: function (idx, slide) {
            return '<div class="pager_item"><a href="#">' + (idx + 1) + '</a><div class="pager_item_thumb"><img src="' + jQuery(".hdnThumbSrc", slide).val() + '" alt="" /></div>';
        },
        before: function (curr, next, opts, fwd) {
            if (!initial) {
                var index = opts.nextSlide;
                var item_width = jQuery('.pager_item', jQuery(selector).parent()).eq(0).outerWidth();
                var nextLeft = item_width * index;
                jQuery('.pager_selected', jQuery(selector).parent()).animate({ left: nextLeft }, 400)
                jQuery('#hero_video_player', jQuery(selector).parent()).addClass("zero_opacity");
            }
        },
        after: function (curr, next, opts, fwd) {
            if (!initial) {
                if (jQuery('.OoyalaVideoPlayer', jQuery(selector).parent()).length > 0) {
                    jQuery('.OoyalaVideoPlayer', jQuery(selector).parent())[0].pauseMovie();
                }
                if (jQuery("#hdnVideoEmbedCode", jQuery(next)).length > 0) {
                    var embed_code = jQuery("#hdnVideoEmbedCode", jQuery(next)).val();
                    if (embed_code != jQuery("#heroCurrentVideoEC").val()) {
                        var player_id = jQuery('.OoyalaVideoPlayer', jQuery(selector).parent()).attr('id');
                        var identifier = player_id.substring(11);
                        var vid_title = jQuery("#hdnVideoTitle", jQuery(next)).val();
                        var player_url = jQuery('input#ec_url', jQuery(selector).parent()).val();
                        ChangeHeroVideo(player_id, identifier, vid_title, player_url, embed_code);
                        videoSwapped = true;
                        jQuery("#heroCurrentVideoEC").val(embed_code)
                        var isRecipeHero = jQuery(".hdnRecipeHeroPlayClicked", jQuery(next)).length > 0;
                        var fn = function () { pollVideoSwap(isRecipeHero); }
                        videoReadyTimeout = setTimeout(fn, 200);
                    }
                    else {
                        var isRecipeHero = jQuery(".hdnRecipeHeroPlayClicked", jQuery(next)).length > 0;
                        var fn = function () { pollVideoSwap(isRecipeHero); }
                        videoReadyTimeout = setTimeout(fn, 200);
                    }
                }
            }
            initial = false;

            //var index = opts.currSlide;
            //jQuery('#hero_pager .pager_item').eq(index).addClass('pager_selected');
        },
        prevNextClick: function (isNext, idx, slide) {
            pauseHero(selector);
        },
        pagerClick: function (isNext, idx, slide) {
            pauseHero(selector);

        }
    }).after("<input type='hidden' class='hero_state' value='1' />");

    jQuery('#hero_pager .pager_item', jQuery(selector).parent()).hover(function () {
        jQuery('.pager_item_thumb', jQuery(this)).show()
    },function () {
        jQuery('.pager_item_thumb', jQuery(this)).hide()
    });
    jQuery('a#playtoggle', jQuery(selector).parent()).click(function () {
        if (jQuery('.hero_state', jQuery(selector).parent()).val() == "0") {
            resumeHero(selector);
        }
        else {
            pauseHero(selector);
        }
    });
    var single_item_width = jQuery('.pager_item', jQuery(selector).parent()).eq(0).outerWidth();
    var item_count = jQuery('.pager_item', jQuery(selector).parent()).length;
    var item_bg_width = (single_item_width * item_count) - 1;
    jQuery('div.pager_items_background', jQuery(selector).parent()).css({ width: item_bg_width + "px" });

    jQuery('.recipe_hero_play', jQuery(selector)).click(function () {
        //jQuery('.hdnRecipeHeroPlayClicked').val("1");
        pauseHero(selector);
        jQuery('#hero_video_player').removeClass("zero_opacity");
        var fn = function () { playRecipeVideo(jQuery(selector).parent()); }
        videoReadyTimeout = setTimeout(fn, 500);
    });

    jQuery('.closeVideoButton').click(function () {
        var player_id = jQuery('.OoyalaVideoPlayer', jQuery(selector).parent()).attr('id');
        var identifier = jQuery(selector).parent().attr('id').substring(11);
        var event_catcher = getFlashMovie("eventCatcher" + identifier);
        event_catcher.seek(playerId);
        jQuery('#hero_video_player').addClass("zero_opacity");
    });
}

function playRecipeVideo(context) {
    clearTimeout(videoReadyTimeout);
    jQuery('.OoyalaVideoPlayer', context)[0].playMovie();
}

function pauseHero(selector) {
    jQuery('a#playtoggle', jQuery(selector).parent()).attr('class', 'toggle_play')
    jQuery('.hero_state', jQuery(selector).parent()).val('0');
    jQuery(selector).cycle('pause');
}
function resumeHero(selector) {
    jQuery('a#playtoggle', jQuery(selector).parent()).attr('class', 'toggle_pause')
    jQuery('.hero_state', jQuery(selector).parent()).val('1');
    jQuery(selector).cycle('resume');
}
function pollVideoSwap(isRecipeHero) {
    clearTimeout(videoReadyTimeout);
    if (!videoSwapped && !isRecipeHero) {
        jQuery('#hero_video_player').removeClass("zero_opacity");
    }
    else {
        if (jQuery('#heroVideoReady').val() == "1") {
            jQuery('#heroVideoReady').attr("value", "0");
            if (!isRecipeHero) {
                videoReadyTimeout = setTimeout("revealVideo()", 1000);
            }
        }
        else {
            var fn = function () { pollVideoSwap(isRecipeHero); }
            videoReadyTimeout = setTimeout(fn, 200);
        }
    }
}
function revealVideo() {
    clearTimeout(videoReadyTimeout);
    jQuery('#hero_video_player').removeClass("zero_opacity");
}

function ChangeOoyalaVideo(playerId, embedCode, videoTitle, videoDescription, caller) {
    //todo fix the change of the videos
    //jQuery('#eventCatcher').html(jQuery('#eventCatcher').html().replace(new RegExp('waId=[a-zA-Z0-9\s]*', 'g'), 'waId=' + videoTitle));
    if (caller) {
        jQuery(caller).parents('ul').parents('ul').children('li').children('ul').children('li').removeClass('activeVideo');
        jQuery(caller).parents('li:first').addClass('activeVideo');
    }
    jQuery('#' + playerId)[0].setEmbedCode(embedCode);
    jQuery('.videoTitle').html(videoTitle)
    jQuery('.videoCopy').html(videoDescription)
    videoDescription
    return false;
}

function ChangeHeroVideo(playerId, identifier, vid_title, player_url, embedCode) {
    var player = jQuery('#' + playerId)[0];
    player.setEmbedCode(embedCode);
    var waURL = "/Services/PostHandlers/WebActivityReceiver.ashx";
    var waName = "PBVideos";
    var waType = "VideoViewed";
    var new_flashvar_string = "waURL=" + waURL + "&waName=" + waName + "&waId=" + vid_title + "&waRscURL=" + player_url + "&waType=" + waType;
    document.getElementById("event_catcher_container"+identifier).innerHTML = BuildEventCatcherHtml(new_flashvar_string, identifier);
    //jQuery(ec_container).html('');
    //jQuery(ec_container).html(BuildEventCatcherHtml(new_flashvar_string, identifier));
    //var event_catcher = getFlashMovie("eventCatcher" + identifier);
    //event_catcher.setAttribute("flashvars", new_flashvar_string);
}

function BuildEventCatcherHtml(fv_string, ec_id)
{
    var ec_html = '';
    ec_html += '<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,40,0"'
    ec_html += '    width="1px" height="1px" id="eventCatcher'+ec_id+'" style="position:fixed;">'
    ec_html += '    <param name="movie" value="/flash/ooyala_event_catcher.swf" />'
    ec_html += '    <param name="quality" value="high" />'
    ec_html += '    <param name="allowScriptAccess" value="always" />'
    ec_html += '    <param name="flashvars" id="flashVarsParam" value="'+fv_string+'" />'
    ec_html += '    <embed id="videoEmbed" src="/flash/ooyala_event_catcher.swf"'
    ec_html += '        flashvars="'+fv_string+'"'
    ec_html += '        width="1" height="1" name="eventCatcher'+ec_id+'" align="middle"'
    ec_html += '        play="true"'
    ec_html += '        quality="high"'
    ec_html += '        allowScriptAccess="always"'
    ec_html += '       type="application/x-shockwave-flash"'
    ec_html += '       pluginspage="http://www.adobe.com/go/getflashplayer">'
    ec_html += '   </embed>'
    ec_html += '</object>'
    return ec_html;
}

function childBrowseAdjust() {
    jQuery('.hero_main').css({ 'padding-bottom': '0px' });
    jQuery('.hero_main .hero_details').css({ 'border-bottom': '0' });
    setToEqualHeight(jQuery('.hero_main .hero_details'));
    jQuery('.hero_main .hero_container').css({ 'height': jQuery('.hero_main .hero_container').height()-1, 'overflow':'hidden'});
    if (jQuery('.hero_main .hero_container_single').length == 0) {
        jQuery('.hero_browse_children .inner').css({ 'padding-left': '30px', 'padding-right': '30px' });
    }
}

function vidScrollerAdjust() {
    jQuery('.hero_video').css({ 'padding-bottom': '0px' });
    jQuery('.hero_video .hero_details').css({ 'border-bottom': '0' });
    setToEqualHeight(jQuery('.hero_video .hero_details'));
    jQuery('.hero_video .hero_container').css({ 'height': jQuery('.hero_video .hero_container').height() - 1, 'overflow':'hidden'});
}

function vidDetailAdjust() {
    jQuery('.hero_video').css({ 'padding-bottom': '0px' });
    jQuery('.hero_video .hero_details').css({ 'border-bottom': '0' });
    jQuery('.hero_video .hero_container').css({ 'height': jQuery('.hero_video .hero_container').height() - 1, 'overflow': 'hidden' });
}

jQuery('.hero_image div, .hero_image object, .hero_image embed').click(function () {
    pauseHero(jQuery(this).parents('.hero_container'));
});



function js_setCookie(c_name, value, expiredays) {
    var exdate = new Date();
    exdate.setDate(exdate.getDate() + expiredays);
    document.cookie = c_name + "=" + escape(value) + ((expiredays == null) ? "" : ";expires=" + exdate.toUTCString());
}
function js_getCookie(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 "";
}
function js_removeCookie(c_name) {
    setCookie(c_name, null, -1000);
}


//Flavor Selector
var fading = false;
function setFlavors(context) {

    if (jQuery('.flavor_container', context).data('state') == undefined) {
        jQuery('.flavor_container', context).data('state', 'up');
    }

    jQuery('.flavor_container', context).data('curIndex', 0);
    jQuery('.flavor_links a:first', context).eq(0).addClass('selected');
    jQuery('.flavor_container', context).height(jQuery('.flavor_item', context).eq(0).outerHeight() + 5);
    jQuery('.flavor_items', context).height(jQuery('.flavor_item', context).eq(0).outerHeight());

    jQuery('.flavor_links a', context).click(function () {
        if (!jQuery(this).hasClass('selected') && !fading) {
            fading = true;
            var new_index = parseInt(jQuery(this).attr('id').substring(11));
            updateSelectedFlavor(new_index);
            flavorFade(new_index);
            return false;
        }
    });

    jQuery('.jq_flavor_next', context).click(function () {
        if (!fading) {
            fading = true;
            var f_count = jQuery('.flavor_links a', context).length;
            var cur_index = jQuery('.flavor_container', context).data('curIndex');
            var new_index = (cur_index >= f_count - 1) ? 0 : cur_index + 1;
            updateSelectedFlavor(new_index);
            flavorFade(new_index);
        }
    });

    jQuery('.jq_flavor_prev', context).click(function () {
        if (!fading) {
            fading = true;
            var f_count = jQuery('.flavor_links a', context).length;
            var cur_index = jQuery('.flavor_container', context).data('curIndex');
            var new_index = (cur_index == 0) ? f_count - 1 : cur_index - 1;
            updateSelectedFlavor(new_index);
            flavorFade(new_index);
        }
    });
}

function updateSelectedFlavor(index) {
    jQuery('.flavor_links a').removeClass('selected');
    var link_targ = "#flavor_link" + index;
    jQuery(link_targ).addClass('selected');
}

function flavorFade(index) {
    jQuery('.flavor_container', '.flavorModule').data('curIndex', index);
    var targ_top = parseInt(jQuery('.flavor_item').eq(index).position().top)
    var targ_height = jQuery('.flavor_item').eq(index).outerHeight();
    jQuery('.flavor_items_content').fadeOut(500, function () {
        jQuery('.flavor_items_content').css('top', -targ_top);
        jQuery('.flavor_items').animate({ 'height': targ_height }, 200);
        if (jQuery('.flavor_container').data('state') == 'up') {
            jQuery('.flavor_container').animate({ 'height': targ_height + 5 }, 200);
        }
        jQuery('.flavor_items_content').fadeIn(500, function () {
            fading = false;
        });
    });
}


/***************************************************************/
/***************************************************************/
/***************************************************************/
/****************** OLD STUFF BELOW ****************************/
/***************************************************************/
/***************************************************************/
/***************************************************************/



function InitRecipeScroller(startingSlideNumber) {
    jQuery('.heroSlideShowRecipe,  .heroSlideShow ul, .heroBodyCopy, .heroCoupon, .heroHeadline').each(function (index) {
        jQuery(this).cycle({
            timeout: 6000,            //Time between slides
            speed: 0,          // Transition time
            fx: 'fade',
            pager: '.heroPager',
            next: '.heroNext',
            prev: '.heroPrev',
            debug: true,
            cleartype: true,
            cleartypeNoBg: true,
            startingSlide: startingSlideNumber,
            pagerAnchorBuilder: function (i) {
                if (index == 0)
                    return '<a href="#">' + (i + 1) + '</a>';
                return '.heroPager a:eq(' + i + ')';
            }
        });
    });
    if (jQuery('.heroSlideShow ul img, .heroSlideShowRecipe > div').length > 1) { jQuery('.heroPager, .heroNext, .heroPrev').css({ 'display': 'block' }); }
}

/* Stuff to Show First */

/* Social sharing START */
function ShareSite(sUrl, site) {

    if (typeof window.fireSpotlight == 'function') {
        fireSpotlight('share_pills', 'share01');
    }

    dcsMultiTrack('DCS.dcsuri', '/recipes/share/' + site.toLowerCase(), 'WT.ti', 'Share Content with ' + site);
    window.open(sUrl, 'winShare', 'scrollbars=1,toolbar=0,width=800,height=600');
    return;
}
/* Social sharing END */

/* Video Recommend START */
function RecommendVideo(choice) {
    var videoId = jQuery('input[name=VideoRecommendId]').attr("value")
    var statusFlag = jQuery.parseJSON(jQuery.ajax({ url: "/Services/Profile/LogOnStatusHandler.ashx",
                                                    async: false,
                                                    timeout: 3000
                                                  }).responseText);

    if (statusFlag.toUpperCase() == "AU" || statusFlag.toUpperCase() == "K") {
        jQuery('div.videoRecommend').load("/Services/VideoHandler.ashx?vguid=" + videoId + "&choice=" + choice);
    }
    else {
        jQuery('p.videoRecommendPrompt').show();
    }
    return false;
}

function VideoNoThanks() {
    jQuery('div.VideoRecommendWarnArea').css("visibility", "hidden");
    
    return false;
}



//function receiveOoyalaEvent(playerId, eventName, eventArgs) {
//    var playerObject = document.getElementById(playerId);
//    
//    switch (eventName) {
//        case "currentItemEmbedCodeChanged":
//            playerObject.playMovie();
//            break;
//    }
//}

/* Video Recommend END */


// Browse Recipe Tab Selection
jQuery(function() {
    //jQuery('.findaRecipeMenu a:first').addClass('selected');
    var tabContainers = jQuery('.browseRecipeItems>div');
    tabContainers.hide().filter(':first').show().addClass('selected');
    jQuery('.findaRecipeMenu a').click(function() {
        //jQuery('.findaRecipeMenu a').removeClass('selected');
        //jQuery(this).addClass('selected');
        tabContainers.hide().removeClass('selected');
        jQuery('.browseRecipeItems div' + jQuery(this).attr('name')).show().addClass('selected');
        return false;
    });
});

// Rookie Bake Off Tab Selection
jQuery(function () {
    var index = jQuery('.challengeTabContainer li:has(div.currentTab)').index();
    jQuery('div[id*=challengerContainer' + index + "]").show();
    jQuery('.challengeTabContainer .tab ').click(function () {
        if (jQuery('.challengeTabContainer li:has(div.activeTab)').click(function () {
            jQuery('div[id^=challengerContainer]').hide();
            jQuery('.tab>div').removeClass('currentTab');
            var index = jQuery('.challengeTabContainer li').index(this);
            jQuery('div[id*=challengerContainer' + index + "]").show();
            jQuery('li[id*=tabContainer' + index + "] > div").addClass('currentTab');
            return false;
        }));
    });
});

/* Dynamic search BEGIN */
function PerformSearch(searchTerm, searchType) {
    var redirectUrl = '/Services/Search/LogSearch.ashx?terms=' + encodeURIComponent(searchTerm);

    jQuery.ajax({ url: redirectUrl,
        success: function (data, status, xhr) { PostSearchLogRequest(searchTerm, searchType) },
        error: function (xhr, status, error) { PostSearchLogRequest(searchTerm, searchType, xhr, status, error) },
        timeout: 5000
       });


}

function PostSearchLogRequest(searchTerm, searchType, xhr, status, error) {

    var queryParameters = new Array();
    queryParameters.push('terms=' + encodeURIComponent(searchTerm));

    if (searchType != undefined && searchType != '') {
        queryParameters.push('tab=' + encodeURIComponent(searchType));
    }

    window.location = '/search/?' + queryParameters.join('&');
    return false;
}


function PerformEasyMealSearch(ingredient1, ingredient2, ingredient3, refineFacet, defaultIngredient1Text, defaultAdditionalIngredientText) {

    var terms = new Array();
    var queryParameters = new Array();

    if (ingredient1 != undefined && ingredient1 != '' && ingredient1 != defaultIngredient1Text) {
        terms.push(ingredient1);
        queryParameters.push('ingredient1=' + encodeURIComponent(ingredient1));
    }

    if (ingredient2 != undefined && ingredient2 != '' && ingredient2 != defaultAdditionalIngredientText) {
        terms.push(ingredient2);
        queryParameters.push('ingredient2=' + encodeURIComponent(ingredient2));
    }

    if (ingredient3 != undefined && ingredient3 != '' && ingredient3 != defaultAdditionalIngredientText) {
        terms.push(ingredient3);
        queryParameters.push('ingredient3=' + encodeURIComponent(ingredient3));
    }

    var refineParameter = '';
    if (refineFacet != undefined && refineFacet != '') {
        queryParameters.push('f=' + encodeURIComponent(refineFacet));
        queryParameters.push('refine=' + encodeURIComponent(refineFacet));
    }
    
    var combinedTerms = terms.join(' ');
    queryParameters.push('terms=' + encodeURIComponent(combinedTerms));
    queryParameters.push('tab=Recipes');

//    var redirectUrl = '/Services/Search/LogSearch.ashx?terms=' + encodeURIComponent(combinedTerms);
//    jQuery.ajax({ url: redirectUrl });
    window.location = '/search/?' + queryParameters.join('&');
    return false;
}
/* Dyanmic search END */


//Video Image Swap
jQuery(function() {
    jQuery('.videoModuleRight ul li:first ul li:first').addClass('activeVideo');
    //jQuery('.videoModuleRight ul li ul li:not(.activeVideo) img').after('<span class="playButton"></span>');
    //jQuery('.videoModuleRight ul li ul li.activeVideo img').after('<p>Playing</p>');
});

//Video Recommendation
jQuery(function() {
    
    jQuery('.noThanks').click(function() {
        jQuery('.videoRecommendPrompt').hide();
        return false;
    });
    jQuery('.videoModuleShare > ul > li').hover(
        function() { jQuery('ul:first', this).addClass('show'); },
        function() { jQuery('ul:first', this).removeClass('show'); }
    );
});

//Search Results Page
jQuery(function() {
var hiddenSubFacet = jQuery('.searchResultsFacetsHeaders');
jQuery('.seeMore', hiddenSubFacet).click(function() {
jQuery('div.bottomAll', hiddenSubFacet).hide('fast');
jQuery(this).next('div.bottomAll').show('fast');
return false;
});
jQuery('.bottomAll img', hiddenSubFacet).click(function() {
jQuery('div.bottomAll', hiddenSubFacet).hide('fast');
return false;
});
});


/* Report Abuse */
function sendReportAbuse(containerId, contenttype, itemId, url, comment) {
    jQuery('#' + containerId).load("/Services/ReportAbuse/ReportAbuseHandler.ashx?c_type=" + contenttype + "&item_guid=" + itemId + "&report_url=" + url + "&comment=" + encodeURIComponent(comment));
}

function ReportAbuseSubmit() {
    if (jQuery('#ReportAbuseComment').val().length > 0) {
        jQuery('div#ReportAbuse').hide();

        sendReportAbuse(jQuery('#ReportAbuseDisplayMessage').val(),
        jQuery('#ReportAbuseContentType').val(),
        jQuery('#ReportAbuseItemId').val(),
        jQuery('#ReportAbuseUrl').val(),
        jQuery('#ReportAbuseComment').val());
        
        //reset the form
        jQuery('#ReportAbuseComment').val('');
        jQuery('#ReportMessageError').hide();
    } else {
        jQuery('#ReportMessageError').show();
    }
}

function DisplayReportAbuse(source, contenttype, itemId, url) {

    var e = jQuery('#ReportAbuse');
    
    if(!(e.length > 0)){
        e = jQuery('<div id="ReportAbuse" class="reportAbuse">' +
        '<div id="divLoginMessage">Please describe how this content is inappropriate</div>' +
        '<textarea id="ReportAbuseComment" style="width:220px; height:68px;"></textarea><br />' +
        '<div id="ReportMessageError" style="display:none; color: #ff0000;">You must provide a reason.</div>' +
        '<a onclick="ReportAbuseClose();" style="padding-right:10px; cursor: pointer; cursor: hand;">Cancel</a>' +
        '<a onclick="ReportAbuseSubmit();" style="cursor: pointer; cursor: hand;">Submit</a>' +
        '<input id="ReportAbuseContentType" type="hidden" />' +
        '<input id="ReportAbuseItemId" type="hidden" />' +
        '<input id="ReportAbuseUrl" type="hidden" />' +
        '<input id="ReportAbuseDisplayMessage" type="hidden" />' +
        '</div>');
    }
    jQuery('body').prepend(e);

    jQuery('#ReportAbuseContentType').val(contenttype);
    jQuery('#ReportAbuseItemId').val(itemId);
    jQuery('#ReportAbuseUrl').val(url);
    jQuery('#ReportAbuseDisplayMessage').val(source.id);

    var leftPosition = jQuery(source).offset().left;
    var topPosition = jQuery(source).offset().top + jQuery(source).height() + 2;

    e.css('left', leftPosition);
    e.css('top', topPosition);
    e.css('position', 'absolute');
    e.css('z-index', 4000);
    e.show();
    return false;
}

function ReportAbuseClose() {
    jQuery('div#ReportAbuse').hide();
    return false;
}

/* Pop-Up links - Detect rel attribute and add on-click with href */

jQuery(function () {
    jQuery('a[rel]').click(function () {
        var share_url = jQuery(this).attr('shareurl');
        var share_title = jQuery(this).attr('sharetitle');       
        switch (jQuery(this).attr('rel')) {
            case 'external':
                window.open(jQuery(this).attr('href'));
                break;
            case 'popup_print':
                PrintPopUp(jQuery(this).attr('href'));
                break;
            case 'digg':
                if (share_url == null || share_title == null) {
                    (new shareMethods()).openDigg();
                }
                else {
                    (new shareMethods(share_title, share_url)).openDigg();
                }
                break;
            case 'facebook':
                if (share_url == null || share_title == null) {
                    (new shareMethods).openFacebook();
                }
                else {
                    (new shareMethods(share_title, share_url)).openFacebook();
                }
                break;
            case 'reddit':
                if (share_url == null || share_title == null) {
                    (new shareMethods).openReddit();
                }
                else {
                    (new shareMethods(share_title, share_url)).openReddit();
                }
                break;
            case 'stumbleUpon':
                if (share_url == null || share_title == null) {
                    (new shareMethods).openStumbleupon();
                }
                else {
                    (new shareMethods(share_title, share_url)).openStumbleupon();
                }
                break;
            case 'delicious':
                if (share_url == null || share_title == null) {
                    (new shareMethods).openDelicious();
                }
                else {
                    (new shareMethods(share_title, share_url)).openDelicious();
                }
                break;
            case 'twitter':
                if (share_url == null || share_title == null) {
                    (new shareMethods).openTwitter();
                }
                else {
                    (new shareMethods(share_title, share_url)).openTwitter();
                }
                break;
            default:
                return true;
        }
        return false;
    });

    jQuery('div.rtbTop a[rel=share_recipe]').share({ shareType: 'share_recipe' });
    jQuery('div.rtbBottom a[rel=share_recipe]').share({ direction: 'top', shareType: 'share_recipe' });
    jQuery('div.rtbRight a[rel=share_recipe]').share({ direction: 'left', shareType: 'share_recipe' });
    jQuery('a[rel=share]').share();
});

jQuery.query = function() {
    var r = {};
    var q = location.search;
    q = q.replace(/^\?/, ''); // remove the leading ?
    q = q.replace(/\&$/, ''); // remove the trailing &
    jQuery.each(q.split('&'), function() {
        var key = this.split('=')[0];
        var val = this.split('=')[1];
        // convert floats
        if (/^[0-9.]+$/.test(val))
            val = parseFloat(val);
        // ingnore empty values
        if (val)
            r[key] = val;
    });
    return r;
};

/*  ------   Double Click tag functions. (aka Spotlight)    */

function DoubleClickTagIt(tagSrc, tagType, tagCat, tagOrd, protocal) {

    var axel = Math.random() + "";
    var a = axel * 10000000000000;
    var spotpix = new Image();
    if (tagOrd == null)
        spotpix.src = protocal + "://fls.doubleclick.net/activityi;src=" + tagSrc + ";type=" + tagType + ";cat=" + tagCat + ";ord=" + a;
    else
        spotpix.src = protocal + "://fls.doubleclick.net/activityi;src=" + tagSrc + ";type=" + tagType + ";cat=" + tagCat + ";ord=" + tagOrd + ";num=" + a;

    spotpix.onload = DoubleClickTagItFakeFunction;
    return true;
}

function DoubleClickTagItFakeFunction() { }

/*  ------ End  Double Click tag functions. (aka Spotlight)    */

/* Limit Max Length */
jQuery.fn.limitMaxlength = function(options) {

    var settings = jQuery.extend({
        attribute: "maxlength",
        onLimit: function() { },
        onEdit: function() { }
    }, options);

    // Event handler to limit the textarea
    var onEdit = function() {
        var textarea = jQuery(this);
        var maxlength = parseInt(textarea.attr(settings.attribute));

        if (textarea.val().length > maxlength) {
            textarea.val(textarea.val().substr(0, maxlength));

            // Call the onlimit handler within the scope of the textarea
            jQuery.proxy(settings.onLimit, this)();
        }

        // Call the onEdit handler within the scope of the textarea
        jQuery.proxy(settings.onEdit, this)(maxlength - textarea.val().length);
    }

    this.each(onEdit);

    return this.keyup(onEdit)
				.keydown(onEdit)
				.focus(onEdit)
				.live('input paste', onEdit);
}

jQuery(function() {
    jQuery('textarea[maxlength]').limitMaxlength();
});

/* Grocerylist */
//function GetGroceryList(callbackFunction) {
//    jQuery.ajax({
//        url: '/Services/grocerylist/getlist.ashx',
//        success: callbackFunction,
//        error: callbackFunction,
//        complete: callbackFunction,
//        //data: '{"ListId":"76838d4d-a859-4caf-ae45-76122f59aefb"}',
//        dataType: 'json',
//        type: 'POST'
//    });
//}

function GetGroceryList(callbackFunction, listId) {
    var requestData;
    if (listId != null) {
        var requestObject = { ListId: listId }
        requestData = JSON.stringify(requestObject)
    }
    jQuery.ajax({
        url: '/Services/grocerylist/getlist.ashx',
        success: callbackFunction,
        error: callbackFunction,
        data: requestData,
        dataType: 'json',
        type: 'POST'
    });
}

function GetGroceryLists(callbackFunction) {
    jQuery.ajax({
        url: '/Services/grocerylist/GetGrocerylists.ashx',
        success: callbackFunction, 
        dataType: 'json',
        type: 'POST'
    });
}

function AddRecipeToGroceryList(listId, recipeId, callbackFunction) {
    var requestObject = {ListId: listId, RecipeId: recipeId}
    jQuery.ajax({
        url: '/Services/grocerylist/AddRecipeToList.ashx',
        success: callbackFunction,
        data: JSON.stringify(requestObject),
        dataType: 'json',
        type: 'POST'
    });
}

function AddRecipeToNewGroceryList(listName, recipeId, callbackFunction) {
    var requestObject = { ListName: listName, RecipeId: recipeId }
    jQuery.ajax({
        url: '/Services/grocerylist/AddListAndRecipe.ashx',
        success: callbackFunction,
        data: JSON.stringify(requestObject),
        dataType: 'json',
        type: 'POST'
    });
}

function DeleteGroceryList(listId, callbackFunction) {
    var requestObject = { ListId: listId }
    jQuery.ajax({
        url: '/Services/grocerylist/DeleteGroceryList.ashx',
        success: callbackFunction,
        data: JSON.stringify(requestObject),
        dataType: 'json',
        type: 'POST'
    });
}

function DeleteRecipeFromGroceryList(listId, recipeId, callbackFunction) {
    var requestObject = { ListId: listId, RecipeId: recipeId }
    jQuery.ajax({
        url: '/Services/grocerylist/DeleteRecipeFromGroceryList.ashx',
        success: callbackFunction,
        data: JSON.stringify(requestObject),
        dataType: 'json',
        type: 'POST'
    });
}

function AddNewGroceryList(listName, callbackFunction) {
    var requestObject = { ListName: listName }
    jQuery.ajax({
        url: '/Services/grocerylist/AddGroceryList.ashx',
        success: callbackFunction,
        data: JSON.stringify(requestObject),
        dataType: 'json',
        type: 'POST'
    });
}

function DeleteGroceryListLine(listId, listLineId, callbackFunction) {
    var requestObject = { ListId: listId, ListLineId: listLineId }
    jQuery.ajax({
        url: '/Services/grocerylist/DeleteLineItem.ashx',
        success: callbackFunction,
        data: JSON.stringify(requestObject),
        dataType: 'json',
        type: 'POST'
    });
}

function AddGroceryListLine(listId, description, categoryId, callbackFunction) {
    var requestObject = { ListId: listId, Description: description, CategoryId: categoryId }
    jQuery.ajax({
        url: '/Services/grocerylist/AddLineItem.ashx',
        success: callbackFunction,
        data: JSON.stringify(requestObject),
        dataType: 'json',
        type: 'POST'
    });
}

jQuery(function () {
    jQuery('div[id*=PollSubmit]').click(function () {
        var selectedPollChoice = jQuery('input:radio[name=radioVote]:checked').val();
        var atLeastOneIsChecked = jQuery('input:radio[name=radioVote]:checked').length > 0;
        var PERCENT_BAR_WIDTH_MULTIPLIER = .8;

        //function AddPollEntry(selectedPollChoice) {
        if (atLeastOneIsChecked == 0) {
            jQuery('div[id*=PollError]').show();
        }
        else {
            var requestObject = { ChoiceId: selectedPollChoice }
            jQuery.ajax({
                url: '/Services/Polls/PollHandler.ashx',
                success: function (data) {

                    //Needs to log in first
                    if (data.UserState == 'A') {
                        location.href = "/login";
                    }

                    //Everything ok show the poll results
                    if (data.UserState == 'K') {
                        jQuery('div[id*=SubmissionPanel]').hide();
                        jQuery('div[id*=DisplayPanel]').hide();
                        jQuery('div[id*=DisplayPollPanel]').show();
                        var tempString = "";

                        var i;
                        for (i = 0; i < data.InfoItems.length; i++) {
                            tempString += '<div class="poll_competitor">';
                            tempString += '<div class="competitor_text">' + data.InfoItems[i].LabelText + '</div>';
                            tempString += '<div class="competitor_bar left" style="width:' + (data.InfoItems[i].PercentLead * PERCENT_BAR_WIDTH_MULTIPLIER) + '%"></div>';
                            tempString += '<div class="competitor_pct left">' + data.InfoItems[i].PercentTotal + '%</div>';
                            tempString += '<div class="full_clear"></div>';
                            tempString += '</div>';
                        };

                        jQuery('div[id*=PollDisplayRepeater]').append(tempString);

                    }
                    else {
                        jQuery('div[id*=SubmissionPanel]').show();
                        jQuery('div[id*=DisplayPanel]').hide();
                        jQuery('div[id*=DisplayPollPanel]').hide();
                    }

                    jQuery('div[id*=PollError]').hide();

                },
                error: function (xhr, status, error) {
                    //alert("Failed to select poll choice!");

                },
                data: requestObject,
                dataType: 'json',
                type: 'POST'
            });
        }

        //}
    });
});

jQuery(function () {
    jQuery('div[id*=TipSubmit]').click(function () {
        var suppliedtiplength = jQuery("textarea[id*=TipText]").val().length;
        var suppliedtip = jQuery("textarea[id*=TipText]").val();
        var tipguid = jQuery("input[id*=TipGuid]").val();

        //Make sure they supplied a tip that was less then 250 charactors
        if (suppliedtiplength == 0) {
            if (suppliedtip == 0) {
                jQuery('div[id*=TipErrorLabel]').html("You have not entered any information");
            }
        }
        else if (suppliedtiplength >= 250) {
            jQuery('div[id*=TipErrorLabel]').html("You have exceeded the character limit");
        }
        else {
            //alert(suppliedtip);
            var requestObject = { TipContent: suppliedtip, TipGUID: tipguid }
            jQuery.ajax({
                url: '/Services/Tips/TipHandler.ashx',
                success: function (data) {

                    //Everything ok show the poll results
                    if (data.SuccessStatus == 'K') {
                        jQuery('div[id*=TipFormContainer]').hide();
                        jQuery('div[id*=TipThankYouContainer]').show();

                    }
                    else {
                        if (data.ErrorType == '2') {
                            //Need to agree to community terms
                            location.href = data.ErrorMessage;
                        }
                        else {
                            jQuery('div[id*=TipErrorLabel]').html(data.ErrorMessage);
                        }
                    }
                },
                error: function (xhr, status, error) {
                    //alert("Failed to select poll choice!");

                },
                data: requestObject,
                dataType: 'json',
                type: 'POST'
            });
        }

        //}
    });
});


function ParseMicrosoftDate(inputDate) {
    var result = new Date(parseInt(inputDate.substr(6)));
    return result;
}

function MarinTagging(catDesc) {
    try {
         var src;
         src = "https://tracker.marinsm.com/tp?act=2&cid=6139535055&trans=" + catDesc;
         document.getElementById("marinFrame").src = ("https:" == document.location.protocol) ? src.replace("http:", "https:") : src;
        } catch (err) {}
    return true;
}

/* Newsletter Widget Start */

function getSubscriptions() {
    jQuery.ajax({
        type: "POST",
        url: "/Services/Profile/Newsletters/GetSubscriptions.ashx",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (data) {
            jQuery(".knownUserNewsletter").empty().append(jQuery("#SubscriptionTemplate").tmpl(data));
            jQuery(".knownUserNewsletter input:checkbox").click(function () {
                var $checkBox = jQuery(this);
                var checked = $checkBox.attr("checked") == true
                processSubscription($checkBox.next().attr("value"), checked, this)
            });        
        }
    });
};

function processSubscription(newsletterId, subscribed, item) {
    jQuery(".loadingNewsletter").html("<img src='/images/coupons/loading.gif' alt='Loading...' />").show();

    var requestObject = { "NewsletterId": newsletterId, "Subscribed": subscribed };
    jQuery.ajax({
        type: "POST",
        url: "/Services/Profile/Newsletters/ProcessSubscription.ashx",
        data: JSON.stringify(requestObject),
        complete: function () {
            jQuery(".loadingNewsletter").empty().hide();
        },
        success: function (data) {
            if (data == true) {
                var message;
                if (subscribed) {
                    message = " (subscribed)";
                    subscribeNewsletter(newsletterId);
                }
                else {
                    message = " (unsubscribed)";
                    unsubscribeNewsletter();
                }
                jQuery(item).next().next().next().text(message);
            }
            else {
                jQuery(item).next().next().next().text("Error occurred while processing");
            }
        },
        error: function (data) {
            jQuery(item).next().next().next().text("Error occurred while processing");
        }
    });
};

/* Newsletter Widget End */

 

