﻿if (typeof ROGERS == "undefined" || !ROGERS) { var ROGERS = {}; }
ROGERS.debug = true;
ROGERS.utils = ROGERS.utils || {};
ROGERS.tools = ROGERS.tools || {};
ROGERS.tools.Food = ROGERS.tools.Food || {};

/* Initialize client-side behaviour after page has loaded
*****************************************************/
$(function() {

    var loggedIn = $.cookie("ext") != null && $.cookie("ext").length > 0;
    if (loggedIn) {
        $("#login").html("<a href='http://food.chatelaine.com/Site/Logout/'>Logout</a>");
        $("#login").css("margin-right", "20px");
    } else {
        $("#login").html("<a href='http://my.chatelaine.com/uumsweb/login.do?property=100051&target=" + document.location.href.toString() + "'>Login</a>");
    }

    // NAVIGATION
    var nav_visible = 3;
    $(".recipe-left-nav ul").each(CollapseList);

    function CollapseList() {
        if ($(this).find("li").length > nav_visible + 1) {
            $(this).find("li").slice(nav_visible + 1).hide();
            if (!$(this).find('.recipe-nav-more').length) {
                $(this).append("<li class='recipe-nav-more'><a href='#'>More...</a></li>");
            } else {
                $(this).find('.recipe-nav-more a').text("More...");
                $(this).find('.recipe-nav-more').show();
            }
        }
    }

    $(".recipe-nav-more a").toggle(
        function() {
            $(this).closest("ul").find("li").slideDown();
            $(this).text("...Less");
            return false;
        },
        function() {
            $(this).closest("ul").each(CollapseList);
            return false;
        }
    );

    $(".print").click(function() {
        var href = $(this).attr("href");
        var printWin = window.open(href, "PrintWindow");
        return false;
    });

    $(".form-confirm").submit(function() {
        var answer = confirm("Are you sure?");
        return answer;
    });


    /** Meal Planning
    */
    var my_recipes_url = window.location.protocol + "//" + window.location.host + "/Recipes/MyRecipes";
    $(".meal-multiselect").each(function() {
        $(this).fcbkcomplete({ json_url: my_recipes_url, json_cache: true });
        $("#plan-loading").hide();
        $("#plan-wrap").fadeIn("slow");
    });

    var meal_navigating = false;
    var scrollBy = 220;
    $("#dayPrev").click(function() {
        MealPlanNav(-scrollBy);
        return false;
    });

    $("#dayNext").click(function() {
        MealPlanNav(scrollBy);
        return false;
    });

    function MealPlanNav(offset) {
        var currentLeft = $("#plan-grid").scrollLeft();
        if ($.browser.msie) {
            $("#plan-grid").hide();
            $("#plan-grid").scrollLeft(currentLeft + offset);
            $("#plan-grid").show();
        } else {
            var op = offset > 0 ? "+=" : "-=";
            offset = Math.abs(offset);
            if (!meal_navigating) {
                meal_navigating = true;
                $("#plan-grid").scrollTo(op + offset + "px", 250,
                    { axis: 'x',
                        onAfter: function() {
                            meal_navigating = false;
                        }
                    });
            }
        }
    }

    $("#plan-create-start").dialog({
        autoOpen: false,
        modal: true,
        title: "MEAL PLAN OPTIONS",
        width: 375
    });

    $("#plan-create-button").click(function() {
        $("#plan-create-start").dialog('open');
        return false;
    });

    //itemHeight=$("#recipe-navigation li").height();
    //$("#recipe-navigation ul").css({height:numVisible*itemHeight,overflow:"hidden"});

    /* FORM UI
    *****************************************************/
    $('input[type=checkbox]').checkBox();
    // $('.resizable textarea').resizable({ handles: "s", minHeight: 50 });
    // $('.autosize').autogrow();

    $(".tabbed").tabs(); // { cookie: { expires: 1 }});
    $recipe_details = $("#recipe-details").tabs(
    {
        cookie: { expires: 1 }
    });

    RenumberPreparationSteps();
    ROGERS.utils.Forms.Cloneable.ReindexList($("#recipe-preparation-steps"));
    ROGERS.utils.Forms.Cloneable.ReindexList($("#recipe-ingredients-input"));

    /* CLONABLE FORM LIST ITEMS
    *****************************************************/
    $(".cloneable").cloneable();

    //    $("#recipe-preparation-steps").sortable({
    //        containment: "parent",
    //        opacity: 0.5,
    //        update: function(e, ui) {
    //            RenumberPreparationSteps();
    //            ROGERS.utils.Forms.Cloneable.ReindexList($(this));
    //        }
    //    });

    function BindRecipeBoxForms() {
        $("form.recipe-box-async").unbind('submit');
        $("form.recipe-box-async").submit(function() {
            var id = $(this).find("input[name='id']").val();
            var action = $(this).attr("action");
            $(this).parent().load(action, { "id": id }, BindRecipeBoxForms);
            $(this).fadeOut(function() { $(this).remove() });
            //$.post(action, , RecipeBoxCallback, "html");
            return false;
        });
    }
    BindRecipeBoxForms();

    function BindGroceryListEmailForms() {
        $("form.grocerylist-email-async").unbind('submit');
        $("form.grocerylist-email-async").submit(function() {
            var id = $(this).find("input[name='id']").val();
            var action = $(this).attr("action");
            $(this).parent().load(action, { "id": id }, BindRecipeBoxForms);
            $(this).fadeOut(function() { $(this).remove() });
            //$.post(action, , RecipeBoxCallback, "html");
            return false;
        });
    }
    BindGroceryListEmailForms();

    $(".recipe-box-delete-async").submit(function() {
        return window.confirm("Click OK to delete; this cannot be undone!");
    });

    function BindGroceryListItemRemove() {
        $("form.grocerylist-item-remove-async").submit(function() {
            ROGERS.log("Removing item...");
            var itemID = $(this).find("input[name='itemID']").val();
            var listID = $(this).find("input[name='listID']").val();
            var action = $(this).attr("action");
            //$(this).parent().load(action, { "itemID": itemID, "listID" : listID });
            $.post(action, { "itemID": itemID, "listID": listID });
            $(this).closest("li").fadeOut(function() { $(this).remove() });
            //$.post(action, , RecipeBoxCallback, "html");
            return false;
        });
    }
    BindGroceryListItemRemove();

    function BindRecipeBoxPublishing() {
        $("form.recipe-box-share-async").unbind('submit');
        $("form.recipe-box-share-async").submit(function() {
            var id = $(this).find("input[name='id']").val();
            var action = $(this).attr("action");
            $(this).parent().load(action, { "id": id }, BindRecipeBoxPublishing);
            $(this).fadeOut(function() { $(this).remove() });
            return false;
        });
    }
    BindRecipeBoxPublishing();

    function BindGroceryListForms() {
        $("form.recipe-grocery-async").unbind('submit');
        $("form.recipe-grocery-async").submit(function() {
            var id = $(this).find("input[name='id']").val();
            var action = $(this).attr("action");
            $(this).parent().load(action, { "id": id }, BindGroceryListForms);
            $(this).fadeOut(function() { $(this).remove() });
            return false;
        });
    }
    BindGroceryListForms();

    $.postJSON = function(url, data, callback) {
        $.post(url, data, callback, "json");
    };

    //    $("#recipe-ingredients-input").sortable({
    //        containment: "parent",
    //        opacity: 0.5,
    //        update: function(e, ui) {
    //            ROGERS.utils.Forms.Cloneable.ReindexList($(this));
    //        }
    //    });

    //    $("#document-notes ul").sortable({
    //        containment: "parent",
    //        opacity: 0.5,
    //        update: function(e, ui) {
    //            ROGERS.utils.Forms.Cloneable.ReindexList($(this));
    //        }
    //    });

    $("#recipe-search-recent h4").click(function() {
        $("#recipe-search-recent ul").slideToggle("fast");
        $("#recipe-search-recent").toggleClass("close");
    });
    LoadRecentSearches();

    $("#recipe-search-type label").click(function() {
        var id = $(this).attr("for"); $(id).click();
        $("#recipe-search-type label").removeClass("selected");
        $("#recipe-search-type label[for='" + id + "']").addClass("selected");
    });

    // Javascript is supported, so we don't need the standard submit button
    $(".recipe-rating-submit").hide();

    $('.auto-submit-star').rating({
        callback: function(value, link) {
            ROGERS.log(value);
            var id = $(this).closest("form").find("input[name='id']").val();
            var action = $(this).closest("form").attr("action");
            $.post(action, { "id": id, "rating": value }, RatingCallback, "json");
        }
    });

    function RatingCallback(data) {
    }

    $("#tools-view-comments").click(function() {
        $recipe_details.tabs('select', 2); // switch to third tab
        $.scrollTo("#recipe-details", 800, { easing: 'swing' });
        return false;
    });

    /* Search Related
    ----------------------------------------------------*/
    var DEFAULT_SEARCH_TEXT = "Type an ingredient or recipe name";
    if ($("#q").val() == "") {
        $("#q").val(DEFAULT_SEARCH_TEXT);
    }
    $("#q").focus(function() {
        if ($(this).val() == DEFAULT_SEARCH_TEXT)
            $(this).val("").css("color", "black");
    });
    $("#q").blur(function() {
        if ($(this).val() == "")
            $(this).val(DEFAULT_SEARCH_TEXT);
    });

    /* Commenting
    ---------------------------------------------------*/
    $(".comment-reportabuse").submit(function() {
        var answer = window.confirm("Do you really want to flag this post as hate speech, spam, or abuse?");
        if (answer) {
            var id = $(this).closest("form").find("input[name='id']").val();
            var action = $(this).closest("form").attr("action");
            $.post(action, { "id": id }, ReportCallback, "json");
            //$(this).load(action, { "id": id });
        }
        return false;
    });

    function ReportCallback(data) {
        alert(data);
    }

    /* Login Dialogs
    ----------------------------------------------------*/
    $("#recipes-login").dialog({
        autoOpen: false,
        modal: true,
        title: "LOGIN",
        width: 375
    });

    $(".recipes-auth").click(function() {
        var target = $(this).attr("href");
        if (target != "") {
            var pos = target.indexOf("&target");
            var pos2 = target.indexOf("&", pos + 1);
            if (pos > -1) {
                target = target.substring(pos + 8, pos2);
                $("#recipes-login").find("input[name='target']").val(target);
            }
        }
        $("#recipes-login").dialog('open');

        return false;
    });

    $("#recipe-search-form").submit(function() {
        var q = $("#q").val();
        if (q != "" && q != DEFAULT_SEARCH_TEXT) {
            return true;
        } else {
            $("#q").val(DEFAULT_SEARCH_TEXT).css("color", "red");
            return false;
        }
    });

    /* Fit to content textareas
    *****************************************************/
    $(".autosize textarea").each(function() {
        FitToContent(this, 300);
    });

    $(".autosize textarea").keyup(function() {
        FitToContent(this, 300)
    });


});


/* Event Handlers
*****************************************************/
function Focused() {
    $(this).parents("li").addClass("focused");
    $(this).children(":input").focus();
    $(this).parents("li").children(".instruct").show();
}

function Blurred() {
    $(this).parents("li").removeClass("focused");
    $(this).parents("li").children(".instruct").hide();
}

/* Helpers
*****************************************************/
var RECENT_SEARCH_STRINGS_COOKIE = "recent_search_strings";
var RECENT_SEARCH_URLS_COOKIE = "recent_search_urls";
var RECENT_SEARCHES_DELIM = "|";

function LoadRecentSearches()
{
  var searchStringsCookie = $.cookie(RECENT_SEARCH_STRINGS_COOKIE);
  var searchUrlsCookie = $.cookie(RECENT_SEARCH_URLS_COOKIE);
  if(searchStringsCookie != null)
  {
    $("#recipe-search-recent").show();
    var searchStrings = searchStringsCookie.split(RECENT_SEARCHES_DELIM);
    var searchUrls = searchUrlsCookie.split(RECENT_SEARCHES_DELIM);
    ROGERS.log(searchUrls);
    $("#recipe-search-recent").append("<ul></ul>");
    for(var i=1; i<searchStrings.length; i++)
    {
      var link = ["<li><a href='/Recipes/Search?",searchUrls[i],"'>",searchStrings[i],"</a></li>"].join('');
      $("#recipe-search-recent ul").append(link);
    }
  }
  
} 


// renumber the display
function RenumberPreparationSteps() {
    var step = 1;
    $("#recipe-preparation-steps li label strong").each(function() {
        $(this).text(step++);
    });
}

/* Event Binding Helpers
*****************************************************/
function Forms_BindInputHighlighting() {
    $("form li :input").focus(Focused);
    $("form li").hover(
        function() {
            $(this).children(".instruct").show();
        },
        function() {
            if ($(this).attr("class").indexOf("focused") == -1)
                $(this).children(".instruct").hide();
        });
    $("form li :input").blur(Blurred);
}

/* Textarea Resizing
*****************************************************/
var FIT_TO_CONTENT_BUFFER = 25;

function FitToContent(id, maxHeight)
{
   var text = id && id.style ? id : document.getElementById(id);
   if ( !text )
      return;

   var adjustedHeight = text.clientHeight;
   if ( !maxHeight || maxHeight > adjustedHeight )
   {
      adjustedHeight = Math.max(text.scrollHeight, adjustedHeight);
      if ( maxHeight )
         adjustedHeight = Math.min(maxHeight, adjustedHeight);
      if ( adjustedHeight > text.clientHeight )
      {
        //$(text).animate({height: (adjustedHeight + FIT_TO_CONTENT_BUFFER) + "px"}, 50);
         text.style.height = (adjustedHeight + FIT_TO_CONTENT_BUFFER) + "px";
      }
   }
}



/* Clonable Form Lists
*****************************************************/
ROGERS.utils.Forms = ROGERS.tools.Forms || {};
ROGERS.utils.Forms.Cloneable = ROGERS.utils.Forms.Cloneable || {};
ROGERS.utils.Forms.Cloneable.CONTROLS_CSS_CLASS = "cloneable-controls";
ROGERS.utils.Forms.Cloneable.options = {
    "keep_one": true
}
ROGERS.utils.Forms.Cloneable.controls = "<a class='delete' title='Delete'>X</a> <a class='add'>+</a>";
ROGERS.utils.Forms.Cloneable.confirm = "<span>Are you sure? <a class='yes'>yes</a> / <a class='no'>no</a><span>";

$.fn.cloneable = function() {
    return this.each(function() {
        ROGERS.utils.Forms.Cloneable.Init(this);
    });
};

// Initialize a cloneable item
ROGERS.utils.Forms.Cloneable.Init = function(o) {
    $(o).append(["<div class='", ROGERS.utils.Forms.Cloneable.CONTROLS_CSS_CLASS, "'>",
                 ROGERS.utils.Forms.Cloneable.controls, "</div>"].join(''));
    ROGERS.utils.Forms.Cloneable.BindInit(o);
};

ROGERS.utils.Forms.Cloneable.BindInit = function(o) {
    ROGERS.utils.Forms.Cloneable.BindDelete(o);
    ROGERS.utils.Forms.Cloneable.BindAdd(o);
};

ROGERS.utils.Forms.Cloneable.BindConfirm = function(o) {

    $yes = $(o).find(".yes");
    $yes.unbind();
    $yes.click(function() {
        $(this).closest("li").hide("scale", {}, "slow", function() {
            $(this).remove();
            RenumberPreparationSteps();
        });
    });

    $no = $(o).find(".no");
    $no.unbind();
    $no.click(function() {
        $(this).parent().html(ROGERS.utils.Forms.Cloneable.controls);
        ROGERS.utils.Forms.Cloneable.BindInit(o);
    });
};

ROGERS.utils.Forms.Cloneable.BindDelete = function(o) {
    $delete = $(o).find(".delete");
    $delete.unbind();
    $delete.click(function() {
        $(this).closest("div").html(ROGERS.utils.Forms.Cloneable.confirm);
        ROGERS.utils.Forms.Cloneable.BindConfirm(o);
    });
};

ROGERS.utils.Forms.Cloneable.BindAdd = function(o) {
    $add = $(o).find(".add");
    $add.unbind();
    $add.click(function() {
        var count = $(this).closest("li").siblings().length + 1;
        ROGERS.log("add", count);
        var $clone = $(this).closest("li").clone();
        $(this).closest("li").after($clone);
        $clone.find(":input").each(function() { $(this).attr("value", ""); });
        $clone.find("textarea").each(function() { $(this).html(""); });

        ROGERS.utils.Forms.Cloneable.ReindexList($(this).closest("ul"));
        RenumberPreparationSteps();
        ROGERS.utils.Forms.Cloneable.BindInit($clone);
    });
};

// Updates the index number used in lists of form controls.
// e.g. <input type="text" name="Samples[INDEX].Name"/>
ROGERS.utils.Forms.Cloneable.Reindex = function(html, count) {
    html = html.replace(/\[\d*\]/g, "[" + count + "]");
    return html;
};

// Updates the index number used in lists of form controls.
// e.g. <input type="text" name="Samples[INDEX].Name"/>
ROGERS.utils.Forms.Cloneable.ReindexList = function($list) {
    var count = 0;
    $list.find("li").each(function() {
        var $li = $(this);
        var html = $li.html();
        //$li.html(ROGERS.utils.Forms.Cloneable.Reindex(html, count));
        $li.find(":hidden[name$=.Index]").attr("value", count);
        $li.find(":input").each(function() {
            var id = $(this).attr("id");
            var name = $(this).attr("name");
            if (id.match(/\[\d*\]/g)) {
                id = id.replace(/\[\d*\]/g, "[" + count + "]");
                name = name.replace(/\[\d*\]/g, "[" + count + "]");
                $(this).attr("id", id);
                $(this).attr("name", name);
            }
        });

        ROGERS.utils.Forms.Cloneable.BindInit($li);
        count++;
    });
};

/* Logging
*****************************************************/
ROGERS.log = function() {
    if (ROGERS.debug && window.console)
        console.debug.apply(console, arguments);
};