﻿/// <reference name="MicrosoftAjax.js"/>

Type.registerNamespace("WebControls");

WebControls.Grid = function(element) {
    WebControls.Grid.initializeBase(this, [element]);

    this._startRow = 1;
    this._pageSize = 10;    
    this._items = null;
    this._selectedItem = null;
    this._filter = null;
    this._foreignID = null;
}

WebControls.Grid.prototype = {
    initialize: function() {
        WebControls.Grid.callBaseMethod(this, 'initialize');

        var that = this;

//         if (this._serviceProxy && this._daoName && this._loadOnInit) {
        if (this._serviceProxy && this._daoName) {
                
            this._tableView.add_itemSave(
                function(sender, e) {
                    that.saveItem(e.item);
                }
            );

            this._tableView.add_itemDelete(
                function(sender, e) {
                    that.deleteItem(e.item);
                }
            );

            if (this._loadOnInit) {
                this.loadGrid();
            }
            
        }
        
        if (this._allowEdit) {
            this.add_addButtonClicked(
                function(sender, e) {
                    // alert("add");
                    that._tableView.setupNewItem();
                }
            );
        }

        // Re-raise these events (and handle as appropriate)
        this._tableView.add_itemClicked( function(sender, e) { that._raiseEvent("itemClicked", e); } );
        this._tableView.add_itemUp( function(sender, e) {
            that._raiseEvent("itemUp", e);
            that.moveItemUp(e.id);
        } );
        this._tableView.add_itemDown( function(sender, e) {
            that._raiseEvent("itemDown", e);
            that.moveItemDown(e.id);
        } );
        this._tableView.add_itemToStart( function(sender, e) {
            that._raiseEvent("itemToStart", e);
            that.moveItemToStart(e.id);
        } );
        this._tableView.add_itemToEnd( function(sender, e) {
            that._raiseEvent("itemToEnd", e);
            that.moveItemToEnd(e.id);
        } );
        this._tableView.add_showButton( function(sender, e) {
            that._raiseEvent("showButton", e);
        } );
        this._tableView.add_buttonClicked( function(sender, e) {
            that._raiseEvent("buttonClicked", e);
        } );
        this._tableView.add_generateCustomTd( function(sender, e) {
            that._raiseEvent("generateCustomTd", e);
        } );

        if (this._addButton) {
            this._addButton.add_buttonClicked(
                function(sender, e) { 
                    that.deselectRow();
                    that._raiseEvent("addButtonClicked", {});                    
                }
            );
        }
        if (this._deleteButton) {
            this._deleteButton.add_buttonClicked(
                function(sender, e) { that._raiseEvent("deleteButtonClicked", {}); }
            );
        }
        if (this._paging) {
            this._previousPageButton.add_buttonClicked(
                function(sender, e) { that.pagePrevious(); }
            );
            this._nextPageButton.add_buttonClicked(
                function(sender, e) { that.pageNext(); }
            );
        }                
        
        this.showMain();

    },
    dispose: function() {
        //Add custom dispose actions here
        WebControls.Grid.callBaseMethod(this, 'dispose');
    },
    
    showLoading: function() {
        this._panelSet.showPanel(this._loadingPanelID);
    },
    showMain: function() {
        this._panelSet.showPanel(this._mainPanelID);
    },
    
    moveItemToStart: function(id) {
        var that = this;
        var serviceProxy = eval(that._serviceProxy);
        
        // Different web service calls if we're passing foreignID
        if (this._foreignFieldName) {                                
            serviceProxy.MoveItemToStartByForeignID(
                this._daoName,
                id,
                function(result) {
                    that.loadGrid(id);
                    that._raiseEvent('itemClicked', { id: id });
                },
                webServiceError
            );
        } else {
            serviceProxy.MoveItemToStart(
                this._daoName,
                id,
                function(result) {
                    that.loadGrid(id);
                    that._raiseEvent('itemClicked', { id: id });
                },
                webServiceError
            );                               
        }
    },

    moveItemUp: function(id) {
        var that = this;
        var serviceProxy = eval(that._serviceProxy);
        
        // Different web service calls if we're passing foreignID
        if (this._foreignFieldName) {                                
            serviceProxy.MoveItemUpByForeignID(
                this._daoName,
                id,
                function(result) {
                    that.loadGrid(id);
                    that._raiseEvent('itemClicked', { id: id });
                },
                webServiceError
            );       
        } else {
            serviceProxy.MoveItemUp(
                this._daoName,
                id,
                function(result) {
                    that.loadGrid(id);
                    that._raiseEvent('itemClicked', { id: id });
                },
                webServiceError
            );                               
        }
    },
    
    moveItemDown: function(id) {
        var that = this;
        var serviceProxy = eval(that._serviceProxy);
        
        // Different web service calls if we're passing foreignID
        if (this._foreignFieldName) {                                                        
            serviceProxy.MoveItemDownByForeignID(
                this._daoName,
                id,
                function(result) {
                    that.loadGrid(id);
                    that._raiseEvent('itemClicked', { id: id });
                },
                webServiceError
            );
        } else {
            serviceProxy.MoveItemDown(
                this._daoName,
                id,
                function(result) {
                    that.loadGrid(id);
                    that._raiseEvent('itemClicked', { id: id });
                },
                webServiceError
            );                        
        }
    },
    
    moveItemToEnd: function(id) {
        var that = this;
        var serviceProxy = eval(that._serviceProxy);
        
        // Different web service calls if we're passing foreignID
        if (this._foreignFieldName) {                                
            serviceProxy.MoveItemToEndByForeignID(
                this._daoName,
                id,
                function(result) {
                    that.loadGrid(id);
                    that._raiseEvent('itemClicked', { id: id });
                },
                webServiceError
            );
        } else {
            serviceProxy.MoveItemToEnd(
                this._daoName,
                id,
                function(result) {
                    that.loadGrid(id);
                    that._raiseEvent('itemClicked', { id: id });
                },
                webServiceError
            );
        }
    },

    get_selectedItem: function() {
        return this._tableView.get_selectedItem();
    },

    get_selectedID: function() {
        return this._tableView.get_selectedID();
    },

    set_selectedID: function(id) {
        this._tableView.set_selectedID(id);
    },

    pagePrevious: function() {
        this._startRow -= this._pageSize;
        if (this._startRow < 1) { this._startRow = 1; }
        this.loadGrid();
    },
    pageNext: function() {
        var itemCount = this._tableView.get_itemCount();
        if (itemCount == null || (this._startRow + this._pageSize) <= itemCount) {
            this._startRow += this._pageSize;
        }
        this.loadGrid();
    },
    
    processGetPageCallback: function(result) {    
        var rows = result.Rows;
        if (this._paging) {
            if (rows.length > 0) {
                this._startRow = result.StartRow;
                this._itemFromLabel.set_value(this._startRow);                                    
            } else {
                this._startRow = 1;
                this._itemFromLabel.set_value(0);
            }
            this._itemToLabel.set_value(this._startRow + rows.length - 1);
            this._itemCountLabel.set_value(result.TotalRowCount);
        }
        this._tableView.set_itemCount(result.TotalRowCount);
        this._tableView.set_itemList(rows);        
        this._raiseEvent("gridLoaded", {});
        this.showMain();
    },

    clearGrid: function() {
        this._tableView.set_itemList([]);
    },

    loadGrid: function(id) {
        var that = this;

        var serviceProxy = eval(this._serviceProxy);

        if (this._showLoadingPanel) {
            this.showLoading();
        }

        // Different web service calls if we're passing foreignID
        if (this._foreignFieldName) {        

            // Don't load if no foreignID
            if (this._foreignID > 0) {
                if (!this._paging) {
                    serviceProxy.GetListByForeignID(
                        this._daoName,
                        this._foreignID,
                        this._filter || null,  // null,  // this._filterPanel.get_filter(),
                        function(result) {                  
                            that._tableView.set_itemCount(result.length);      
                            that._tableView.set_itemList(result);
                            that.showMain();
                            if (id > 0) {
                                that.set_selectedID(id);
                            }
                            that._raiseEvent("gridLoaded", {});
                        },
                        webServiceError
                    );
                } else if (id > 0) {
                    serviceProxy.GetPageContainingItemByForeignID(
                        this._daoName,
                        this._foreignID,
                        id,
                        this._pageSize,
                        null,
                        null,
                        this._filter || null,  // null, // this._filterPanel.get_filter(),
                        function(result) {                        
                            that.processGetPageCallback(result);                            
                            that.set_selectedID(id);
                        },
                        webServiceError
                    );
                } else {
                    serviceProxy.GetPageByForeignID(
                        this._daoName,
                        this._foreignID,
                        this._startRow,
                        this._pageSize,
                        null,
                        null,
                        this._filter || null,  // null,  // this._filterPanel.get_filter(),
                        function(result) {
                            that.processGetPageCallback(result);
                        },
                        webServiceError
                    );
                }                
            } else {
                programError("No foreignID for grid " + this.get_id());
            }
        } else {
            if (id > 0) {
                serviceProxy.GetPageContainingItem(
                    this._daoName,
                    id,
                    this._pageSize,
                    null,
                    null,
                    this._filter || null,  // null, // this._filterPanel.get_filter(),
                    function(result) {
                        that.processGetPageCallback(result);
                    },
                    webServiceError
                );
            } else {
                serviceProxy.GetPage(
                    this._daoName,
                    this._startRow,
                    this._pageSize,
                    null,
                    null,
                    this._filter || null,  // null,  // this._filterPanel.get_filter(),
                    function(result) {
                        that.processGetPageCallback(result);
                    },
                    webServiceError
                );
            }
        }

    },
    
    saveItem: function(item) {
    
        var that = this;
    
//        var item = this.get_item();
//        
//        if (this.validateEditControls()) {        
//            this._raiseEvent("itemSave", {item: item});

//            if (this._serviceProxy) {
//                       
                var serviceProxy = eval(this._serviceProxy);
            
                // if (item.ID > 0) {
                if (item[this._pkFieldName] > 0) {
                    serviceProxy.Update(
                        this._daoName,
                        item,
                        function(result) {
                            // var item = result;                            
                            // that.set_item(item);
                            that.loadGrid();
//                            that._raiseEvent("itemSaved", {id: that.get_itemID(), item: item});
//                            if (that._formView.get_messageLabel()) {
//                                that._formView.get_messageLabel().flashMessage("Item Saved");
//                            }
                        },
                        webServiceError
                    );
                } else {
                    serviceProxy.Insert(
                        this._daoName,
                        item,
                        function(result) {
                            // that.set_itemID(result);
                            // item.ID = result;
                            item[this._pkFieldName] = result;
                            that.loadGrid();
//                            that._raiseEvent("itemSaved", {id: that.get_itemID(), item: item});
//                            if (that._formView.get_messageLabel()) {
//                                that._formView.get_messageLabel().flashMessage("Item Saved");
//                            }
                        },
                        webServiceError
                    );   
                }
//            }
//            
//            // Not sure if we should go back to the view mode
//            // here automatically or rely on the caller to do that
//            // Could be optional based on a parameter?
//            // (Also we are not necessarily going back to 
//            // view mode anyway, eg if it's being used a a filter panel etc)
//            
//        } else {
//            this.showMessage("One or more fields are invalid");
//        }        
    
    },

    deleteItem: function(item) {

        var that = this;
    
//        var item = this.get_item();
//        
////        // Is this the right place to raise this or should
////        // it be done after the validateControls?
////        this._raiseEvent("saveClicked", {item: item});
//        
//        if (this.validateEditControls()) {        
//            this._raiseEvent("itemDelete", {item: item});

//            if (this._serviceProxy) {
//                       
                var serviceProxy = eval(this._serviceProxy);
            
                serviceProxy.Delete(
                    this._daoName,
                    item,
                    function(result) {
                        that.loadGrid();
//                        // var item = result;                            
//                        // that.set_item(item);
//                        that.set_itemID(null);
//                        that.set_item({});
//                        // that.loadItem();
//                        that.showStartView();
//                        that._raiseEvent("itemDeleted", {});
//                        if (that._formView.get_messageLabel()) {
//                            that._formView.get_messageLabel().flashMessage("Item Deleted");
//                        }
                    },
                    webServiceError
                );
//            }
//            
//            // Not sure if we should go back to the view mode
//            // here automatically or rely on the caller to do that
//            // Could be optional based on a parameter?
//            // (Also we are not necessarily going back to 
//            // view mode anyway, eg if it's being used a a filter panel etc)
//            
//        } else {
//            this.showMessage("One or more fields are invalid");
//        }        
    },

    get_filter: function() {
        return this._filter;
    },
    set_filter: function(filter) {
        this._filter = filter;
    },
    
    deselectRow: function() {
        this._tableView.deselectRow();
    },
    
    // Need special setter for foreignID
    // to set foreignID of tableView if
    // foreignID set dynamically in JS
    get_foreignID: function() {
        return this._foreignID;
    },    
    set_foreignID: function(value) {
        this._foreignID = value;
        if (this._tableView) {
            this._tableView.set_foreignID(value);
        }
    }

}
WebControls.Grid.createProperty("panelSet");
WebControls.Grid.createProperty("loadingPanelID");
WebControls.Grid.createProperty("mainPanelID");
WebControls.Grid.createProperty("tableView");
WebControls.Grid.createProperty("columns");
WebControls.Grid.createProperty("serviceProxy");
WebControls.Grid.createProperty("daoName");
WebControls.Grid.createProperty("pkFieldName");
WebControls.Grid.createProperty("foreignFieldName");
// WebControls.Grid.createProperty("foreignID");
WebControls.Grid.createProperty("loadOnInit");
WebControls.Grid.createProperty("allowEdit");
WebControls.Grid.createProperty("paging");
WebControls.Grid.createProperty("orderable");
WebControls.Grid.createProperty("itemFromLabel");
WebControls.Grid.createProperty("itemToLabel");
WebControls.Grid.createProperty("itemCountLabel");
WebControls.Grid.createProperty("addButton");
WebControls.Grid.createProperty("deleteButton");
WebControls.Grid.createProperty("previousPageButton");
WebControls.Grid.createProperty("nextPageButton");
WebControls.Grid.createProperty("showLoadingPanel");
// WebControls.Grid.createProperty("itemCount");  // Needed?
// WebControls.Grid.createProperty("rowCssClass");
// WebControls.Grid.createProperty("selectedRowCssClass");

WebControls.Grid.createEvent("itemClicked");
WebControls.Grid.createEvent("itemToStart");
WebControls.Grid.createEvent("itemUp");
WebControls.Grid.createEvent("itemDown");
WebControls.Grid.createEvent("itemToEnd");
WebControls.Grid.createEvent("addButtonClicked");
WebControls.Grid.createEvent("deleteButtonClicked");
WebControls.Grid.createEvent("previousPageButtonClicked");
WebControls.Grid.createEvent("nextPageButtonClicked");
WebControls.Grid.createEvent("showButton");
WebControls.Grid.createEvent("buttonClicked");
WebControls.Grid.createEvent("generateCustomTd");
WebControls.Grid.createEvent("gridLoaded");

WebControls.Grid.registerClass('WebControls.Grid', Sys.UI.Control);

if (typeof (Sys) !== 'undefined') Sys.Application.notifyScriptLoaded();

if(typeof(Sys)!=='undefined')Sys.Application.notifyScriptLoaded();