﻿/// <reference name="MicrosoftAjax.debug.js" />
/// <reference name="MicrosoftAjaxTimer.debug.js" />
/// <reference name="MicrosoftAjaxWebForms.debug.js" />

/// <reference path="../jquery-1.2.6-vsdoc.js"/>

Type.registerNamespace('SCOTT.CSC.Tools.GroceryList');

SCOTT.CSC.Tools.GroceryList.Application = function(panelId, registrationUrl) 
{   
    var __app = this;
    this.ClientID = panelId;
    this.Selector = '#' + panelId;
    this.Aisles = [];
    this.Items = [];
    this.List = undefined;
    this.Lists = [];
    this.SelectedAisle = undefined;
    this.NextID = 1;
    this.ReadyState = 0;
    this.RegistrationUrl = registrationUrl;
    
    this.HighlightColor = '#e9f6fb';
    this.ErrorColor = '#f55';
    
    this.ListHeight = $('#List').height();
    
    // inheritance (of sorts)
    SCOTT.CSC.Extend(SCOTT.CSC.Tools.GroceryList.Application, SCOTT.CSC.Core);
    
    this.GroceryListService = SCOTT.CSC.Tools.GroceryListService;
    this.GroceryListService.set_defaultUserContext(this);
    this.GroceryListService.set_defaultFailedCallback(this.HandleError);
    
    window.GetPrintContent = function()
    {
        return __app.GetPrintContent();
    };
    
    this.Initialize();
    this.Start();
};

SCOTT.CSC.Tools.GroceryList.Application.prototype =
{
    __type : 'SCOTT.CSC.Tools.GroceryList.Application',
    Start : function()
    {
        var __app = this;
        var context = $(this.Selector);
        
        // disable for unsupported browsers
        if ($.browser.safari && parseFloat($.browser.version, 10) < 3.1)
        {
            alert('Sorry, this version of Safari is not supported. Please upgrade to version 3.1 or later.');
            return;
        }
        else if ($.browser.mozilla && parseFloat($.browser.version, 10) < 1.8)
        {
            // Note: Firefox 2.0 is Mozilla 1.8 and Firefox is Mozilla 1.9.
            alert('Sorry, this version of Firefox is not supported. Please upgrade to version 2.0 or later.');
            return;
        }
        else if ($.browser.msie && parseFloat($.browser.version, 10) < 6.0)
        {
            alert('Sorry, this version of Internet Explorer is not supported. Please upgrade to version 6.0 or later.');
            return;
        }
        
        $(context).before('<div id="LoadStatus" style="display: none;"><span>Loading...</span></div>');
        this.CenterElement($('#LoadStatus').get(0));
        $('#LoadStatus').show();
        
        $('#Aisles .Inner', context).empty();
        $('#ListHeader2 .Inner', context).empty();
        $('#List .Inner', context).empty();
        
        this.LoadData();
        this.AttachControlEvents();
    },
    IncrementReadyState : function()
    {
        var __app = this;
        
        this.ReadyState++;
        if (this.ReadyState === 4)
        {
            $('#LoadStatus').fadeOut(1000, function()
            {
                $('#Application').fadeIn(100, function()
                {
                    var onWelcome = function()
                    {
                        __app.DisplayStatusModal(
                        {
                            title : 'Welcome', 
                            message : 'Please start by creating a list.', 
                            hideDelay : 5000 
                        });
                    };
                    
                    setTimeout(onWelcome, 500);
                });
            });
            this.DisplayStartScreen();
        }
    },
    LoadData : function()
    {
        var __app = this;
        
        var aislesHandler = function(data)
        {
            __app.Aisles = SCOTT.CSC.Tools.GroceryList.Aisle.ConvertAll(data);
            __app.IncrementReadyState();
        };

        this.GroceryListService.GetGroceryAisles(aislesHandler);
        
        var itemsHandler = function(data)
        {
            var items = SCOTT.CSC.Tools.GroceryList.Item.ConvertAll(data);
            var i = 0;
            for (i=0;i<items.length;i++)
            {
                __app.Items[i] = items[i];
            }
            __app.IncrementReadyState();
        };

        this.GroceryListService.GetSharedGroceryItems(itemsHandler);
        
        var listsHandler = function()
        {
            __app.IncrementReadyState();
        };
        
        this.LoadGroceryLists(listsHandler);
        
        var customItemsHandler = function()
        {
            __app.IncrementReadyState();
        };
        
        this.LoadCustomItems(customItemsHandler);
    },
    AttachControlEvents : function()
    {
        var __app = this;
        var context = $(this.Selector);
        
        var onBeforeUnload = function(ev)
        {
            if (__app.List && __app.List.IsDirty)
            {
                var message = 'Your list has not been saved. Do you want to leave without saving?';
                if (typeof evt == 'undefined')
                {
                    evt = window.event;
                }
                if (evt) 
                {
                    evt.returnValue = message;
                }
                return message;
            }
        };
        
        window.onbeforeunload = onBeforeUnload;
        
        var onMyListClicked = function()
        {
            __app.DisplayStartScreen();
        };
        
        $('#MyListsBtn', context).click(function()
        {
            if (__app.RequireAuthentication(onMyListClicked))
            {
                onMyListClicked();
            }
            return false;
        });
        
        var onSave = function()
        {
            if (!__app.List)
            {
                __app.DisplayStatusModal(
                {
                    title : 'Save List',
                    message : 'There are no changes to save.',
                    hideDelay : 3000
                });
                return false;
            }
            
            var execSave = function()
            {
                __app.SaveList();
            };
            
            var onSuccess = function()
            {
                execSave();
            };
            
            if (!__app.RequireAuthentication(onSuccess))
            {
                return false;
            }
            else
            {
                execSave();
                return false;
            }
            return false;
        };
        
        $('#Save').attr('title', 'Save (Ctrl-s)').click(onSave);
        $.hotkeys.add('Ctrl+s', onSave);
        
        var showSaveAsNewModal = function()
        {
            $('#SaveAsNewListModal .tbNewName').val(__app.List.Name);
            $('#SaveAsNewListModal').slideDown(250, function()
            {
                $('#SaveAsNewListModal .tbNewName').focus();
            });
        };
        
        var hideSaveAsNewModal = function()
        {
            $('#SaveAsNewListModal').slideUp(250);
        };
        
        var execSaveAsNew = function()
        {
            var newListName = $('#SaveAsNewListModal input.tbNewName').val();
            // validate new list name (defined and unique)
            if (newListName)
            {
                hideSaveAsNewModal();
                __app.List.Name = newListName;
                __app.List.ID.Value = -1;
                __app.List.IsDirty = true;
                __app.SaveList();
            }
            else
            {
                $('#SaveAsNewListModal input.tbNewName').css('background-color', __app.ErrorColor);
                __app.DisplayStatusModal(
                {
                    title : 'Email List',
                    message : 'Please enter a valid list name.',
                    hideDelay : 4000
                });
            }
            return false;
        };
        
        var onSaveAsNew = function()
        {
            if (!__app.List)
            {
                __app.DisplayStatusModal(
                {
                    title : 'Save As New List',
                    message : 'There are no changes to save.',
                    hideDelay : 3000
                });
                return false;
            }
            
            var execSave = function()
            {
                showSaveAsNewModal();
            };
            
            var onSuccess = function()
            {
                execSave();
            };
            
            if (!__app.RequireAuthentication(onSuccess))
            {
                return false;
            }
            else
            {
                execSave();
            }
            return false;
        };
        
        $('#SaveNew').attr('title', 'Save As New List').click(onSaveAsNew);
        
        $('#SaveAsNewListModal .SaveBtn').click(execSaveAsNew);
        
        $('#SaveAsNewListModal .CancelBtn').click(function()
        {
            hideSaveAsNewModal();
            return false;
        });
        
        $('#SaveAsNewListModal .tbNewName').keydown(function(ev)
        {
            if (ev.keyCode === 13)
            {
                execSaveAsNew();
            }
            else if (ev.keyCode === 27)
            {
                hideSaveAsNewModal();
            }
        });
        
        var onPrint = function()
        {
            if (__app.List)
            {
                var features = 'menubar=1,resizable=1,scrollbars=1';
                var w = window.open('PrintPreview.aspx', 'PrintPreview', features);
                if (w)
                {
                    w.focus();
                }
                else
                {
                    __app.DisplayStatusModal(
                    {
                        title : 'Print List',
                        message : 'Unable to print due to pop-up blocker. Please click "Print" button.',
                        hideDelay : 3000
                    });
                }
            }
            else
            {
                __app.DisplayStatusModal(
                {
                    title : 'Print List',
                    message : 'There is no list open.',
                    hideDelay : 3000
                });
            }
            return false;
        };
        
        $('#Print').attr('title', 'Print (Ctrl-p)').click(onPrint);
        $.hotkeys.add('Ctrl+p', onPrint);
        
        var showEmailModal = function()
        {
            $('#EmailListModal').slideDown(250, function()
            {
                $('input.Name', this).focus();
            });
        };
        
        var hideEmailModal = function(emailSent)
        {
            $('#EmailListModal').slideUp(250, function()
            {
                if (emailSent)
                {
                    __app.DisplayStatusModal(
                    {
                        title : 'Email List',
                        message : 'The email has been sent.',
                        hideDelay : 3000
                    });
                }
            });
            $('#EmailListModal .Name').val('');
            $('#EmailListModal .Email').val('');
            $('#EmailListModal .Comment').val('');
        };
        
        var onEmailThisList = function()
        {
            if (!__app.RequireAuthentication(showEmailModal))
            {
                return false;
            }
            else
            {
                if (__app.List.IsDirty)
                {
                    __app.DisplayStatusModal(
                    {
                        title : 'Email List',
                        message : 'Please save your before emailing.',
                        hideDelay : 3000
                    });
                    return false;
                }
                
                if (__app.List)
                {
                    showEmailModal();
                }
                else
                {
                    __app.DisplayStatusModal(
                    {
                        title : 'Email List',
                        message : 'There is no list open.',
                        hideDelay : 3000
                    });
                }
            }
            return false;
        };
        
        $('#EmailThisList').attr('title', 'Email List').click(onEmailThisList);
        
        $('#EmailListModal .CancelBtn').click(function()
        {
            hideEmailModal();
            return false;
        });
        
        $('#EmailListModal .SendBtn').click(function()
        {
            var fname = $('#EmailListModal .Name').val();
            var femail = $('#EmailListModal .Email').val();
            var comment = $('#EmailListModal .Comment').val();
            var isValid = true;
            var errorMessage = '';
            
            if (!fname)
            {
                isValid = false;
                errorMessage = 'Please enter a name.';
            }
            else if (!femail)
            {
                isValid = false;
                errorMessage = 'Please enter an email.';
            }
            else if (femail.indexOf('@') === -1)
            {
                isValid = false;
                errorMessage = 'Please enter a valid email.';
            }
            
            if (isValid)
            {
                var onSuccess = function()
                {
                    hideEmailModal(true);
                };
                
                var onFailure = function()
                {
                    hideEmailModal(false);
                };
                
                __app.GroceryListService.EmailGroceryList(__app.List, fname, femail, comment, onSuccess, onFailure);
            }
            else
            {
                __app.DisplayStatusModal(
                {
                    title : 'Email List',
                    message : errorMessage,
                    hideDelay : 3000
                });
            }
            return false;
        });
        
        // Fix for IE6 which does not support :hover in CSS
        if ($.browser.msie && $.browser.version === '6.0') 
        {
            $('#Aisles .Aisle').mouseover(function()
            {
                $(this).addClass('AisleHover');
            });
            
            $('#Aisles .Aisle').mouseout(function()
            {
                $(this).removeClass('AisleHover');
            });
        }
        
        $('#CloseBtn').css('cursor', 'pointer').click(function()
        {
            window.close();
            return false;
        });
        
        var onAbout = function()
        {
            __app.DisplayStatusModal(
            {
                title : 'About', 
                message : 'The Grocery List, brought to you by SCOTT Brand.', 
                hideDelay : 10000 }
            );
        };
        
        $.hotkeys.add('Ctrl+Shift+a', onAbout);
        
        var onCredit = function()
        {
            __app.DisplayStatusModal(
            {
                title : 'Credit', 
                message : 'Created by Fullhouse Interactive.', 
                hideDelay : 10000 }
            );
        };
        
        $.hotkeys.add('Ctrl+Shift+c', onCredit);
        
        // Enable drop zone
//        var dropOptions = {
//            accept: '.Item',
//            activeClass: 'droppable-active',
//            hoverClass: 'droppable-hover',
//            drop: function(ev, ui) {
//                var item = __app.GetItemByElementID(ui.draggable.get(0).id);
//                if (item !== undefined)
//                {
//                    __app.AddListItem(item);
//                }
//            }
//        };
//        $('#List').droppable(dropOptions);
    },
    SelectAisle : function(aisle)
    {
        var __app = this;
        var context = $(this.Selector);
        
        if (this.List && aisle && aisle !== this.SelectedAisle)
        {
            this.SelectedAisle = aisle;
            
            var selector = '#Aisle-' + aisle.ID.Value;
            $('#Aisles .SelectedAisle', context).removeClass('SelectedAisle');
            $(selector, context).addClass('SelectedAisle');
            
            __app.SetAisleItems(aisle);
            this.DisplayItems(aisle);
        }
    }
};

// Next load Data and Display

