﻿/// <reference name="MicrosoftAjax.debug.js" />
/// <reference name="MicrosoftAjaxTimer.debug.js" />
/// <reference name="MicrosoftAjaxWebForms.debug.js" />

/// <reference path="../jquery-1.2.6-vsdoc.js"/>

// Data

SCOTT.CSC.Tools.GroceryList.Data = function(){};

SCOTT.CSC.Tools.GroceryList.Data.prototype =
{
    StartNewList : function(promptForName)
    {
        var __app = this;
        
        var list = new SCOTT.CSC.Tools.GroceryList.List();
        list.Name = 'My Grocery List';
        
        var onChangeList = function()
        {
            __app.ChangeList(list);
        };
        
        if (promptForName)
        {
            this.DisplayPromptModal(
            {
                title : 'Create New List', 
                message : 'Please enter the name of your new list.', 
                text : list.Name, 
                okCallback : function(text)
                {
                    list.Name = text;
                    onChangeList();
                }, 
                cancelCallback : function()
                {
                    // do nothing
                } 
            });
        }
        else
        {
            onChangeList();
        }
    },
    ChangeList : function(newList)
    {
        var __app = this;
        
        var execCallback = function()
        {
            __app.List = new SCOTT.CSC.Tools.GroceryList.List(newList.Clone());
            __app.DisplayList();
            
            // if My Lists are still visible, click to first aisle
            if ($('#Items .MyLists').is(':visible'))
            {
                $('#Aisles .Aisle:first').click();
            }
        };
        
        // If the current list is dirty, prompt to save it
        if (this.List && this.List.IsDirty)
        {
            this.DisplayConfirmModal({
                title : 'List Change',
                message : 'Your current list is not saved. Save it now?',
                responseCallback : function(response)
                {
                    if (response)
                    {
                        __app.SaveList();
                    }
                    execCallback();
                }
            });
        }
        else
        {
            execCallback();
        }
    },
    SaveList : function(callback)
    {
        var __app = this;
        var i, item;
        
        if (this.List && this.List.IsDirty)
        {
            var onSuccess = function(list)
            {
                if (list)
                {
                    __app.DisplayStatusModal(
                    {
                        title : 'Save List',
                        message : 'Your list has been saved.',
                        hideDelay : 3000
                    });
                    __app.List = SCOTT.CSC.Tools.GroceryList.List.Convert(list);
                    __app.LoadGroceryLists(function()
                    {
                        __app.UpdateMyLists();
                    });
                    __app.DisplayList();
                }
            };
            
            for (i=0;i<this.List.Items.length;i++)
            {
                this.List.Items[i].__type = 'SCOTT.CSC.Model.Tools.GroceryList.ListItem';
            }
            this.GroceryListService.SaveGroceryList(this.List, onSuccess);
        }
        else
        {
            this.DisplayStatusModal(
            {
                title : 'Save List', 
                message : 'There are no changes to save.', 
                hideDelay : 3000
            });
        }
    },
    DeleteList : function(list)
    {
        var __app = this;
        
        var onDelete = function()
        {
            __app.DisplayStatusModal(
            {
                title : 'Delete List',
                message : 'The list named "' + list.Name + '" has been deleted.',
                hideDelay : 3000
            });
            
            if (__app.List && list.ID.Value === __app.List.ID.Value)
            {
                __app.List = undefined;
                __app.ClearList();
            }
            
            __app.LoadGroceryLists(function()
            {
                __app.UpdateMyLists();
            });
        };
        
        this.GroceryListService.DeleteGroceryList(list, onDelete);
    },
    AddListItem : function(item)
    {
        if (this.List)
        {
            if (this.List.Items.length >= 500)
            {
                this.DisplayStatusModal(
                {
                    title : 'Add List Item', 
                    message : 'This list is now too large. Please create another list.', 
                    hideDelay : 5000
                });
            }
            else
            {
                this.List.IsDirty = true;
                var listItem = this.List.AddItem(item);
                this.DisplayList(listItem);
            }
        }
    },
    RemoveListItem : function(listItem)
    {
        var newItemsList = [];
        var i;
        for (i=0;i<this.List.Items.length;i++)
        {
            if (listItem !== this.List.Items[i])
            {
                newItemsList[newItemsList.length] = this.List.Items[i];
            }
        }
        this.List.IsDirty = true;
        this.List.Items = newItemsList;
    },
    SetAisleItems : function(aisle)
    {
        if (!aisle.Items && this.Items)
        {
            var isMatch = function(item)
            {
                return item.AisleID === aisle.ID.Value;
            };
            aisle.Items = From(this.Items).Where(isMatch).Select("*").GetArray();
        }
    },
    AddCustomItem : function(customItem, aisle)
    {
        // only add the item if it does not exist yet
        var isMatch = function(item)
        {
            return item.ID.Value === customItem.ID.Value;
        };
        var matches = From(this.Items).Where(isMatch).Select("*").GetArray();
        if (matches.length === 0)
        {
            this.Items[this.Items.length] = customItem;
            this.SetAisleItems(aisle);
        }
        
    },
    LoadGroceryLists : function(callback)
    {
        var __app = this;
        var i;
        
        this.Lists = [];
        
        // load the lists individually to avoid exceeding the maximum message size

        var onLoadCount = function(listCount)
        {   
            var loadList = function(currentIndex)
            {   
                if (currentIndex < listCount)
                {
                    var onLoadList = function(list)
                    {
                        __app.Lists[currentIndex] = SCOTT.CSC.Tools.GroceryList.List.Convert(list);
                        loadList(currentIndex + 1);
                    };
                    
                    $('#LoadStatus span').text('Loading list ' + (currentIndex + 1) + ' of ' + listCount + '...');
                    __app.GroceryListService.GetGroceryListByIndex(currentIndex, onLoadList);
                }
                else
                {
                    if (callback && typeof (typeof(callback) === 'function'))
                    {
                        callback();
                    }
                }
            };
            loadList(0);
        };
        
        this.GroceryListService.GetGroceryListsCount(onLoadCount);
    },
    LoadCustomItems : function(callback)
    {
        var __app = this;
        var i;
        
        var onLoad = function(customItems)
        {
            var items = SCOTT.CSC.Tools.GroceryList.Item.ConvertAll(customItems);
            for (i=0;i<items.length;i++)
            {
                __app.Items[__app.Items.length] = items[i];
            }
            
            if (callback && typeof (typeof(callback) === 'function'))
            {
                callback();
            }
        };
    
        this.GroceryListService.GetCustomGroceryItems(onLoad);
    }
};

// Add Utility functions to Application
SCOTT.CSC.Extend(SCOTT.CSC.Tools.GroceryList.Application, 
    SCOTT.CSC.Tools.GroceryList.Data);
