﻿if (typeof (GMI.Calendar) == 'undefined') {
    GMI.Calendar = {};
}

if (typeof (GMI.Calendar.Notes) == 'undefined') {
    GMI.Calendar.Notes = {};
}

if (typeof (GMI.Calendar.RecipeSearch) == 'undefined') {
    GMI.Calendar.RecipeSearch = { };
}

if (typeof (GMI.Calendar.RecipeSearch.Data) == 'undefined') {
    GMI.Calendar.RecipeSearch.Data = { UserKey: "",
                                        MealTypeId: 0,
                                        SearchText: "",
                                        CurrentPage: 0                                        
                                     };
}

if (typeof(GMI.Calendar.RecipeBox) == 'undefined') {
    GMI.Calendar.RecipeBox = {};
}

// Recipe actions on calendar
GMI.Calendar.MaximizeRecipe = function(evt) {
    evt.preventDefault();
    $(this).parent().removeClass('min-recipe');
}

GMI.Calendar.MinimizeRecipe = function(evt) {
    evt.preventDefault();
    $(this).parent().addClass('min-recipe');
}

GMI.Calendar.RemoveRecipe = function(evt) {
    evt.preventDefault();
    $(this).unbind('click', GMI.Calendar.RemoveRecipe); // Don't let the same request be sent again
    var parentRecipe = $(this).closest('div.recipe');
    var parentCell = parentRecipe.closest('td');
    parentRecipe.hide(); // This is so there's some instant gratification for the user
    data = GMI.Calendar.GetContainerData(parentRecipe);

    // RemoveFromCalendar returns true or false based on whether request was successful
    GMI.SendXHRToWCF('RemoveFromCalendar',
                    { userKey: data.UserKey, recipeId: data.ItemId, mealTypeId: data.MealId, planDate: data.CellDate },
                    // Success function
                    function(data) {
                        parentRecipe.remove();
                        if (parentCell.find('.recipe, .notes').length < 1) {
                            parentCell.closest('td').removeClass('occupied');
                        }
                    },
                    // Error function
                    function() {
                        parentRecipe.show();
                        ModalAlert('There was an error submitting your request. Please "reload" the page to try again.');
                    }
    );
}

GMI.Calendar.PerformPrint = function(evt) {
    evt.preventDefault();
    // Check if meal plan is to be printed    
    var printMealPlan = $('.dialog-content input[name=mealPlan]:checked').length;
    var printRecipes = $('.dialog-content input[name=recipesInPlan]:checked').length;

    var type = $(this).attr('id').split('-')[2];

    var dateString;
    if (type == 'week') {
        dateString = $('th:nth-child(2)').attr('id');
    } else {
        dateString = $('th:last').attr('id');
    }

    // Reset the checkbox values for the future
    $('#print-dialog input#mealPlan').attr('checked', '');

    // tracking code - make webtrends calls to track printing
    if (printMealPlan) {
        if (type == 'week')
            trackAction(GMI.BAH.Tracking.PrintPlanWeek);
        else
            trackAction(GMI.BAH.Tracking.PrintPlanDay);
    }
    if (printRecipes) {
        if (type == 'week')
            trackAction(GMI.BAH.Tracking.PrintPlanWeekRecipes);
        else
            trackAction(GMI.BAH.Tracking.PrintPlanDayRecipes);
    }

    window.open('/myplan/' + type + '.aspx?' + type + '=' + dateString.replace('/-/g', '/') + '&print=1&plan=' + printMealPlan + '&recipes=' + printRecipes + '&type=' + type);
    $('.dialog-overlay').click();
} 

GMI.Calendar.ClosePrintView = function(evt) {
    $('link[media=fake]').attr('media', 'screen');
    $('link[media!=screen]').attr('media', 'print');
}

   
GMI.Calendar.PrintPlanWeek = function(evt) {
    evt.preventDefault();
    //GMI.OpenModalDialog("#print-dialog-week", 350, "What would you like to print?", 'printDialog', 200, 'fixed');
    $("#print-dialog-week").ModalDialog({'width': 350, 'title': 'What would you like to print?', id: 'printDialog'});
}

GMI.Calendar.PrintPlanDay = function(evt) {
    evt.preventDefault();
    //GMI.OpenModalDialog("#print-dialog-day", 350, "What would you like to print?", 'printDialog', 200, 'fixed');
    $('#print-dialog-day').ModalDialog({ 'width': 350, 'title': 'What would you like to print?', id: 'printDialog' });
}

///////////////////////////
// Logic for drag and drop
///////////////////////////

// Holds the original parent of the item currently being dragged
GMI.Calendar.OriginalContainer;

// Keeps track of whether we're going to destroy the draggable or not once dropped
GMI.Calendar.destroyDraggable = false;

GMI.Calendar.draggableDropped;

GMI.Calendar.UpdateFolderTotal = function(folder, amount) {
    var folderCountRegex = new RegExp(/\([0-9]{1,6}\)/);
    var folderText = folder.find('h4').text();
    var folderCount = folderCountRegex.exec(folderText)[0].replace('(', '').replace(')', '');
    folder.find('h4').text(folderText.replace(folderCountRegex, '(' + (Number(folderCount) + amount) + ')'));
}

// The options that will be attached to all draggable objects
GMI.Calendar.DraggableOptions = {
    appendTo: '#content',
    cancel: 'a', // Prevents dragging when clicking on certain elements
    cursor: 'move',
    cursorAt: {left: 80, top: 15},
    delay: 0,
    distance: 5,
    containment: false,
    refreshPositions: true,
    revert: 'invalid',
    revertDuration: 100,
    helper: 'clone',
    zindex: 1000000,
    start: function(evt, ui) { // Event order: draggable.start, droppable.drop, draggable.stop
        GMI.Calendar.draggableDropped = false;
        GMI.Calendar.OriginalContainer = $(this).parent();
        if (GMI.Calendar.OriginalContainer.find('.recipe, .notes').length <= 1) {
            GMI.Calendar.OriginalContainer.removeClass('occupied');
        }
        if (!GMI.Calendar.OriginalContainer.hasClass('rec-folder')) {
            $(this).hide();
        }
    },
    stop: function(evt, ui) {
        if (GMI.Calendar.destroyDraggable) {
            $(this).remove();
            GMI.Calendar.OriginalContainer.each(GMI.Calendar.RecipeBox.SetupPaging); // Nothing should happen if OriginalContainer isn't a .rec-folder
        } else {
            if (!GMI.Calendar.OriginalContainer.hasClass('collapsed')) {
                $(this).show();
                $(this).parent().addClass('occupied');
            }
        }
        GMI.Calendar.destroyDraggable = false;
    }
}

GMI.Calendar.DroppableOptions = {
    accept: '.recipe, .notes',
    hoverClass: 'current',
    refreshPositions: true,
    greedy: true,
    tolerance: 'pointer',

    // A recipe has been dropped
    // $(this) = the droppable jQuery object
    // ui.draggable = the object being dragged onto this one
    drop: function(evt, ui) {
        var $this = $(this);
        // So it can't be dropped in two cells
        if (GMI.Calendar.draggableDropped) return;
        GMI.Calendar.draggableDropped = true;

        ui.helper.remove(); // Don't want to keep the helper since it's positioned absolutely and will look funny

        // Where did this come from and where did it end up?
        var toRecipeBox = $this.hasClass('rec-folder');
        var fromRecipeBox = GMI.Calendar.OriginalContainer.hasClass('rec-folder');

        // Recipe data for original container and new container
        var originalData = GMI.Calendar.GetContainerData(ui.draggable);
        var newData = GMI.Calendar.GetContainerData($this);
        newData.ItemId = originalData.ItemId; // assigns this the actual recipe ID since GetContainerData expects the recipe object and not the container; this line could be removed with no negative consequences

        // Check if this is a note
        if (ui.draggable.hasClass('notes')) {
            GMI.Calendar.Notes.Dropped(ui.draggable, originalData, newData, $this);
            return;
        }

        // Clone the recipe (only clones HTML element)
        var clonedRecipe = ui.draggable.clone().draggable(GMI.Calendar.DraggableOptions).show();

        // Recipe was dropped where it started -- don't do anything
        if (GMI.Calendar.OriginalContainer.attr('id') == $this.attr('id')) {
            return;
        }

        // This enforces the 4 recipe max rule
        if ($this.find('.recipe, .notes').length > 3 && !toRecipeBox) {
            // Put this back in its original container if it existed on the screen
            if (GMI.Calendar.OriginalContainer.closest('td').length > 0) {
                GMI.Calendar.OriginalContainer.prepend(clonedRecipe);
            }
            ModalAlert("Each cell can contain a maximum of 4 items.");
            return;
        }

        // If this recipe already exists in this container then stop
        if ($this.find('.recipe[id=' + clonedRecipe.attr('id') + ']').length) {
            if (toRecipeBox) ModalAlert("You have already added this recipe to this folder.");
            else ModalAlert("You have already added this recipe to this meal. If you would like, you may update the recipe quantity by clicking on the 'Options' menu and selecting, 'Recipe Quantity'.");
            return;
        }

        if (!toRecipeBox) {
            $this.addClass('occupied');
            $this.prepend(clonedRecipe);
        } else {
            clonedRecipe.insertAfter($this.find('h4'));
        }

        // Remove the recipe from its original container unless it came from the recipe box
        if (fromRecipeBox == toRecipeBox) {
            GMI.Calendar.destroyDraggable = true;
        }

        // This handles adding a new recipe from the recipe box to the calendar
        if (fromRecipeBox && !toRecipeBox) {
            GMI.SendXHRToWCF('MoveRecipeFromRecipeBoxToCalendar',
                            { userKey: originalData.UserKey, recipeId: originalData.ItemId, recipeBoxCategoryId: originalData.FolderId, mealtypeId: newData.MealId, planDate: newData.CellDate },
                            function(data) {
                                // ModalAlert(data.d);
                            },
                            function() {
                                ModalAlert("There was an error processesing your request.  Please try to 'reload' the page and try again.");
                            }
            );

            return; // We're done 
        }

        // This handles moving a recipe from cell to cell on the calendar
        if (!fromRecipeBox && !toRecipeBox) {
            GMI.SendXHRToWCF('MoveRecipe',
                            { userKey: originalData.UserKey, recipeId: originalData.ItemId, originalMealTypeId: originalData.MealId, newMealtypeId: newData.MealId, originalPlanDate: originalData.CellDate, newPlanDate: newData.CellDate },
                            function(data) {
                                if (typeof (data.d) == 'undefined') {
                                    ModalAlert('major error');
                                }
                            },
                            function() {
                                ModalAlert("There was an error submitting your request. Please refresh the page to try again.");
                            }
            );
            return;
        }

        // Moving a recipe from folder to folder in the recipe box
        if (fromRecipeBox && toRecipeBox) {
            // Update recipe folder totals
            GMI.Calendar.UpdateFolderTotal(GMI.Calendar.OriginalContainer, -1);
            GMI.Calendar.UpdateFolderTotal($this, 1);

            GMI.SendXHRToWCF('MoveRecipeAcrossRecipeBoxCategories',
                            { userKey: originalData.UserKey, recipeId: originalData.ItemId, sourceRecipeBoxCategoryId: originalData.FolderId, destinationRecipeBoxCategoryId: newData.FolderId },
                            function(data) {
                                if (typeof (data.d) == 'undefined') {
                                    ModalAlert('major error');
                                }
                            },
                            function(XHR, status, errorThrown) {
                                alert(XHR.responseText);
                            }
            );
            return;
        }

        // Moved from calendar to recipe box
        if (!fromRecipeBox && toRecipeBox) {
            GMI.Calendar.UpdateFolderTotal($this, 1);
            GMI.Calendar.SaveRecipeToRecipeBoxSendXHR(originalData.ItemId, newData.FolderId);
        }

        // Need to figure out paging again
        if (toRecipeBox) {
            $this.each(GMI.Calendar.RecipeBox.SetupPaging);
        }

    },
    over: function(evt, ui) {
        // The pause for if a calendar cell is minimized
        if ($(this).hasClass('min')) {
            // The animate is added just for a delay
            $(this).animate({ g: 1 }, 500).queue(function() {
                GMI.Calendar.ExpandCollapseRelatedColumn($(this).attr('class'));
                $(this).dequeue();
            });
        }
        // Pause if recipe box folder is collapsed
        if ($(this).hasClass('collapsed')) {
            $(this).animate({ g: 1 }, 200).queue(function() {
                $(this).find('h4').click();
                $(this).dequeue();
            });
        }
    },
    out: function(evt, ui) {
        // Setting the queue to an empty array of functions (cancelling our events)
        $(this).queue([]);
    }
}

//functions for adding/editing/deleting notes
GMI.Calendar.Notes.Add = function() {
    //remove class from all cells so that contents of cell show
    $('td.note-edit').removeClass('note-edit');

    //add class to current cell to hide contents
    GMI.Calendar.CellContextRelatedCell.addClass('note-edit');

    //new note ID = 0
    GMI.Calendar.Notes.CurrentNoteID = 0;

    //show the note editing area in the selected cell
    $('div.notes-edit-placeholder textarea.notes-edit-box').attr('value', 'add a personal note');
    $('div.notes-edit-placeholder').appendTo(GMI.Calendar.CellContextRelatedCell);
    $('div.notes-edit-placeholder').show();

    //clear default text on focus
    $('div.notes-edit-placeholder textarea.notes-edit-box').focus(GMI.Calendar.Notes.Clear);

    return false;
}

GMI.Calendar.Notes.Dropped = function(note, originalData, newData, newContainer) {
    var clonedNote = note.clone().draggable(GMI.Calendar.DraggableOptions).show();

    // This enforces the 4 recipe/note max rule
    if ($(this).find('.recipe, .notes').length > 3 && !toRecipeBox) {
        // Put this back in its original container if it existed on the screen
        if (GMI.Calendar.OriginalContainer.closest('td').length > 0) {
            GMI.Calendar.OriginalContainer.prepend(clonedRecipe);
        }
        ModalAlert("Each cell can contain a maximum of 4 items.");
        return;
    }

    clonedNote.insertBefore(newContainer.find('div.context-buttons'));

    newContainer.addClass('occupied');

    GMI.Calendar.destroyDraggable = true;
    GMI.Calendar.draggableDropped = true;

    // MoveNote(ByVal userKey As String, ByVal noteID As String, ByVal notes As String, ByVal originalMealTypeId As Integer, ByVal newMealtypeId As Integer, ByVal originalPlanDate As String, ByVal newPlanDate As String) As Boolean
    GMI.SendXHRToWCF('MoveNote',
                    { userKey: newData.UserKey, noteID: newData.ItemId, newMealtypeId: newData.MealId, newPlanDate: newData.CellDate },
                    // Success function
                    function(data) {

                    },
                    // Error function
                    function() {
                        ModalAlert('There was an error submitting your request. Please "reload" the page to try again.');
                    }
        );
}

GMI.Calendar.Notes.Edit = function() {
    //remove class from all cells so that contents of cell show
    $('td.note-edit').removeClass('note-edit');

    //add class to current cell to hide contents
    GMI.Calendar.CellContextRelatedCell = $(this).closest('td');
    GMI.Calendar.CellContextRelatedCell.addClass('note-edit');

    //set current note ID that is being edited
    GMI.Calendar.Notes.CurrentNoteID = $(this).closest('div.notes').attr('id');

    //get current text for editing
    var noteText = $(this).closest('div.notes').find('h5').html();

    //show the note editing area in the selected cell
    $('div.notes-edit-placeholder textarea.notes-edit-box').attr('value', noteText);
    $('div.notes-edit-placeholder').appendTo(GMI.Calendar.CellContextRelatedCell);
    $('div.notes-edit-placeholder').show();

    $('div.notes-edit-placeholder textarea.notes-edit-box').unbind('focus', GMI.Calendar.Notes.Clear); //don't clear text on edit

    return false;
}

GMI.Calendar.Notes.Clear = function() {
    $('div.notes-edit-placeholder textarea.notes-edit-box').attr('value', '');
}

GMI.Calendar.Notes.ClearEdit = function() {
    //remove class from all cells so that contents of cell show
    $('td.note-edit').removeClass('note-edit');

    //move notes edit div out of calendar cell and hide it
    $('div.notes-edit-placeholder').hide();
    $('div.notes-edit-placeholder').appendTo('body');
}

GMI.Calendar.Notes.Cancel = function() {
    GMI.Calendar.Notes.ClearEdit();
    return false;
}

GMI.Calendar.Notes.Save = function() {
    var notesText = $('div.notes-edit-placeholder textarea.notes-edit-box').val();

    var parentContainer = $(this).closest('div.notes-edit-placeholder');
    data = GMI.Calendar.GetContainerData(parentContainer);
    var parentCell = parentContainer.closest('td')

    if (GMI.Calendar.Notes.CurrentNoteID > 0) {
        //replace the notes text with the new edit
        parentCell.find('div#' + GMI.Calendar.Notes.CurrentNoteID + ' h5').html(notesText);
        //save note edit
        GMI.SendXHRToWCF('EditNoteFromCalendar',
                    { userKey: data.UserKey, notesId: GMI.Calendar.Notes.CurrentNoteID, mealTypeId: data.MealId, planDate: data.CellDate, notesText: notesText },
                             function() { },
                            function() { ModalAlert("failed"); });
    }
    else {
        //add the new note
        GMI.SendXHRToWCF('AddNotesToCalendar',
                    { userKey: data.UserKey, mealTypeId: data.MealId, planDate: data.CellDate, notesText: notesText },
                     function(data) {
                         parentCell.find('div.context-buttons').before(data.d);
                         parentCell.addClass('occupied');
                         parentCell.find('.notes').draggable(GMI.Calendar.DraggableOptions);
                     },
                    function() { ModalAlert("failed"); });
    }

    GMI.Calendar.Notes.ClearEdit();
    return false;
}

GMI.Calendar.Notes.Delete = function(evt) {
    evt.preventDefault();
    $(this).unbind('click', GMI.Calendar.Notes.Delete); // Don't let the same request be sent again
    var notesContainer = $(this).closest('div.notes');
    var parentCell = notesContainer.closest('td');
    notesContainer.hide(); // This is so there's some instant gratification for the user
    data = GMI.Calendar.GetContainerData(notesContainer);

    // RemoveFromCalendar returns true or false based on whether request was successful
    GMI.SendXHRToWCF('RemoveNoteFromCalendar',
                    { userKey: data.UserKey, noteId: data.ItemId, mealTypeId: data.MealId, planDate: data.CellDate },
                    // Success function
                    function(data) {
                        notesContainer.remove();
                        if (parentCell.find('.recipe, .notes').length < 1) {
                            parentCell.closest('td').removeClass('occupied');
                        }
                    },
                    // Error function
                    function() {
                        notesContainer.show();
                        ModalAlert('There was an error submitting your request. Please "reload" the page to try again.');
                    }
        );
}

//functions for popup recipe search
GMI.Calendar.RecipeSearch.Start = function() {
    //remove class from all cells so that contents of cell show
    $('td.note-edit').removeClass('note-edit');

    //add class to current cell to hide contents
    GMI.Calendar.CellContextRelatedCell.addClass('note-edit');

    //show the search box in the selected cell
    $('div.search-placeholder .search-text').attr('value', 'enter recipe search term');
    $('div.search-placeholder').appendTo(GMI.Calendar.CellContextRelatedCell);
    $('div.search-placeholder').show();
    
}

GMI.Calendar.RecipeSearch.ClearText = function() {
    $('div.search-placeholder .search-text').attr('value', '');
}


GMI.Calendar.RecipeSearch.Clear = function() {
    //move search box out of calendar cell and hide it
    $('div.search-placeholder').hide();
    $('div.search-placeholder').appendTo('body');

    //remove class from all cells so that contents of cell show
    $('td.note-edit').removeClass('note-edit');
}

GMI.Calendar.RecipeSearch.Cancel = function(evt) {
    evt.preventDefault();
    GMI.Calendar.RecipeSearch.Clear();
}

GMI.Calendar.RecipeSearch.Submit = function(evt) {
    evt.preventDefault();

    GMI.Calendar.RecipeSearch.Data.UserKey = GMI.Calendar.UserKey; // user key
    GMI.Calendar.RecipeSearch.Data.MealTypeId = $('div.search-placeholder').closest('tr').attr('class');
    GMI.Calendar.RecipeSearch.Data.SearchText = $('div.search-placeholder .search-text').val();
    GMI.Calendar.RecipeSearch.Data.CurrentPage = 1;

    //hide search edit box in cell
    GMI.Calendar.RecipeSearch.Clear();

    //show search results dialog
    if (GMI.Calendar.RecipeSearch.Data.SearchText.trim().length > 0) {
        $('#search-results-dialog').ModalDialog({ width: 542, title: '', id: 'search-results', template: '<a href="#" id="close-dialog"></a>' });
        GMI.Calendar.RecipeSearch.Run();
    }
}

GMI.Calendar.RecipeSearch.Page = function(evt) {
    evt.preventDefault();
    //$('#search-results-dialog .content').html('<div class="waiting"></div>');
    GMI.Calendar.RecipeSearch.Data.CurrentPage = $(this).attr('rel');
    GMI.Calendar.RecipeSearch.Run();
}


GMI.Calendar.RecipeSearch.Run = function() {

    $('#search-results-dialog .waiting').show();
    $('#search-results-dialog .content').hide();

    GMI.SendXHRToWCF('SearchFromCalendar',
                    { userKey: GMI.Calendar.RecipeSearch.Data.UserKey,
                        mealTypeId: GMI.Calendar.RecipeSearch.Data.MealTypeId,
                        searchText: GMI.Calendar.RecipeSearch.Data.SearchText,
                        currentPage: GMI.Calendar.RecipeSearch.Data.CurrentPage
                    },
    // Success function
                    function(data) {
                        //display the search results
                    $('#search-results-dialog .content').html(data.d);
                    $('#search-results-dialog .waiting').hide();
                    $('#search-results-dialog .content').show();
                    //get recipe images
                    $('#search-results-dialog img.async').each(GMI.LoadImage);
                    
                    
                    },
    // Error function
                    function() {
                        ModalAlert('There was an error running the recipe search. Please "reload" the page to try again.');
                    }
            );
              
}

GMI.Calendar.RecipeSearch.AddToCalendar = function(evt) {
    evt.preventDefault();
    $('#search-results-dialog').ModalDialog.Close();

    GMI.Calendar.CellContextRelatedCell.find('div.context-buttons').before(GMI.Calendar.RecipeContextRelatedRecipe);
    GMI.Calendar.CellContextRelatedCell.addClass('occupied');

    //enable drag & drop
    GMI.Calendar.RecipeContextRelatedRecipe.draggable(GMI.Calendar.DraggableOptions)

    //save
    var data = GMI.Calendar.GetContainerData(GMI.Calendar.RecipeContextRelatedRecipe);

    GMI.SendXHRToWCF('AddToCalendar',
                    { userKey: data.UserKey, recipeId: data.ItemId, mealTypeId: data.MealId, planDate: data.CellDate },
                    function(data) {
                        // ModalAlert(data.d);
                    },
                    function() {
                        ModalAlert("There was an error processesing your request.  Please try to 'reload' the page and try again.");
                    }
    );
    return false;
}

GMI.Calendar.ToggleRecipeFolderVisibility = function() {
    var folderContainer = $(this).parent();
    if (folderContainer.hasClass('collapsed')) {
        folderContainer.removeClass('collapsed');
        folderContainer.find('.recipe').show();
        if (folderContainer.find('.recipe').length > 5) folderContainer.find('.recipe-pager').show();
        $('#' + folderContainer.attr('id')).trigger('refresh.evtpaginate');
        $('#recipe-box').height($('#recipe-box').height() + 1);
    } else {
        if (folderContainer.find('.recipe').length) {
            folderContainer.find('.recipe').hide();
        }
        folderContainer.find('.recipe-pager').hide();
        folderContainer.addClass('collapsed');
    }
}

GMI.Calendar.BindRecipeBoxFolderActions = function(recipeBoxFolder) {
    recipeBoxFolder.find('h4').click(GMI.Calendar.ToggleRecipeFolderVisibility);
    var thisFolderId = recipeBoxFolder.attr('id');
    if (thisFolderId != 'user-published-folder' && thisFolderId != 'user-drafts-folder')
        recipeBoxFolder.droppable(GMI.Calendar.DroppableOptions);
}

GMI.Calendar.OpenAddNewFolderToRecipeBox = function() {
    //check for max of 10 folders - there are 2 auto created folders for user recipes so 12 folders total
    if ($('#recipe-box .rec-folder').length > 11) {
        ModalAlert('You have created your last available folder. You can always edit and rearrange your folders on your My Recipe Box page.', 'Unable to create folder');
        return false;
    }

    $(this).hide(); // Hide the add folder button

    $('#recipe-box #create-new-folder').show(); // Show the controls to enter a folder name
    
    // If this is the last folder, show the message that user is creating last folder
    if ($('#recipe-box .rec-folder').length > 10) {
        $('#recipe-box #recipe-box-actions p').show();
    }
    return false;
}

GMI.Calendar.CancelAddNewFolderToRecipeBox = function() {
    $(this).parent().hide();
    $('#new-folder-button').show();
    $('input#new-folder-name').val('');
    $('#recipe-box #recipe-box-actions p').hide();
    return false;
}

// User has clicked the save button when adding a new folder
GMI.Calendar.AddNewFolderToRecipeBox = function() {
    $(this).parent().hide();
    $('#new-folder-button').show();

    var folderName = $('#new-folder-name').val();

    if (!GMI.ValidRecipeBoxFolder(folderName, '#recipe-box .rec-folder h4'))  //function in common.js
        return false;

    // Make WCF call that creates a new recipe box folder and returns the new ID
    // AddCategoryToRecipeBox(ByVal userKey As String, ByVal categoryName As String) As String
    GMI.SendXHRToWCF('AddCategoryToRecipeBox',
                     { userKey: GMI.Calendar.UserKey, categoryName: folderName },
                     function(data) {
                         var recipeCategoryId = data.d;
                         $('#recipe-box').remove();

                         GMI.SendXHRToWCF('LoadRecipeBox', null,
                            function(data) {
                                $('#calendar-container').css('overflow', 'hidden');
                                $('#calendar-container').prepend(data.d);
                                $('#recipe-box').hide().fadeIn(1500);
                                GMI.Calendar.InitializeRecipeBoxEvents();
                            },
                            GMI.StandardAJAXErrorFunction
                        );
                     },
                    function() {
                        // Error
                        ModalAlert("There was an error submitting your request. Please refresh the page to try again.");
                    }
            );
    return false;
}

// This holds the recipe the current context menu was opened for
GMI.Calendar.RecipeContextRelatedRecipe = null;

// Holds the current cell for cell context menu
GMI.Calendar.CellContextRelatedCell = null;

GMI.Calendar.OpenRecipeQuickView = function(evt) {
    var recipeId = GMI.Calendar.RecipeContextRelatedRecipe.attr('id');
    $('#recipe-quick-view-placeholder').ModalDialog({ width: 624, template: '<a href="#" id="close-dialog"></a>', id: 'QuickView', position: 'absolute', deferredDisplay: true });
    GMI.SendXHRToWCF('GetRecipeQuickView', { userKey: GMI.Calendar.UserKey, recipeId: recipeId },
        function(data) {
            $('#recipe-quick-view-placeholder').html(data.d);
            $('#recipe-quick-view-placeholder').ModalDialog.Show();
        },
        function() {
            // Error
            ModalAlert("There was an error submitting your request. Please refresh the page to try again.");
        }
    );
    $(this).parent().mouseout();
    return false;
}

GMI.Calendar.RemoveRecipeViaMenu = function(evt) {
    evt.preventDefault();
    GMI.Calendar.RecipeContextRelatedRecipe.find('a.remove-recipe').click();
    $(this).parent().mouseout();
}

GMI.Calendar.AddAsLeftOvers = function(evt) {
    evt.preventDefault();
    recipeData = GMI.Calendar.GetContainerData(GMI.Calendar.RecipeContextRelatedRecipe);
    var parsedDate = GMI.GetDateFromStandardStringFormat('-', recipeData.CellDate);

    // Reset the dialog to original state
    $('.leftover-day h6').attr('class', '');
    $('.leftover-day input[type=checkbox]').attr('checked', '');
    $('.leftover-day li').show();

    // Hide options for hidden meals
    var hiddenMeals = [];
    $('tr.meal-hidden').each(function(index) {
        hiddenMeals[index] = $(this).attr('class').replace(' meal-hidden', '');
    });

    for (var i = 0; i < hiddenMeals.length; i++) {
        $('.leftover-day input[id=' + hiddenMeals[i] + ']').parent().hide();
    }

    // populate each column header with a class of the date and the string header
    for (var i = 1; i <= 4; i++) {
        var thisDate = GMI.AddDaysToDate(i, parsedDate);
        var dateAsString = GMI.GetDateStringFromDate(thisDate);
        $('.leftover-day h6#position-' + i).addClass(dateAsString);
        $('.leftover-day h6#position-' + i).html(GMI.Calendar.DayArray[thisDate.getDay()] + ' ' + (thisDate.getMonth() + 1) + '/' + thisDate.getDate());
    }
    //GMI.OpenModalDialog('#leftovers-dialog', 650, "To which days would you like to add this recipe as leftovers?", 'LeftOvers', 300);
    $('#leftovers-dialog').ModalDialog({ width: 650, title: "To which days would you like to add this recipe as leftovers?", id: 'LeftOvers', height: 300 });
    $(this).parent().mouseout();
}

GMI.Calendar.SaveLeftOvers = function(evt) {
    evt.preventDefault();
    var leftoverContainer = $(this).closest('#leftovers-dialog');
    leftoverContainer.find('input[type=checkbox]:checked').each(function(index) {
        var clonedRecipe = GMI.Calendar.RecipeContextRelatedRecipe.clone().draggable(GMI.Calendar.DraggableOptions);
        //GMI.Calendar.BindRecipeEventsToRecipe(clonedRecipe); DELEGATE
        clonedRecipe.addClass('leftover');
        var columnHeader = $(this).closest('.leftover-day').find('h6');
        var cellDate = columnHeader.attr('class');
        var mealTypeId = $(this).attr('id');
        var dayAbbr = columnHeader.text().substr(0, 3).toLowerCase();
        if ($('th.' + dayAbbr).attr('id') == cellDate) {
            $('tr.' + mealTypeId + ' > td.' + dayAbbr).prepend(clonedRecipe).addClass('occupied');
        }
        GMI.SendXHRToWCF('AddRecipeAsLeftoverToCalendar', { userKey: GMI.Calendar.UserKey, recipeId: clonedRecipe.attr('id'), planDate: cellDate, mealTypeId: Number(mealTypeId) },
            function(data) {
            },
            function() {
                // Error
                ModalAlert("There was an error submitting your request. Please refresh the page to try again.");
            }
        );
    });
    $('#leftovers-dialog').ModalDialog.Close();
}

GMI.Calendar.GetQuantitySliderPosition = function(quantity) {
    return (quantity * 16 + 44) + 'px';
}

GMI.Calendar.UpdateRecipeQuantity = function(evt) {
    evt.preventDefault();
    var quantity = $(this).closest('#recipe-quantity-dialog').find('#current-value').text();
    GMI.Calendar.RecipeContextRelatedRecipe.find('.quantity').text(quantity + 'x');
    GMI.Calendar.RecipeContextRelatedRecipe.addClass('has-quantity');
    recipeData = GMI.Calendar.GetContainerData(GMI.Calendar.RecipeContextRelatedRecipe);
    $('.dialog-overlay').click();
    GMI.SendXHRToWCF('UpdateRecipeQuantity', { userKey: GMI.Calendar.UserKey, mealTypeId: recipeData.MealId, newQuantity: quantity, planDate: recipeData.CellDate, recipeId: recipeData.ItemId },
                     function(data) {

                     },
                    function() {
                        // Error
                        ModalAlert("There was an error submitting your request. Please refresh the page to try again.");
                    }
    );
}

GMI.Calendar.RecipeQuantity = function(evt) {
    evt.preventDefault();
    var currentQuantity = GMI.Calendar.RecipeContextRelatedRecipe.find('.quantity').text().replace('x', '');
    $('#current-value').html(currentQuantity);
    $('#current-value').css('left', GMI.Calendar.GetQuantitySliderPosition(currentQuantity));
    $('#quantity-slider').slider('option', 'value', currentQuantity);
    // GMI.OpenModalDialog('#recipe-quantity-dialog', 500, 'How many times would you like to make this recipe?');
    $('#recipe-quantity-dialog').ModalDialog({ width: 500, title: 'How many times would you like to make this recipe?' });
    $(this).parent().mouseout();
}

GMI.Calendar.PrintRecipe = function(evt) {
    evt.preventDefault();
    trackAction(GMI.BAH.Tracking.PrintPlanRecipe);
    window.open('/Recipes/RecipeView.aspx?recipeguid=' + GMI.Calendar.RecipeContextRelatedRecipe.attr('id') + '&print=true');
    $(this).parent().mouseout();
}

GMI.Calendar.SearchRecipes = function(evt) {
    evt.preventDefault();
    GMI.Calendar.RecipeSearch.Start();
    $(this).parent().mouseout();
    trackAction(GMI.BAH.Tracking.MyPlanSearchForRecipes);
}

GMI.Calendar.AddNote = function(evt) {
    evt.preventDefault();
    GMI.Calendar.Notes.Add();
    $(this).parent().mouseout();
    trackAction(GMI.BAH.Tracking.MyPlanAddNote);
}

GMI.Calendar.AddRecipe = function(evt) {
    evt.preventDefault();
    ModalAlert("add recipe");
}

GMI.Calendar.RecipeOptionsMenu = function(evt) {
    evt.preventDefault();
    GMI.Calendar.RecipeContextRelatedRecipe = $(this).closest('.recipe');
    var calendarPosition = $('#calendar-container').position();
    var recipePosition = GMI.Calendar.RecipeContextRelatedRecipe.position();
    var optionsPosition = $(this).position();
    var menuPosition = {};
    menuPosition.top = $(this).offset().top ;
    menuPosition.left = $(this).offset().left;
    $('body').append($('#recipe-context-menu-placeholder').html());
    var thisContextMenu = $('body > .recipe-context-menu');
    thisContextMenu.find('a').attr('rel', GMI.Calendar.RecipeContextRelatedRecipe.attr('id')); 
    thisContextMenu.css({ 'top': menuPosition.top, 'left': menuPosition.left }).show();
}

GMI.Calendar.CellContextMenu = function(evt) {
    evt.preventDefault();
    GMI.Calendar.CellContextRelatedCell = $(this).closest('td');
    var calendarPosition = $('#calendar-container').position();
    var buttonHolderPosition = $(this).closest('.context-buttons').position();
    var buttonPosition = $(this).position();
    var menuPosition = {};
    menuPosition.top = $(this).offset().top + 5;
    menuPosition.left = $(this).offset().left;
    $('body').append($('#cell-context-menu-placeholder').html());
    var thisContextMenu = $('body > .cell-context-menu');
    thisContextMenu.css({ 'top': menuPosition.top, 'left': menuPosition.left }).show();
}

GMI.Calendar.RecipeSearch.RecipeOptionsMenu = function(evt) {
    evt.preventDefault();
    GMI.Calendar.RecipeContextRelatedRecipe = $(this).closest('.recipe');

    var menuPosition = {};
    menuPosition.top = $(this).offset().top;
    menuPosition.left = $(this).offset().left;
    $('body').append($('#search-recipe-context-menu').html());
    var thisContextMenu = $('body > .recipe-context-menu');
    thisContextMenu.css({ 'top': menuPosition.top, 'left': menuPosition.left }).show();
    
    //hide context menu when click/select a menu item
    $('.recipe-context-menu a').click(function() { $(this).parent().mouseout(); });
}

GMI.Calendar.RateRecipeUp = function(evt) {
    if (!GMI.IsLoggedIn) {
        GMI.ShowLoginPrompt();
        return;
    }
    $(this).addClass('rated');
    thisRecipe = $(this).closest('div.recipe');
    $(this).closest('div.recipe').find('a.thumbs-down').removeClass('rated');
    GMI.SendXHRToWCF('LikeRecipe',
                            { userKey: GMI.Calendar.UserKey, recipeId: thisRecipe.attr('id') },
                            function() { },
                            function() { ModalAlert("failed"); }
    );
    trackAction(GMI.BAH.Tracking.RecipeThumbsUp);
}

GMI.Calendar.RateRecipeDown = function(evt) {
    if (!GMI.IsLoggedIn) {
        GMI.ShowLoginPrompt();
        return;
    }
    $(this).addClass('rated');
    thisRecipe = $(this).closest('div.recipe');
    $(this).closest('div.recipe').find('a.thumbs-up').removeClass('rated');
    GMI.SendXHRToWCF('DisLikeRecipe',
                            { userKey: GMI.Calendar.UserKey, recipeId: thisRecipe.attr('id') },
                            function() { },
                            function() { ModalAlert("failed"); }
    );
    trackAction(GMI.BAH.Tracking.RecipeThumbsDown);
}

GMI.Calendar.SearchRecipeBox = function() {
    // Grab the search text and validate it
    var searchText = $('input#RecipeName').val();
    if (searchText.length < 3) {
        ModalAlert("Please enter at least three characters to search for.");
        return;
    }

    // Make the XHR call and get the HTML of the recipes returned
    GMI.SendXHRToWCF('SearchFromRecipeBox',
                    { userKey: GMI.Calendar.UserKey, searchText: searchText },
                    function(data) {
                        // Remove any past search results
                        $('#recipe-folders #search-results').remove();

                        // Inject the recipes into the .recipe-folders container
                        $('#recipe-folders').prepend($('<div id="search-results" class="rec-folder"></div>'));
                        $('#search-results').html(data.d);
                        $('#search-results').each(GMI.Calendar.RecipeBox.SetupPaging);
                        $('#search-results .recipe').draggable(GMI.Calendar.DraggableOptions);
                    },
                    function() {
                        ModalAlert("failed");
                    }
    );

    return false;
}

GMI.Calendar.ShowHideRecipeBox = function() {
    if ($('#recipe-box #recipe-folders').css('display') == 'none') {
        $('#recipe-box #recipe-folders').show();
        $('#recipe-box').animate({ 'left': '0' }, 300, function() { // callback when animation is complete
            $('#recipe-box #handle').css('background', '#fff url(/images/bg/bg-recipe-box-handle.gif) no-repeat 0 0');
            $('#calendar-container').css('overflow', 'visible');
        });
    } else {
        $('#calendar-container').css('overflow', 'hidden');
        $('#recipe-box').animate({ 'left': '-210px' }, 300, function() { // callback when animation is complete
            $('#recipe-box #recipe-folders').hide();
            $('#recipe-box #handle').css('background', '#fff url(/images/bg/bg-recipe-box-handle-closed.gif) no-repeat 0 0');
        });
    }
}

GMI.Calendar.RecipeBox.AddPagingNumbers = function(folder) {
    var recipeCount = folder.find('.recipe').length;
    if (recipeCount < 6) return;
    var pages = Math.ceil(recipeCount / 5);
    folder.find('.page-numbers').html('');
    for (var i = 1; i <= pages; i++) {
        folder.find('.page-numbers').append($('<a href="#" class="show-page">' + i + '</a>'));
    }
    folder.find('.page-numbers > a:first').addClass('selected');
}

// The attribute is a hack so this function can be used two ways
GMI.Calendar.RecipeBox.SetupPaging = function(index) {
    if ($(this).find('.recipe').length < 6) {
        $(this).find('.recipe-pager').hide();
        return;
    }

    $(this).find('.recipe-pager').show();

    GMI.Calendar.RecipeBox.AddPagingNumbers($(this));

    var thisFolderId = $(this).attr('id');
    var folderWrapper = $('#' + thisFolderId);
    
    $(this).find('a.recipe-prev-page').click(function() {
        folderWrapper.trigger('prev.evtpaginate');
        if (!folderWrapper.find('a.show-page:first').hasClass('selected')) {
            folderWrapper.find('a.selected').removeClass('selected').prev().addClass('selected');
        }
        $(this).parent('.recipe-pager').hide().show(); // This to fix a layout bug in IE 6 & 7
        return false;
    });

    $(this).find('a.recipe-next-page').click(function() {
        folderWrapper.trigger('next.evtpaginate');
        if (!folderWrapper.find('a.show-page:last').hasClass('selected')) {
            folderWrapper.find('a.selected').removeClass('selected').next().addClass('selected');
        }
        $(this).parent('.recipe-pager').hide().show(); // This to fix a layout bug in IE 6 & 7
        return false;
    });

    $(this).find('a.show-page').click(function(evt) {
        folderWrapper.trigger('show.evtpaginate', $(this).text());
        folderWrapper.find('a.show-page').removeClass('selected');
        $(this).addClass('selected');
        $(this).closest('.recipe-pager').hide().show(); // This to fix a layout bug in IE 6 & 7
        return false;
    });

    folderWrapper.evtpaginate({ filter: 'div' });
    folderWrapper.trigger('refresh.evtpaginate');

    $(this).removeClass('collapsed');
}

GMI.Calendar.ClearMealPlan = function(evt) {
    evt.preventDefault();

    // This just closes the dialog
    $('.dialog-overlay').click();

    $('td .recipe, td .notes').remove();
    $('td').removeClass('occupied');

    GMI.SendXHRToWCF('ClearMealPlan',
                    { userKey: GMI.Calendar.UserKey,  weekStartDate: $('th:nth-child(2)').attr('id')},
                    function() { },
                    function() { ModalAlert("failed"); }
    );

    ModalAlert("Meal plan cleared!", "Meal plan cleared");
}

GMI.Calendar.PerformHideMeal = function() {
    GMI.Calendar.CurrentMealRow.find('.recipe, .notes').remove();
    var mealTypeId = GMI.Calendar.CurrentMealRow.attr('class');
    GMI.Calendar.CurrentMealRow.addClass('meal-hidden');
    var linkText = GMI.Calendar.CurrentMealRow.find('td:first > a').text()
    GMI.Calendar.CurrentMealRow.find('td:first > a').text(linkText.replace('Hide', 'Show'));
    GMI.Calendar.CurrentMealRow.find('td').droppable('destroy');
    $('.dialog-overlay').click();
    GMI.SendXHRToWCF('HideMealType',
                    { userKey: GMI.Calendar.UserKey, mealTypeId: mealTypeId },
                    function() { },
                    function() { ModalAlert("Hide failed"); }
    );
    return false;
}

GMI.Calendar.HideShowMeal = function(evt) {
    evt.preventDefault();
    var linkText = $(this).text();
    if (linkText.substring(0, 4) == "Hide") {
        GMI.Calendar.CurrentMealRow = $(this).closest('tr');
        //GMI.OpenModalDialog('#hide-meal-type-confirm', 300, 'Hide this meal?');
        $('#hide-meal-type-confirm').ModalDialog({ width: 300, title: 'Hide this meal?' });
    } else {
        var parentRow = $(this).closest('tr');
        parentRow.removeClass('meal-hidden');
        parentRow.find('td').removeClass('occupied');
        parentRow.find('td').droppable(GMI.Calendar.DroppableOptions);
        $(this).text(linkText.replace('Show', 'Hide'));
        GMI.SendXHRToWCF('ShowMealType',
                    { userKey: GMI.Calendar.UserKey, mealTypeId: parentRow.attr('class').replace(' meal-hidden', '') },
                    function() { },
                    function() { ModalAlert("Hide failed"); }
        );
    }
}

GMI.Calendar.ExpandAllRecipes = function(evt) {
    evt.preventDefault();
    $(this).hide();
    $('.btn-collapse-all').show();
    $('table .recipe').removeClass('min-recipe');
}

GMI.Calendar.CollapseAllRecipes = function(evt) {
    evt.preventDefault();
    $(this).hide();
    $('.btn-expand-all').show();
    $('table .recipe').addClass('min-recipe');
}

GMI.Calendar.InitializeGeneralCalendarEvents = function() {
    // Expand/Collapse recipes
    $('.btn-collapse-all').click(GMI.Calendar.CollapseAllRecipes);
    $('.btn-expand-all').click(GMI.Calendar.ExpandAllRecipes);

    // Clear meal plan
    $('.clear-meal-plan').click(function() {
        $('#clear-meal-plan-confirm').ModalDialog({ width: 300, height: 200, title: 'Clear your meal plan?' });
    });

    $('.return-to-cal-link').click(GMI.Calendar.ClosePrintView);

    $('#confirm-clear-mealplan').click(GMI.Calendar.ClearMealPlan);

    // Hide/show meal
    $('a.hide-show-meal').click(GMI.Calendar.HideShowMeal);
    $('#confirm-hide-meal').click(GMI.Calendar.PerformHideMeal);

    $('.print-plan-button-week').click(GMI.Calendar.PrintPlanWeek); // Button that opens dialog
    $('.print-plan-button-day').click(GMI.Calendar.PrintPlanDay);   // Button that opens dialog
    $('#print-plan-day, #print-plan-week').click(GMI.Calendar.PerformPrint);     // Button that confirms selection and prints

    $('.calendar-picker-button').click(GMI.Calendar.ShowDatePicker);

    $('body').delegate('td.min .recipe, td.min .notes', 'click', function() {
        GMI.Calendar.ExpandCollapseRelatedColumn($(this).closest('td').attr('class'));
    });

    // Calendar date picker
    $('.date-picker-input').datepicker({
        showButtonPanel: true,
        buttonImage: '/images/buttons/calendar-button.gif',
        buttonImageOnly: true,
        currentText: '> Go to Today',
        showOn: 'button',
        showAnim: 'fadeIn',
        dayNamesMin: ['S', 'M', 'T', 'W', 'T', 'F', 'S'],
        onSelect: function(dateText, inst) {
            window.location = 'Week.aspx?week=' + dateText;
        }
    });

    // Override the _gotoToday function so it actually load the page
    DP_jQuery.datepicker._gotoToday = function() {
        window.location = 'Week.aspx?week=' + GMI.GetDateStringFromDate(new Date());
    }
}

GMI.Calendar.InitializeRecipeContextMenu = function() {
    $('body').delegate('div.recipe-context-menu', 'mouseleave', function(evt) {
            $(this).fadeOut(150, function() {
                $(this).remove(); // Remove it completely from the document
            });
        }
    );
    $('body').delegate('div.recipe-context-menu > a.recipe-quick-view', 'click', GMI.Calendar.OpenRecipeQuickView);
    $('body').delegate('div.recipe-context-menu > a.remove-recipe', 'click', GMI.Calendar.RemoveRecipeViaMenu);
    // Event handler for this moved to commonplan.js so it can be used on other pages
    $('body').delegate('div.recipe-context-menu > a.save-recipe-to-recipe-box', 'click', GMI.Calendar.SaveRecipeToRecipeBox);
    $('body').delegate('div.recipe-context-menu > a.add-as-leftovers', 'click', GMI.Calendar.AddAsLeftOvers);
    $('body').delegate('div.recipe-context-menu > a.recipe-quantity', 'click', GMI.Calendar.RecipeQuantity);
    $('body').delegate('div.recipe-context-menu > a.print-recipe', 'click', GMI.Calendar.PrintRecipe);
    
    // Confirm add to recipe box
    $('#add-to-recipebox').click(GMI.Calendar.AddRecipeToRecipeFolder);

    // Initialize the recipe quantity slider
    $('#quantity-slider').slider({
        value: 2,
        min: 1,
        max: 20,
        step: 1,
        slide: function(evt, ui) {
            $('#current-value').html(ui.value);
            $('#current-value').css('left', GMI.Calendar.GetQuantitySliderPosition(ui.value));
        }
    });

    // Update recipe quantity
    $('#apply-quantity-button').click(GMI.Calendar.UpdateRecipeQuantity);

    // Leftovers dialog submit
    $('#add-as-leftovers').click(GMI.Calendar.SaveLeftOvers);


    $('body').delegate('#calendar-container .recipe .options', 'click', GMI.Calendar.RecipeOptionsMenu);
}

GMI.Calendar.InitializeRecipeEvents = function() {
    $('body').delegate('.recipe a.minimize-recipe', 'click', GMI.Calendar.MinimizeRecipe);
    $('body').delegate('.recipe a.maximize-recipe', 'click', GMI.Calendar.MaximizeRecipe);
    $('body').delegate('.recipe a.remove-recipe', 'click', GMI.Calendar.RemoveRecipe);
    //    recipe.find('.options').click(GMI.Calendar.RecipeOptionsMenu);

    // Rate a recipe
    $('body').delegate('a.thumbs-up', 'click', GMI.Calendar.RateRecipeUp);
    $('body').delegate('a.thumbs-down', 'click', GMI.Calendar.RateRecipeDown);
    $('body').delegate('.recipe a.thumbs-up, a.thumbs-down', 'hover', function() {
        $(this).toggleClass('thumb-hover');
    });

    $('body').delegate('#calendar-container .recipe-pic', 'click', function() {
        trackAction(GMI.BAH.Tracking.RecipeViewFromMyPlan);
        window.location = '/Recipes/RecipeView.aspx?recipeguid=' + $(this).closest('.recipe').attr('id');
    });
}

GMI.Calendar.InitializeCellContextMenu = function() {
    $('body').delegate('.cell-context-menu', 'mouseleave', function(evt) {
        $(this).fadeOut(150, function() {
            $(this).remove(); // Remove it completely from the document
        });
    });

    $('body').delegate('a.cell-context-button', 'click', GMI.Calendar.CellContextMenu);
    $('body').delegate('.cell-context-menu a.search-recipes', 'click', GMI.Calendar.SearchRecipes);
    $('body').delegate('.cell-context-menu a.add-note', 'click', GMI.Calendar.AddNote);
    $('body').delegate('.cell-context-menu a.add-recipe', 'click', GMI.Calendar.AddRecipe);
}

GMI.Calendar.Notes.InitializeEvents = function() {
    // Delete notes on click
    $('body').delegate('.notes a.remove-notes', 'click', GMI.Calendar.Notes.Delete);
    //Edit notes on click
    $('body').delegate('.notes a.edit-notes', 'click', GMI.Calendar.Notes.Edit);

    //cancel and save buttons
    $('body').delegate('a.cancel-note-button', 'click', GMI.Calendar.Notes.Cancel);
    $('body').delegate('a.save-note-button', 'click', GMI.Calendar.Notes.Save);
}

GMI.Calendar.RecipeSearch.InitializeEvents = function() {
    //events for recipe search
    //hide search box on cancel button click
    $('body').delegate('a.cancel-search-button', 'click', GMI.Calendar.RecipeSearch.Cancel);
    //open search dialog results on submit button click
    $('body').delegate('a.submit-search-button', 'click', GMI.Calendar.RecipeSearch.Submit);
    //clear search text on focus
    $('body').delegate('div.search-placeholder .search-text', 'focus', GMI.Calendar.RecipeSearch.ClearText);
    //run search when hit enter key
    $('div.search-placeholder .search-text').EnterAction(GMI.Calendar.RecipeSearch.Submit);

    //add recipe to calendar on context menu click
    $('body').delegate('div.recipe-context-menu > a.save-recipe-to-calendar', 'click', GMI.Calendar.RecipeSearch.AddToCalendar);
    //paging in search dialog
    $('body').delegate('.search-paging .page-links a', 'click', GMI.Calendar.RecipeSearch.Page);
    // Bind search results recipe context menu
    $('body').delegate('#search-results-dialog .recipe .options', 'click', GMI.Calendar.RecipeSearch.RecipeOptionsMenu);

    //click image on recipe in search results to add it to the calendar
    $('body').delegate('#search-results-dialog .recipe-pic', 'click',
                        function(evt) {
                            GMI.Calendar.RecipeContextRelatedRecipe = $(this).closest('.recipe');
                            GMI.Calendar.RecipeSearch.AddToCalendar(evt); 
                            });
}

GMI.Calendar.InitializeRecipeBoxEvents = function() {
    // Recipe box is loaded after page load
    $('#recipe-box #handle').click(GMI.Calendar.ShowHideRecipeBox);

    // Add new folder
    $('#new-folder-button').click(GMI.Calendar.OpenAddNewFolderToRecipeBox);
    $('#save-folder-button').click(GMI.Calendar.AddNewFolderToRecipeBox);
    $('#new-folder-name').EnterAction(GMI.Calendar.AddNewFolderToRecipeBox);
    $('#cancel-folder-button').click(GMI.Calendar.CancelAddNewFolderToRecipeBox);
    $('a.search-recipe-box').click(GMI.Calendar.SearchRecipeBox);
    $('input#RecipeName').EnterAction(GMI.Calendar.SearchRecipeBox);

    // Set up paging for recipe box folders
    $('.rec-folder').each(GMI.Calendar.RecipeBox.SetupPaging);
    
    $('.rec-folder').each(function(index, el) {
        GMI.Calendar.BindRecipeBoxFolderActions($(el));
    });
    
    $('.rec-folder h4').click(); // collapse all recipe box folders
    $('body').delegate('#search-results h4', 'click', GMI.Calendar.ToggleRecipeFolderVisibility);

    $('#recipe-box .recipe').draggable(GMI.Calendar.DraggableOptions);
}

GMI.Calendar.InitializeDraggableDroppable = function() {
    // Set which elements are draggable
    $('.recipe, .notes').draggable(GMI.Calendar.DraggableOptions);

    // Set which elements accept draggable elements
    $('td.sun, td.mon, td.tue, td.wed, td.thu, td.fri, td.sat, td.sun').droppable(GMI.Calendar.DroppableOptions);
    $('tr.meal-hidden td').droppable('destroy');
    $('div.rec-folder').droppable(GMI.Calendar.DroppableOptions).droppable('options', 'accept', '.recipe');
}

GMI.Calendar.GetPrintView = function() {
    var params = window.location.href.split('&');
    var printPlan = false;
    var printRecipes = false;
    var type = '';
    for (var i = 1; i < params.length; i++) {
        if (params[i] == 'recipes=1') {
            printRecipes = true;
            continue;
        }

        if (params[i] == 'plan=1') {
            printPlan = true;
            continue;
        }

        if (params[i].substr(0, 4) == 'type') {
            type = params[i].substr(5).replace('#rld', '');
        }
    }

    if (printPlan) {
        $('div.content-container-mid').removeClass('no-print');
    } else {
        $('div.content-container-mid').addClass('no-print');
    }

    var dateString;
    if (type == 'week') {
        dateString = $('th:nth-child(2)').attr('id');
    } else {
        dateString = $('th:last').attr('id');
    }

    $('body').append('<div class="dialog-overlay"></div>');
    $('.dialog-overlay').show();

    if (printRecipes) {
        $('div#print-recipes-container').removeClass('no-print').html('');
        // Grab the recipes for this week

        GMI.SendXHRToWCF('GetPrintRecipesForPlan',
                        { userKey: GMI.Calendar.UserKey, theDate: dateString, type: type },
        // Success      
                        function(data) {
                            if (data.d == "") {
                                data.d = "No recipes";
                            }

                            // Inject the returned list of recipes into the document
                            $('#print-recipes-container').html(data.d);

                            // This makes it so there isn't a blank white page
                            if (!printPlan) {
                                // The space before page-break-before fixes an IE 7 bug
                                $('.printed-recipe:first').css({ ' page-break-before': 'avoid' });
                            }
                            $('.dialog-overlay').click();
                            $('link[media!=print]').attr('media', 'fake');
                            $('link[media=print]').show().attr('media', '');
                            $('.dialog-overlay').remove();
                            window.print();
                        },
        // Error
                        function() {
                            ModalAlert('There was an error submitting your request. Please "reload" the page to try again.');
                        }
        );
    } else {
        $('div#print-recipes-container').addClass('no-print');
        $('.dialog-overlay').click();
        $('link[media!=print]').attr('media', 'fake');
        $('link[media=print]').show().attr('media', '');
        $('.dialog-overlay').remove();
        window.print();
    }

    $('.return-to-cal-link').click(function() {
        window.close();
    });
}

$(document).ready(function() {

    GMI.Calendar.UserKey = $('span.uk').html();

    GMI.Calendar.InitializeGeneralCalendarEvents();
    GMI.Calendar.InitializeRecipeContextMenu();
    GMI.Calendar.InitializeCellContextMenu();
    GMI.Calendar.InitializeRecipeEvents();
    GMI.Calendar.Notes.InitializeEvents();
    GMI.Calendar.RecipeSearch.InitializeEvents();
    GMI.Calendar.InitializeDraggableDroppable();

    GMI.Calendar.FixIE6ContextMenuButtons();

    if (GMI.IsLoggedIn) $('#recipe-box-preloaded').show();

    // Login auto prompt init
    if (!GMI.IsLoggedIn) GMI.StartLoginTimer(10000);
    $('#login-prompt .close-prompt').click(GMI.ResetLoginTimer);


    var printRegex = new RegExp(/print=1/);

    if (printRegex.test(window.location.href)) {
        GMI.Calendar.GetPrintView();
    }


});

// Deferred load for recipe box control
$(window).load(function() {
    //document.getElementById('calendar-container').onselectstart = function() { return false; } // ie
    //document.getElementById('calendar-container').onmousedown = function() { return false; } // mozilla
    
    if (GMI.IsLoggedIn) {
        GMI.SendXHRToWCF('LoadRecipeBox', null,
                    function(data) {
                        if (data == null) return;
                        $('#calendar-container').prepend(data.d);
                        $('#recipe-box').hide().fadeIn(1500);
                        $('#recipe-box img.async').each(GMI.LoadImage);
                        GMI.Calendar.InitializeRecipeBoxEvents();
                    },
                    function() { ModalAlert("Unable to load recipe box. Please try again by refreshing the page."); }
        );
    }
});

