﻿/// <reference path="../jquery-1.4.2.js"/>

var debug = new Boolean(false);
var recipeId;
//registers javascript namespace
function registerNS(ns) {
    var nsParts = ns.split(".");
    var root = window;

    for (var i = 0; i < nsParts.length; i++) {
        if (typeof root[nsParts[i]] == "undefined")
            root[nsParts[i]] = new Object();

        root = root[nsParts[i]];
    }
}
    registerNS("Recipes");

    jQuery(document).ready(function () {
        jQuery("#TipsTabView").addClass("hide");
        jQuery("#ReviewsTabView").addClass("hide");
        recipeId = jQuery("#hdnRecipeId").val();

        Recipes.MGCInit();
        Recipes.ValidationInit();
        Recipes.AddTabClickBehaviour();
        Recipes.GetReviewsAndTips();
        Recipes.ToolBarClickAction();
        Recipes.JumpToTab();
        Recipes.UserOptions("#recipeUserRating");
        Recipes.UserOptions("#recipeOverallRating");
        Recipes.UserOptions("#recipeOveralUserRating");
        jQuery("#MethodInformationSection li").wrapInner(function () {
            return "<span class='RecipeMethodStep' />"
        }).prepend(function () {
            return "<span class='RecipeMethodItemNumber'>" + (jQuery(this).index("#MethodInformationSection li") + 1) + "</span>"
        });

    });

    function GrocerylistChange(list) {
        if (list.options.selectedIndex > 0) {
            jQuery('#NewListName').val('');
            jQuery('#NewListName').attr('disabled', true);
        }
        else {
            jQuery('#NewListName').attr('disabled', false);
        }
    }

    jQuery.fn.QuickPager = function (options) {
        if (options.totalRecords > options.pageSize) {
            var pageCounter = Math.ceil(options.totalRecords / options.pageSize);
            var pageNav = "<div id='inline-list'><UL>";

            if (Number(options.currentPage) > 1) {
                pageNav += "<LI style='font-weight: bold;'><a onClick='Recipes.GetReviews(" + (Number(options.currentPage) - 1) + "); return false;' href='#'>&lt;Previous |</a></LI>";
            }
            else {
                pageNav += "<LI><a onClick='return false;' href='#' class='notActive'>&lt;Previous |</a></LI>";
            }

            for (i = 1; i <= pageCounter; i++) {
              
                if (i == options.currentPage || (i == 1 && typeof (options.currentPage) == "undefined")) {                    
                    pageNav += "<LI><a onClick='return false;' href='#' class='notActive'>" + i + "</a></LI>";
                }
                else {
                    if (options.pagingForReviews) {
                        pageNav += "<LI><A onClick='Recipes.GetReviews(" + i + "); return false;' href='#'>" + i + "</A></LI>";
                    }
                    else {
                        pageNav += "<LI><A onClick='Recipes.GetTips(" + i + "); return false;' href='#'>" + i + "</A></LI>";
                    }
                }
            }

            if (Number(options.currentPage) == pageCounter) {
                pageNav += "<LI style='font-weight:'><a onClick='return false;' href='#' class='notActive'>...| Next&gt;</a></LI>";

            }
            else if (typeof (options.currentPage) == "undefined") {
                pageNav += "<LI style='font-weight: bold;'><a onClick='Recipes.GetReviews(2); return false;' href='#'>...| Next&gt;</a></LI>";
            }
            else {
                pageNav += "<LI style='font-weight: bold;'><a onClick='Recipes.GetReviews(" + (Number(options.currentPage) + 1) + "); return false;' href='#'>...| Next&gt;</a></LI>";
            }

            pageNav += "</UL></div>";
            jQuery(this).html(pageNav);
        }
    };

    function PagingDetails() {
        this.pagingForReviews = true;
        this.currentPage = 1;
        this.totalRecords = 100;
        this.pageSize = 10
    }

    var rd_mouseovertop = false;
    var rd_mouseoverbottom = false;
    var rguid;

    Recipes.GetRequestedPage = function(additionalData, successfulCallback) {
        if (additionalData.RecipeId == null) {
            additionalData.RecipeId = recipeId;
        }
        jQuery.ajax(
            {
                url: '/layouts/PB/Recipes/Handlers/RecipeHandler.ashx',
                type: 'GET',
                data: encodeURIComponent(JSON.stringify(additionalData)),
                datatype: 'json',
                contentType: "application/json; charset=utf-8",
                success: function(result) { successfulCallback(result); }
            }
          );
    }

    Recipes.PostData = function(additionalData, successfulCallback) {
        if (additionalData.RecipeId == null) {
            additionalData.RecipeId = recipeId;
        }
        jQuery.post("/layouts/PB/Recipes/Handlers/RecipeHandler.ashx", 
                    encodeURIComponent(JSON.stringify(additionalData)),
                    function(result) { successfulCallback(result); });
    }

    //Global error handler
    jQuery(document).ajaxError(function(event, request, settings, exception) {
        var requestData = jQuery.parseJSON(settings.data);
        var action = requestData.Action;
        if (debug) {
            jQuery("#ajaxError").append("<li>Action: " + action + " failed.</li>");
            jQuery("#ajaxError").css('display', 'block');
        }
    });

    Recipes.scErrorHandler = function(type, errorMessage) {
        jQuery("#" + type + "ErrorTop").text(errorMessage).removeClass("hide");
        jQuery("#" + type + "ErrorBottom").removeClass("hide");
    }


    Recipes.UserOptions = function(source) {
        // Enable star mouseovers, rating
        jQuery(source + ' img').each(function(i) {
            var charIndex = jQuery(this).attr('src').indexOf('star_') + 10;
            var sChar = jQuery(this).attr("src").substring(charIndex, charIndex+1);
            var altString = " Stars";
            if (i == 0) { altString = " Star"; }
            jQuery(this).attr("id", "star" + i + sChar)
                   .mouseover(function() {
                       rd_fillStars(source, this);
                   })
                   .mouseout(function() {
                       rd_clearStars(source, this);
                   })
                   .click(function() {
                       if (source == "#recipeOverallRating")
                           Recipes.UpdateRating(this);
                       else
                           Recipes.UpdateRating(this);
                   })
                   .attr("style", "cursor:pointer; display:inline; width:16px; height:16px; ")
                   .attr("alt", "Click to rate this " + (i + 1) + altString)
                   .attr("title", "Click to rate this " + (i + 1) + altString);
        });
    }

    Recipes.AddTabClickBehaviour = function() {
        jQuery(".ReviewsTabHeader").click(
            function() {
                Recipes.TabClicks(".ReviewsTabHeader", "#ReviewsTabView");
                Recipes.TrackReviewView();               
                if (!isMemberGenerated) {
                    dcsMultiTrack('DCS.dcsuri', '/recipes/readrecipereview.aspx', 'DCS.dcsqry', 'rid=' + recipeId, 'WT.ti', 'Read Recipe Review');
                    ntptEventTag(' ev=readrecipereview_bt&RecipeId=' + recipeId + '&RecipeTitle="' + escape(jQuery("#hdnRecipeTitle").val()) + '"');
                   
                } else {
                    dcsMultiTrack('DCS.dcsuri', '/userrecipes/readrecipereview.aspx', 'DCS.dcsqry', 'rid=' + recipeId, 'WT.ti', 'Read Member Generated Recipe Review');
                    ntptEventTag(' ev=MGCreadrecipereview_bt&RecipeId=' + recipeId + '&RecipeTitle=' + escape(jQuery("#hdnRecipeTitle").val()) + '');
                }
            }
        );

        jQuery(".TipsTabHeader").click(
            function() {
                Recipes.TabClicks(".TipsTabHeader", "#TipsTabView");
            }
        );

        jQuery("#RecipeTabHeader").click(
            function() {
                Recipes.TabClicks("#RecipeTabHeader", "#RecipeTabView");
            }
        );

        jQuery(".ReviewItLink").click(
            function() {
                if (isKnown) {
                    Recipes.TabClicks(".ReviewsTabHeader", "#ReviewsTabView");
                    Recipes.showInputReviewSection('#topInputReviewSection');
                }
                else
                    Recipes.positionLoginAlert(this, "review");

                DoubleClickTagIt('1869704', 'pills674', 'viewr310', '1', 'http');
                //
                return false;
            }
        );
    }
    
    Recipes.TabClicks = function(header, view) {
        jQuery(".RecipeTabClass").addClass("tabClosed");
        jQuery(".openTabContent").addClass("hide");

        jQuery(header).addClass("tabOpen").removeClass("tabClosed");
        jQuery(view).removeClass("hide");
    }

    var form_override = false;

    Recipes.JumpToTab = function () {
        var qs_tab = getQueryParam("tab");
        var qs_form = getQueryParam("form");

        if (qs_tab != "") {
            if (qs_tab == "tips") {
                Recipes.TabClicks(".TipsTabHeader", "#TipsTabView");
                if (qs_form == "1" && isKnown) {
                    Recipes.showInputTipSection('#topInputTipSection', null);
                    form_override = true;
                    
                }
            }
            if (qs_tab == "reviews") {
                Recipes.TabClicks(".ReviewsTabHeader", "#ReviewsTabView");
                Recipes.TrackReviewView();
                if (qs_form == "1" && isKnown) {
                    Recipes.showInputReviewSection('#topInputReviewSection', null);
                    form_override = true;
                }
            }
            if (qs_tab == "Email") {
                window.setTimeout(function () { jQuery(".emailRecipeTrigger").trigger('click'); }, 0);
            }
        }
    }

    function rd_noThanks() {
        jQuery('div#loginAlert').hide();
        return false;
    }
    
    function getQueryParam(param) {
        param = param.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
        var reString = "[\\?&]" + param + "=([^&#]*)";
        var regex = new RegExp(reString);
        var results = regex.exec(window.location.href);
        if (results == null)
            return "";
        else
            return results[1];
    }

    // Enable star mouseovers, rating

    function rd_clearStars(source, image) {
        jQuery(source + ' img').each(function (i) {
            var prevSource = jQuery(this).attr("id").substring(5, 6);
            var backsrc = "/images/star_blue_empty.png";
            if (prevSource == "h") { backsrc = "/images/star_blue_half.png"; }
            if (prevSource == "f") { backsrc = "/images/star_blue_full.png"; }
            jQuery(this).attr("src", backsrc);
        });
    }

    function rd_fillStars(source, image) {
        var snum = parseInt(image.id.substring(4, 5));
        jQuery(source + ' img').each(function(i) {
            if (i <= snum) {
                jQuery(this).attr("src", "/images/star_blue_full.png");
            }
            else {
                jQuery(this).attr("src", "/images/star_blue_empty.png");
            }
        });
    }

    var _tmplCache = {}
    this.parseTemplate = function(str, data) {
        var err = "";
        try {
            var func = _tmplCache[str];
            if (!func) {
                var strFunc =
            "var p=[],print=function(){p.push.apply(p,arguments);};" +
                        "with(obj){p.push('" +

             str.replace(/[\r\t\n]/g, " ")
               .replace(/'(?=[^#]*#>)/g, "\t")
               .split("'").join("\\'")
               .split("\t").join("'")
               .replace(/<#=(.+?)#>/g, "',$1,'")
               .split("<#").join("');")
               .split("#>").join("p.push('")
               + "');}return p.join('');";

                func = new Function("obj", strFunc);
                _tmplCache[str] = func;
            }
            return func(data);
        } catch (e) { err = e.message; }
        return "< # ERROR: " + err + " # >";
    }

    Recipes.hideInputTipSection = function() {
        jQuery("#bottomInputTipSection").addClass("hide");
        jQuery("#topInputTipSection").addClass("hide");
        jQuery("#tipErrorTop").addClass("hide");
        jQuery("#tipErrorBottom").addClass("hide");
        jQuery("#tipsText").val("");
        return false;
    }

    Recipes.showInputTipSection = function(inputSection, source) {
        if (isKnown && canUserSubmitData) {
            jQuery("#inputTipSection").appendTo(jQuery(inputSection)).removeClass("hide");
            jQuery(inputSection).removeClass("hide");
        }
        else if (isKnown && !canUserSubmitData) {
            var returnUrl = window.location.href;
            if (returnUrl.indexOf("tab=reviews") == -1 &&
                    returnUrl.indexOf("tab=tips") == -1 &&
                    returnUrl.indexOf("?") == -1) {
                returnUrl = returnUrl + "?tab=tips";
            } else if (returnUrl.indexOf("tab=reviews") == -1 &&
                           returnUrl.indexOf("tab=tips") == -1 &&
                           returnUrl.indexOf("?") > 0) {
                returnUrl = returnUrl + "&tab=tips";
            } else if (returnUrl.indexOf("tab=reviews") > 0) {
                returnUrl = returnUrl.replace("tab=reviews", "tab=tips");
            }
            var redirectUrl = "/member-update?ReturnURL=" + encodeURIComponent(returnUrl);
            window.location.href = redirectUrl;
            }
        else{
            Recipes.positionLoginAlert(source, "tip", true);
            }
        return false;
    }

    Recipes.hideInputReviewSection = function() {
        jQuery("#bottomInputReviewSection").addClass("hide");
        jQuery("#topInputReviewSection").addClass("hide");
        jQuery("#reviewErrorTop").addClass("hide");
        jQuery("#reviewErrorBottom").addClass("hide");
        jQuery("#reviewsText").val("");
        return false;
    }

    Recipes.showInputReviewSection = function(inputSection, source) {
        if (isKnown && canUserSubmitData) {
            jQuery("#inputReviewSection").appendTo(jQuery(inputSection)).removeClass("hide");
            jQuery(inputSection).removeClass("hide");
            jQuery('#reviewsText').focus();
        }
        else if (isKnown && !canUserSubmitData) {
            var returnUrl = window.location.href;
            if (returnUrl.indexOf("tab=reviews") == -1 &&
                returnUrl.indexOf("tab=tips") == -1 &&
                returnUrl.indexOf("?") == -1) {
                returnUrl = returnUrl + "?tab=reviews";
            } else if (returnUrl.indexOf("tab=reviews") == -1 &&
                       returnUrl.indexOf("tab=tips") == -1 &&
                       returnUrl.indexOf("?") > 0) {
                returnUrl = returnUrl + "&tab=reviews";
            } else if (returnUrl.indexOf("tab=tips") > 0) {
                returnUrl = returnUrl.replace("tab=tips", "tab=reviews");
            }

            var redirectUrl = "/member-update?ReturnURL=" + encodeURIComponent(returnUrl);
            window.location.href = redirectUrl;
        }
        else {
            Recipes.positionLoginAlert(source, "review", true);
        }
        return false;
    }

    Recipes.AddToRecipeBox = function(source) {
        if (isKnown) {
        }
        else
            Recipes.positionLoginAlert(source, "AddToRecipeBox");
    }

    Recipes.MessageOn = function () {
        jQuery('#udi_message').show();
    }

    Recipes.MessageOff = function () {
        jQuery('#udi_message').hide();
    }

    Recipes.MGCInit = function () {
        jQuery('#udi_link').click(function () { jQuery('#udi_message').toggle(); });
        jQuery('#udi_message_close').click(function () { jQuery('#udi_message').hide(); });
        //            jQuery('#udi_link').click(function() {
        //                Recipes.MessageOn();
        //            }, function() {
        //                Recipes.MessageOff();
        //            });
        //            
        //            jQuery('#udi_message').click(function() {
        //                Recipes.MessageOn();
        //            }, function() {
        //                Recipes.MessageOff();
        //            });
    }

    Recipes.ValidationInit = function() {
        var MaxLength = 600;
        jQuery('#reviewsText, #tipsText').bind('keyup blur', function() {
            if (jQuery(this).val().length > MaxLength) {
                jQuery(this).val(jQuery(this).val().substring(0, MaxLength));
            }
        });

    }

    jQuery(document).ready(function() {
        if (jQuery('.jq_video_hidden').attr('value') == "1") {
            jQuery('.jq_beauty_shot a').click(function() {
                jQuery('.recipeVideo').show();
                jQuery('.video_play_overlay').hide();
                jQuery('.video_button').hide();
                var containerDiv = jQuery('.jq_mask_size');
                var width = containerDiv.width();
                var height = containerDiv.height();
                jQuery('.recipeMask').show().css({ 'width': width, 'height': height });
                PlayMovieWhenReady();
                return false;
            });
            jQuery('#video_close').click(function() {
                jQuery('.recipeMask').hide();
                jQuery('.recipeVideo').hide();
                jQuery('.video_play_overlay').show();
                jQuery('.video_button').show();
            });
        }
        else { jQuery('.jq_beauty_shot a').click(function() { return false; }); }

    });

    function PlayMovieWhenReady() {
        if (typeof jQuery('#VideoPlayer')[0].playMovie == 'function') {
            jQuery('#VideoPlayer')[0].playMovie();
            result = true;
        }else{
            window.setTimeout(PlayMovieWhenReady, 20);
        }
    }

    Recipes.ToolBarClickAction = function() {
        jQuery(".rtSaveRecipe").click(function() {
            if (!isKnown) {
                Recipes.positionLoginAlert(jQuery(this), "AddToRecipeBox");
                return false;
            }
            DoubleClickTagIt('1869704', 'pills674', 'savep138', '1', 'http');
            MarinTagging('UTM:I||save771||||'); 
//            if (!isMemberGenerated) {
//                dcsMultiTrack('DCS.dcsuri', '/recipes/RecipeBox.aspx', 'DCS.dcsqry', 'RecipeIdList=' + recipeId, 'WT.ti', 'Recipe saved to Recipe Box');
//            } else {
//                dcsMultiTrack('DCS.dcsuri', '/userrecipes/RecipeBox.aspx', 'DCS.dcsqry', 'RecipeidList=' + recipeId, 'WT.ti', 'Member Generated Recipe saved to Recipe Box');
//            }
        });

        jQuery(".rtGroceryList").click(function() {
            if (!isKnown) {
                Recipes.positionLoginAlert(jQuery(this), "AddToGroceryList");
                return false;
            }
//            if (!isMemberGenerated) {
//                dcsMultiTrack('DCS.dcsuri', '/recipes/AddToGroceryList.aspx', 'DCS.dcsqry', 'recipeIds=' + recipeId, 'WT.ti', 'Recipe Added to Grocery List');
//            } else {
//                dcsMultiTrack('DCS.dcsuri', '/userrecipes/AddToGroceryList.aspx', 'DCS.dcsqry', 'recipeIds=' + recipeId, 'WT.ti', 'Member Generated Recipe Added to Grocery List');
//            }
            return false;
        });
    }


    Recipes.positionLoginAlert = function(source, type, insideTab, subtype) {

        var leftPosition = jQuery(source).offset().left;
        var topPosition = jQuery(source).offset().top + jQuery(source).height() + 5;
        var position = "absolute";

        jQuery('body').prepend(jQuery("#loginAlert"));
        jQuery('#' + loginLinkid).attr('href', jQuery('#' + originalLoginUrlId).html());

        if (type == "rate") {
            jQuery("#divLoginMessage").text("You must be logged in to rate a recipe");
            if (loginLinkid != 'undefined' && loginLinkid != null && loginLinkid != 'null') {
                jQuery('#' + loginLinkid).attr('href', jQuery('#' + loginLinkid).attr('href').replace('login?', 'login?esrc=15897&'));
            }
        }
        else if (type == "recommend") {
            jQuery("#divLoginMessage").text("You must be logged in to recommend a recipe");
        }
        else if (type == "recommendreview") {
            jQuery("#divLoginMessage").text("You must be logged in to recommend a recipe");
            if (loginLinkid != 'undefined' && loginLinkid != null && loginLinkid != 'null') {
                jQuery('#' + loginLinkid).attr('href', jQuery('#' + loginLinkid).attr('href').replace('login?', 'login?esrc=15898&') + encodeURIComponent("?tab=reviews"));
            }
        }
        else if (type == "recommendtip") {
            jQuery("#divLoginMessage").text("You must be logged in to recommend a tip");
            if (loginLinkid != 'undefined' && loginLinkid != null && loginLinkid != 'null') {
                jQuery('#' + loginLinkid).attr('href', jQuery('#' + loginLinkid).attr('href').replace('login?', 'login?esrc=15898&') + encodeURIComponent("?tab=tips"));
            }
        }
        else if (type == "review") {
            jQuery("#divLoginMessage").text("You must be logged in to review a recipe");
            if (loginLinkid != 'undefined' && loginLinkid != null && loginLinkid != 'null') {
                jQuery('#' + loginLinkid).attr('href', jQuery('#' + loginLinkid).attr('href').replace('login?', 'login?esrc=15898&') + encodeURIComponent("?tab=reviews&form=1"));
            }
        }
        else if (type == "tip") {
            jQuery("#divLoginMessage").text("You must be logged in to add a tip");
            if (loginLinkid != 'undefined' && loginLinkid != null && loginLinkid != 'null') {
                jQuery('#' + loginLinkid).attr('href', jQuery('#' + loginLinkid).attr('href') + encodeURIComponent("?tab=tips&form=1"));
            }
        }
        else if (type == "AddToRecipeBox")
            jQuery("#divLoginMessage").text("You must be logged in to add this to your Recipe Box");
        else if (type == "AddToGroceryList")
            jQuery("#divLoginMessage").text("You must be logged in to add this to your Grocery List");

        jQuery("#loginAlert").css('left', leftPosition);
        jQuery("#loginAlert").css('top', topPosition);
        jQuery("#loginAlert").css('position', position);
        jQuery("#loginAlert").css('z-index', 1100);
        jQuery('div#loginAlert').show();
    }

