﻿
if (typeof (GMI.BAH) == 'undefined') {
    GMI.BAH = {};
}

if (typeof (GMI.BAH.RecipeBox) == 'undefined') {
    GMI.BAH.RecipeBox = {};
}

if (typeof (GMI.BAH.RecipeBox.Folder) == 'undefined') {
    GMI.BAH.RecipeBox.Folder = {SearchTerm: "",
                                ID: "",
                                Sort: "",
                                Page: 1};
}

GMI.BAH.RecipeBox.CancelLogin = function() {
    window.location.assign('/');

}

GMI.BAH.RecipeBox.AddNewFolder = function() {
    $(this).hide();
    $('#create-new-folder').show();
    $('input#new-folder-name').focus();
    return false;
}


GMI.BAH.RecipeBox.CancelNewFolder = function() {
    $('#create-new-folder').hide();
    $('#new-folder-button').show();
    $('input#new-folder-name').val('');
    return false;
}

GMI.BAH.RecipeBox.SaveNewFolder = function() {
    var folderName = $('input#new-folder-name').val();

    if (!GMI.ValidRecipeBoxFolder(folderName, '.recipe-box-folder'))  //function in common.js
        return false;
        
    GMI.BAH.RecipeBox.CancelNewFolder();

    // Make WCF call that creates a new recipe box folder and returns the new recipe box folders html
    //UpdateRecipeBoxFolders(ByVal userKey As String, ByVal folderIDs As String, ByVal folderNames As String, ByVal folderColors As String) As String
    GMI.SendXHRToWCF('UpdateRecipeBoxFolders',
                         { userKey: GMI.BAH.RecipeBox.UserKey,
                             folderIDs: "",
                             folderNames: folderName,
                             folderColors: ""
                         },
                         function(data) {
                             if (data.d != '') {
                                 $('#recipe-box-folders').html(data.d);
                                 $("#folder-edit").sortable();  //hook up folder sorting
                                 GMI.BAH.RecipeBox.InitializeDroppable();
                             }
                             else
                                 ModalAlert("There was an error submitting your request. Please refresh the page to try again.");
                         },
                        function() {
                            // Error
                            ModalAlert("There was an error submitting your request. Please refresh the page to try again.");
                        }
                );

    return false;
}


GMI.BAH.RecipeBox.EditFolders = function() {
    $('#folder-display').hide();
    $('#folder-functions').hide();
    $('#folder-edit').show();
    $('#edit-folders-save-cancel').show();
    return false;
}

GMI.BAH.RecipeBox.SetFolderColor = function() {
    var colorClass = $(this).attr('class');
    $(this).closest('li').attr('class', 'undershadow ' + colorClass);
    return false;
}

GMI.BAH.RecipeBox.ConfirmFolderDelete = function() {
    
    GMI.BAH.RecipeBox.FolderToDelete = $(this).closest('li').attr('rel');
    $('#remove-folder-confirm').ModalDialog({ width: 300, title: 'Remove Folder?' });

}

GMI.BAH.RecipeBox.DeleteFolder = function() {

    $('.dialog-overlay').click();

    //Make WCF call that deletes the folder returns the new recipe box folders html
    //DeleteRecipeBoxFolder(ByVal userKey As String, ByVal folderID As String) As String
    GMI.SendXHRToWCF('DeleteRecipeBoxFolder',
                         { userKey: GMI.BAH.RecipeBox.UserKey,
                             folderID: GMI.BAH.RecipeBox.FolderToDelete
                         },
                         function(data) {
                             if (data.d != '') {
                                 $('#recipe-box-folders').html(data.d);
                                 $("#folder-edit").sortable();  //hook up folder sorting
                                 GMI.BAH.RecipeBox.InitializeDroppable();
                                 //check if any folders left to edit and put back in edit display
                                 if ($('#folder-edit li').length > 0)
                                     GMI.BAH.RecipeBox.EditFolders();
                                 //if deleted current folder then refresh the folder recipe list - will default to 1st folder
                                 if (GMI.BAH.RecipeBox.FolderToDelete == GMI.BAH.RecipeBox.Folder.ID) {
                                     GMI.BAH.RecipeBox.Folder.ID = $('li.recipe-box-folder').first().attr('rel');
                                     GMI.BAH.RecipeBox.DisplayFolderRecipes();
                                 }
                                 GMI.BAH.RecipeBox.FolderToDelete = "";
                             }
                             else
                                 ModalAlert("There was an error submitting your request. Please refresh the page to try again.");
                         },
                        function() {
                            // Error
                            ModalAlert("There was an error submitting your request. Please refresh the page to try again.");
                        }
                );

    return false;
}

GMI.BAH.RecipeBox.DisplayFolders = function() {

    //refresh the recipe box folders html
    GMI.SendXHRToWCF('GetRecipeBoxFoldersHTML',
                         {  },
                         function(data) {
                             if (data.d != '') {
                                 $('#recipe-box-folders').html(data.d);
                                 $("#folder-edit").sortable();  //hook up folder sorting
                                 GMI.BAH.RecipeBox.InitializeDroppable();
                             }
                             else
                                 ModalAlert("There was an error submitting your request. Please refresh the page to try again.");
                         },
                        function() {
                            // Error
                            ModalAlert("There was an error submitting your request. Please refresh the page to try again.");
                        }
                );

    return false;
}

GMI.BAH.RecipeBox.RefreshFolderHeader = function() {
    //get the current folder name and color from the recipe box folder list
    var folderItem = $('li[rel="' + GMI.BAH.RecipeBox.Folder.ID + '"]');
    var folderColor = folderItem.attr('class').replace('recipe-box-folder undershadow', '').trim();
    var folderName = folderItem.find('div.facetSeeAll').html().trim();
    
    //set the heading folder name and color
    $('div#folder-header').attr('class', folderColor);
    $('.recipe-category-name').html(folderName)
}


GMI.BAH.RecipeBox.ValidateFolders = function() {
    var errors = '';
    var exp = new RegExp(/^[0-9a-zA-Z\s]{1,20}$/);

    //check for valid folder names
    $('input.edit-folder-name').each(function() {
        if (!exp.test($(this).val())) {
            errors += "'" + $(this).val() + "' is an invalid folder name.<br />";
        }
    });
    //display errors
    if (errors != '') {
        ModalAlert("Please enter valid folder names.  The folder names should only include letters and numbers and have a maximum length of 20 characters. <br /><br />" + errors, "Invalid Folder Name");
        return false;
    }

    //check for duplicate folder names
    var folders = $('input.edit-folder-name');
    var i = 0, j = 0, k = 0, count = 0;
    var duplicates = new Array();
    var exists = false;
    for (i = 0; i < folders.length; i++) {
        for (j = 0; j < folders.length; j++) {
            if (i != j && folders[i].value.toLowerCase().trim() == folders[j].value.toLowerCase().trim()) {
                //have a duplicate - check if it already exists in array - if not, add it
                exists = false;
                for (k = 0; k < duplicates.length; k++) {
                    if (folders[i].value.toLowerCase().trim() == duplicates[k].toLowerCase().trim()) {
                        exists = true;
                        break;
                    }
                }
                if (!exists) {
                    duplicates[count] = folders[i].value;
                    count++;
                }
            }
        }
    }
    if (count > 0) {
        for (i = 0; i < duplicates.length; i++) {
            errors += "The folder name '" + duplicates[i] + "' is used more than once.<br />";
        }
    }
    //display errors
    if (errors != '') {
        ModalAlert("You cannot save duplicate folder names.<br /><br />" + errors, "Invalid Folder Name");
        return false;
    }
    else {
        return true;
    }
}


GMI.BAH.RecipeBox.SaveEditFolders = function() {

    if (!GMI.BAH.RecipeBox.ValidateFolders())
        return false;

    var folderIDs = '';
    var folderNames = '';
    var folderColors = '';

    $('input.edit-folder-name').each(function() {
        folderNames += $(this).val() + ",";
        folderIDs += $(this).closest('li').attr('rel') + ",";
        folderColors += $(this).closest('li').attr('class').replace('undershadow', '').trim() + ",";
    });

    // Make WCF call that updates the folder names and colors and returns the new recipe box folders html
    //UpdateRecipeBoxFolders(ByVal userKey As String, ByVal folderIDs As String, ByVal folderNames As String, ByVal folderColors As String) As String
    GMI.SendXHRToWCF('UpdateRecipeBoxFolders',
                         { userKey: GMI.BAH.RecipeBox.UserKey,
                             folderIDs: folderIDs,
                             folderNames: folderNames,
                             folderColors: folderColors
                         },
                         function(data) {
                             if (data.d != '') {
                                 $('#recipe-box-folders').html(data.d);
                                 $("#folder-edit").sortable();  //hook up folder sorting
                                 GMI.BAH.RecipeBox.RefreshFolderHeader();
                                 GMI.BAH.RecipeBox.InitializeDroppable();
                             }
                             else
                                 ModalAlert("There was an error submitting your request. Please refresh the page to try again.");
                         },
                        function() {
                            // Error
                            ModalAlert("There was an error submitting your request. Please refresh the page to try again.");
                        }
                );

    return false;
}


GMI.BAH.RecipeBox.SelectFolder = function() {
    GMI.BAH.RecipeBox.Folder.ID = $(this).closest('li').attr('rel');
    GMI.BAH.RecipeBox.Folder.SearchTerm = '';
    GMI.BAH.RecipeBox.Folder.Sort = '';
    GMI.BAH.RecipeBox.Folder.Page = 1;
    GMI.BAH.RecipeBox.DisplayFolderRecipes();
    return false;
}

GMI.BAH.RecipeBox.SortRecipeList = function() {
    GMI.BAH.RecipeBox.Folder.Sort = $('.recipe-sort-list').val();
    GMI.BAH.RecipeBox.Folder.Page = 1;
    GMI.BAH.RecipeBox.DisplayFolderRecipes();
    return false;
}

GMI.BAH.RecipeBox.PageRecipeList = function() {
    GMI.BAH.RecipeBox.Folder.Page = $(this).attr('rel');
    GMI.BAH.RecipeBox.DisplayFolderRecipes();
    return false;
}

GMI.BAH.RecipeBox.SearchClear = function() {

    if ($('input#search-text').val() == "Search Your Recipe Box")
        $('input#search-text').val('');
}


GMI.BAH.RecipeBox.SearchRecipeBox = function(evt) {
    var searchTerm = $('input#search-text').val().trim(); 
    if (searchTerm == '') return false;

    GMI.BAH.RecipeBox.Folder.ID = '';
    GMI.BAH.RecipeBox.Folder.SearchTerm = searchTerm; 
    GMI.BAH.RecipeBox.Folder.Sort = '';
    GMI.BAH.RecipeBox.Folder.Page = 1;
    GMI.BAH.RecipeBox.DisplayFolderRecipes();
    return false;
}

GMI.BAH.RecipeBox.DisplayFolderRecipes = function() {

    $('body').append('<div id="waiting-overlay" class="dialog-overlay"></div>');
    $('#waiting-overlay').show();

    GMI.SendXHRToWCF('GetRecipeBoxFolderRecipesHTML',
                        { folderID: GMI.BAH.RecipeBox.Folder.ID,
                            searchText: GMI.BAH.RecipeBox.Folder.SearchTerm,
                            sort: GMI.BAH.RecipeBox.Folder.Sort,
                            currentPage: GMI.BAH.RecipeBox.Folder.Page
                        },
                         function(data) {
                             $('#waiting-overlay').remove();
                             if (data.d != '') {
                                 $('#folder-recipe-list').html(data.d);
                                 GMI.BAH.RecipeBox.InitializeDraggable();
                                 $('.recipe-sort-list').change(GMI.BAH.RecipeBox.SortRecipeList);
                                 //get recipe images
                                 $('img.async-rating').each(GMI.LoadImageAndRating);
                             }
                             else
                                 ModalAlert("There was an error submitting your request. Please refresh the page to try again.");
                         },
                        function() {
                            // Error
                            $('#waiting-overlay').remove();
                            ModalAlert("There was an error submitting your request. Please refresh the page to try again.");
                        }
                );

    return false;
}

GMI.BAH.RecipeBox.RemoveRecipe = function() {

    var ids = $(this).attr('rel').split('~');

    if (ids.length == 2) {
        GMI.SendXHRToWCF('RemoveFromRecipeBox',
                        { recipeId: ids[0],
                            categoryId: ids[1]
                        },
                         function(data) {
                             if (data.d != '') {
                                 alert(data.d);
                             }
                             else {
                                 GMI.BAH.RecipeBox.DisplayFolders();
                                 GMI.BAH.RecipeBox.DisplayFolderRecipes();
                             }
                         },
                        function(requestObj) {
                            //alert(requestObj.responseText);
                            // Error
                            ModalAlert("There was an error removing the recipe. Please refresh the page to try again.");
                        }
                );
    }

    return false;
}


// The options that will be attached to the draggable recipe
GMI.BAH.RecipeBox.DraggableOptions = {
    appendTo: '#folder-recipe-list',
    cancel: '', // Prevents dragging when clicking on certain elements
    cursor: 'pointer',
    delay: 25,
    distance: 5,
    opacity: 0.8,
    containment: false,
    refreshPositions: true,
    revert: 'invalid',
    revertDuration: 100,
    helper: 'clone',
    zindex: 1000000,
    start: function(evt, ui) { // Event order: draggable.start, droppable.drop, draggable.stop
    },
    stop: function(evt, ui) {
    }
}

GMI.BAH.RecipeBox.DroppableOptions = {
    accept: '.recipe-image, .recipe-name',
    hoverClass: 'drag-hover',
    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 recipeID = $(ui.draggable).find('span.recipe-drag').attr('rel');
        var folderID = $(this).attr('rel');

        //make call to add the recipe to the folder
        GMI.SendXHRToWCF('AddToRecipeBox',
                         { recipeId: recipeID,
                             categoryId: folderID
                         },
                         function(data) {
                             if (data.d != '') {
                                 $('#recipe-box-folders').html(data.d);
                                 $("#folder-edit").sortable();  //hook up folder sorting
                                 GMI.BAH.RecipeBox.InitializeDroppable();
                             }
                             else
                                 ModalAlert("There was an error submitting your request. Please refresh the page to try again.");
                         },
                        function() {
                            // Error
                            ModalAlert("There was an error submitting your request. Please refresh the page to try again.");
                        }
                );

    },
    over: function(evt, ui) {
    },
    out: function(evt, ui) {
        // Setting the queue to an empty array of functions (cancelling our events)
        //        $(this).queue([]);
    }
}

GMI.BAH.RecipeBox.InitializeEvents = function() {
    //add new folder events
    $('body').delegate('#new-folder-button', 'click', GMI.BAH.RecipeBox.AddNewFolder);
    $('body').delegate('#cancel-folder-button', 'click', GMI.BAH.RecipeBox.CancelNewFolder);
    $('body').delegate('#save-folder-button', 'click', GMI.BAH.RecipeBox.SaveNewFolder);
    $('input#new-folder-name').EnterAction(GMI.BAH.RecipeBox.SaveNewFolder);

    //edit folders events
    $('body').delegate('#edit-folders-button', 'click', GMI.BAH.RecipeBox.EditFolders);
    $('body').delegate('#cancel-edit-button', 'click', GMI.BAH.RecipeBox.DisplayFolders);
    $('body').delegate('#save-edit-button', 'click', GMI.BAH.RecipeBox.SaveEditFolders);
    $('body').delegate('.color-picker a', 'click', GMI.BAH.RecipeBox.SetFolderColor);
    $('body').delegate('#remove-button', 'click', GMI.BAH.RecipeBox.ConfirmFolderDelete);
    $('body').delegate('#confirm-delete-folder', 'click', GMI.BAH.RecipeBox.DeleteFolder);

    //events that reload the folder recipes
    $('body').delegate('#folder-display a.folder-link', 'click', GMI.BAH.RecipeBox.SelectFolder);
    //$('body').delegate('.recipe-sort-list', 'change', GMI.BAH.RecipeBox.SortRecipeList); -doesn't work in IE
    $('.recipe-sort-list').change(GMI.BAH.RecipeBox.SortRecipeList);
    //paging
    $('body').delegate('.paging .page-links a', 'click', GMI.BAH.RecipeBox.PageRecipeList);
    //search
    $('body').delegate('input#search-text', 'focus', GMI.BAH.RecipeBox.SearchClear);
    $('body').delegate('#search-button', 'click', GMI.BAH.RecipeBox.SearchRecipeBox);
    $('input#search-text').EnterAction(GMI.BAH.RecipeBox.SearchRecipeBox);
    //remove recipe from recipe box folder
    $('body').delegate('.remove-from-recipe-box-link', 'click', GMI.BAH.RecipeBox.RemoveRecipe);
}

GMI.BAH.RecipeBox.InitializeDraggable = function() {
    $('.recipe-tile .recipe-image, .recipe-tile .recipe-name').draggable(GMI.BAH.RecipeBox.DraggableOptions);
}

GMI.BAH.RecipeBox.InitializeDroppable = function() {
    $('.recipe-box-folder').droppable(GMI.BAH.RecipeBox.DroppableOptions);
}

$(document).ready(function() {
    // grab the user key once
    GMI.BAH.RecipeBox.UserKey = $('span.uk').html(); // user key

    //set current folder ID to 1st one in list - that gets displayed on page load by default
    GMI.BAH.RecipeBox.Folder.ID = $('li.recipe-box-folder').first().attr('rel');

    GMI.BAH.RecipeBox.InitializeEvents();

    $("#folder-edit").sortable();

    // set up drag and drop
    GMI.BAH.RecipeBox.InitializeDraggable();
    GMI.BAH.RecipeBox.InitializeDroppable();

});

