﻿if (typeof (GMI.Calendar) == 'undefined') {
    GMI.Calendar = {};
}

//////////////////////////
// General Calendar logic
//////////////////////////
GMI.Calendar.DayStructureByAbbr = {
    Su: 'Sunday',
    Mo: 'Monday',
    Tu: 'Tuesday',
    We: 'Wednesday',
    Th: 'Thursday',
    Fr: 'Friday',
    Sa: 'Saturday'
};

GMI.Calendar.DayArray = [
    'Sunday',
    'Monday',
    'Tuesday',
    'Wednesday',
    'Thursday',
    'Friday',
    'Saturday'
];

GMI.Calendar.UserKey;

GMI.Calendar.FixIE6ContextMenuButtons = function() {
    if ($.browser.msie && $.browser.version == 6.0) {
        $('td.occupied.current, td.occupied.active').addClass('ie6special');
    }
}

// Finds a day in the middle of a string; intended to extract the day class from a calendar cell
GMI.Calendar.DayOfWeekRegex = new RegExp(/sun|mon|tue|wed|thu|fri|sat|/i);

// This function grabs all the important data items for a recipe
GMI.Calendar.GetContainerData = function(el) {
    var returnData = {};
    returnData.UserKey = GMI.Calendar.UserKey; // user key
    returnData.ItemId = el.attr('id'); // recipe or note id
    returnData.MealId = el.closest('tr').attr('class'); // meal type id
    returnData.FolderId = el.closest('.rec-folder').attr('id'); // Recipe box folder id
    if (returnData.FolderId != null) {
        return returnData;
    }
    // This only applies to recipes currently on the calendar
    var dayOfWeekArray = GMI.Calendar.DayOfWeekRegex.exec(el.closest('td').attr('class'));
    returnData.DayOfWeek = dayOfWeekArray[0];
    returnData.CellDate = $('th.' + returnData.DayOfWeek).attr('id'); // recipe cell date
    return returnData;
}

GMI.Calendar.ExpandCollapseCell = function() {
    $(this).unbind('click');

    var pseduo;
    var siblingTh;

    if ($(this).index() > 3) {
        siblingTh = $(this).prev('th');
        pseduo = 'first';
    } else {
        siblingTh = $(this).next('th');
        pseduo = 'last';
    }
    // Grab the last or first th element that does not contain the class 'min' or 'head'
    var selectColToCollapse = 'th:not([class*=min]):not([class*=head]):';
    var colToCollapse = $(selectColToCollapse + pseduo, $(this).parent());
    var thisDayToCollapse = colToCollapse.attr('class').replace('active', '').trim();
    $('.' + thisDayToCollapse).addClass('min');
    $('th.' + thisDayToCollapse).html($('th.' + thisDayToCollapse).html().substr(0, 2) + '<span class="print-only">' + $('th.' + thisDayToCollapse).html().substr(2) + '</span>');
    $(this).removeClass('min');
    $('span', this).replaceWith($('span', this).contents());
    $('.' + $(this).attr('class').replace('active', '').trim()).removeClass('min');
    $('th.min').unbind('click', GMI.Calendar.ExpandCollapseCell);
    $('th.min').click(GMI.Calendar.ExpandCollapseCell);
    if (siblingTh.hasClass('min')) siblingTh.click();
}

// This takes the entire class of a td calendar cell and expands the related column
GMI.Calendar.ExpandCollapseRelatedColumn = function(containerClassAttr) {
    dayOfWeek = GMI.Calendar.DayOfWeekRegex.exec(containerClassAttr);
    if (dayOfWeek.length > 0) {
        $('th.' + dayOfWeek[0]).click();
    }
}

// This makes the call to the web service for the drag & drop and dialogs on calendar and search results
GMI.Calendar.SaveRecipeToRecipeBoxSendXHR = function(recipeId, folderId) {
    GMI.SendXHRToWCF('MoveRecipeFromCalendarToRecipeBox',
                    { userKey: GMI.Calendar.UserKey, recipeId: recipeId, recipeBoxCategoryId: folderId },
                    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.");
                    }
            );
}

// User clicked the Save Recipe To Recipe Box option from the recipe context menu
GMI.Calendar.SaveRecipeToRecipeBox = function(evt) {
    evt.preventDefault();
    $('#save-to-recipe-box-dialog .dialog-content').html('');

    if (!GMI.IsLoggedIn) {
        GMI.ShowLoginPrompt();
        return false;
    }
    $('#save-to-recipe-box-dialog').data('recipeId', $(this).attr('rel'));

    // Make the XHR call and get the HTML of the recipes returned
    GMI.SendXHRToWCF('GetRecipeBoxFolders', null,
                    function(data) {
                        if (!data.d.length) return;
                        for (var i = 0; i < data.d.length; i++) {
                            $('#save-to-recipe-box-dialog .dialog-content').append('<div class="add-to-folder"><input type="checkbox" id="' + data.d[i].ID + '" /> <span class="folder-name">' + data.d[i].Name + '</span></div>');
                        }
                        if (data.d.length < 10) {
                            $('#save-to-recipe-box-dialog .dialog-content').append('<div style="padding-top: 10px;"><label for="new-recipe-folder" style="width:110px">New folder:</label> <input type="text" name="new-recipe-folder" id="new-recipe-folder" size="30" /></div>');
                        }
                        $('#save-to-recipe-box-dialog').ModalDialog({ 'width': 450, 'title': 'To which folder(s) would you like to add this recipe?', id: 'SaveRecipe', height: 250 });
                        $(this).parent().mouseout();
                    },
                    function() {
                        ModalAlert("There was an error getting your recipe box folders.  If you are not logged in, please login and try again.");
                    }
    );
    $(this).parent().mouseout();
}

GMI.AddRecipeToNewlyCreatedFolder = function(recipeId) {
    // Create a new folder and save the recipe to that folder
    var newFolderId;
    var newFolderName = $('#save-to-recipe-box-dialog input#new-recipe-folder').val();
    if (GMI.ValidRecipeBoxFolder(newFolderName, '#save-to-recipe-box-dialog div.add-to-folder .folder-name')) {
        GMI.SendXHRToWCF('AddCategoryToRecipeBox',
            { userKey: $('span.uk').first().text(), categoryName: newFolderName },
            function(data) {
                newFolderId = data.d;
                GMI.Calendar.SaveRecipeToRecipeBoxSendXHR(recipeId, newFolderId);

                // Just reload the recipe box in this case
                if ($('#recipe-box').length) {
                    $('#recipe-box').remove();

                    GMI.SendXHRToWCF('LoadRecipeBox', null,
                        function(data) {
                            $('#calendar-container').prepend(data.d);
                            $('#recipe-box').hide().fadeIn(1500);
                            GMI.Calendar.InitializeRecipeBoxEvents();
                        },
                        GMI.StandardAJAXErrorFunction);
                }

            },
            GMI.StandardAJAXErrorFunction);
        return true;
    }
    else {
        return false;
    }
}

GMI.AddToRecipeBoxFolderFromSearch = function() {
    var recipeId = $('#save-to-recipe-box-dialog').data('recipeId');

    // Save the recipe to the folders selected
    $(this).closest('#save-to-recipe-box-dialog').find('input[type=checkbox]:checked').each(
        function(index) {
            GMI.Calendar.SaveRecipeToRecipeBoxSendXHR(recipeId, $(this).attr('id')); // Make the XHR
        }
    );

    var closeDialog = true;
    if ($('#save-to-recipe-box-dialog input#new-recipe-folder').length && $('#save-to-recipe-box-dialog input#new-recipe-folder').val() != '') {
        closeDialog = GMI.AddRecipeToNewlyCreatedFolder(recipeId);
    }

    if (closeDialog)
        $(this).closest('.dialog-buttons').find('.cancel-button').click();

    return false;
}

GMI.MarkRecipeLikedOrDisliked = function() {
    if ($(this).hasClass('recipe-like')) {
        $(this).parent('div').removeClass('recipe-disliked');
        $(this).parent('div').addClass('recipe-liked');
        GMI.SendXHRToWCF('LikeRecipe', { userKey: $('span.uk').first().text(), recipeId: $(this).find('a').attr('rel') }, function() {}, function() {});
    } else {
        $(this).parent('div').removeClass('recipe-liked');
        $(this).parent('div').addClass('recipe-disliked');
        GMI.SendXHRToWCF('DisLikeRecipe',  { userKey: $('span.uk').first().text(), recipeId: $(this).find('a').attr('rel') }, function() {}, function() {});
    }
}


// After choosing a folder the user clicked the "Add Recipe" button
GMI.Calendar.AddRecipeToRecipeFolder = function(evt) {
    evt.preventDefault();
    
    var recipeId = GMI.Calendar.RecipeContextRelatedRecipe.attr('id');
    // Need to clone recipe and attach events
    var clonedRecipe = GMI.Calendar.RecipeContextRelatedRecipe.clone().draggable(GMI.Calendar.DraggableOptions);

    // Loop through each checked folder and insert the recipe for that folder and make the XHR
    $(this).closest('#save-to-recipe-box-dialog').find('input[type=checkbox]:checked').each(
        function(index) {
            // Logic added to check if this recipe already exists in this folder
            if (!$('#recipe-box #recipe-folders').find('#' + $(this).attr('id')).find('#' + clonedRecipe.attr('id')).length) {
                GMI.Calendar.UpdateFolderTotal($('#recipe-box #' + $(this).attr('id')), 1);  // Update folder total
                clonedRecipe.insertAfter('#' + $(this).attr('id') + ' h4'); // Add the recipe to the folder
                GMI.Calendar.SaveRecipeToRecipeBoxSendXHR(clonedRecipe.attr('id'), $(this).attr('id')); // Make the XHR
                $('#' + $(this).attr('id')).each(GMI.Calendar.RecipeBox.SetupPaging);
            }
        }
    );

    var closeDialog = true;
    if ($('#save-to-recipe-box-dialog input#new-recipe-folder').length && $('#save-to-recipe-box-dialog input#new-recipe-folder').val() != '') {
        closeDialog = GMI.AddRecipeToNewlyCreatedFolder(recipeId);
    }

    // Just a quick and easy way to close the dialog
    if (closeDialog)
        $(this).closest('.dialog-buttons').find('.cancel-button').click();
}

$(document).ready(function() {
    // Expand calendar cell
    $('body').delegate('th.min', 'click', GMI.Calendar.ExpandCollapseCell);
    $('body').delegate('.recipe-like, .recipe-dislike', 'click', GMI.MarkRecipeLikedOrDisliked);
});
