﻿Type.registerNamespace("CorvusCMS.UI");

CorvusCMS.UI.PagedListControl = function(element) {
    CorvusCMS.UI.PagedListControl.initializeBase(this, [element]);

    this._id = null;

    this._itemsPerPage = 10;
    this._maxItemsPerPage = 20;
    this._maxNumberOfPages = null;
    this._totalCount = null;
    this._currentPage = 1;
    this._pagedList = null;

    this._webRequest = null;

    this._onClickHandler = null;
    this._onDblClickHandler = null;

    this._dataSourceHandler = null;
    this._itemDataBoundHandler = null;
    this._customCommandHandler = null;
    this._pageChangedHandler = null;
    this._pageChangingHandler = null;
    this._dblClickHandler = null;

    this._enableCaching = true;
    this._cache;

    this._focused = false;
    this._enabled = false;

    this._iconPath = null;

    this._customArgument = null;

    this._listenControl = false;


    this._initialPagedList = null;
    this._arraylist = null;


    //    this._dcTime = 250;    // doubleclick time
    //    this._dcDelay = 100;   // no clicks after doubleclick
    //    this._dcAt = 0;        // time of doubleclick
    //    this._savEvent = null; // save Event for handling doClick().
    //    this._savEvtTime = 0;  // save time of click event.
    //    this._savTO = null;    // handle of click setTimeOut

}

CorvusCMS.UI.PagedListControl.prototype = {

    initialize: function() {
        CorvusCMS.UI.PagedListControl.callBaseMethod(this, 'initialize');

        if (this._dataSourceHandler)
            this.add_event('dataSource', Function.createDelegate(this, this._dataSourceHandler));

        if (this._pageChangingHandler)
            this.add_event('pageChanging', Function.createDelegate(this, this._pageChangingHandler));

        if (this._pageChangedHandler)
            this.add_event('pageChanged', Function.createDelegate(this, this._pageChangedHandler));

        if (this._itemDataBoundHandler)
            this.add_event('itemDataBound', Function.createDelegate(this, this._itemDataBoundHandler));

        if (this._customCommandHandler)
            this.add_event('customCommand', Function.createDelegate(this, this._customCommandHandler));

        if (this._dblClickHandler)
            this.add_event('dblClick', Function.createDelegate(this, this._dblClickHandler));

        if (this._enableCaching) {
            this._cache = new Hashtable();

            if (this._initialPagedList)
                this._cache.put(1, cfw_cast(this._initialPagedList));
        }

        this._onClickHandler = Function.createDelegate(this, this._onControlClick);

        if (this._listenControl)
            $addHandler(this.get_element(), "click", this._onClickHandler);
        else
            $addHandler(document.body, "click", this._onClickHandler);


        if (this._dblClickHandler) {

            this._onDblClickHandler = Function.createDelegate(this, this._onControlDblClick);

            if (this._listenControl)
                $addHandler(this.get_element(), "dblclick", this._onDblClickHandler);
            else
                $addHandler(document.body, "dblclick", this._onDblClickHandler);
        }
    },

    dispose: function() {


        if (this._dblClickHandler) {
            $removeHandler(this.get_element(), "dblclick", this._onDblClickHandler);
        }
        if (this._listenControl)
            $removeHandler(this.get_element(), "click", this._onClickHandler);
        else {
            if (hasEvent(document.body, "click"))
                $removeHandler(document.body, "click", this._onClickHandler);
        }

        //        if (this._pageChangedHandler)
        //            this.remove_event('pageIndexChanged', this._pageChangedHandler);

        //        if (this._itemDataBoundHandler)
        //            this.remove_event('itemDataBound', this._itemDataBoundHandler);

        //        if (this._customCommandHandler)
        //            this.remove_event('customCommand', this._customCommandHandler);

        CorvusCMS.UI.PagedListControl.callBaseMethod(this, 'dispose');

    },

    get_id: function() {
        return this._id;
    },

    set_id: function(value) {
        if (this._id !== value) {
            this._id = value;
        }
    },

    get_enableCaching: function() {
        return this._enableCaching;
    },

    set_enableCaching: function(value) {
        if (this._enableCaching !== value) {
            this._enableCaching = value;
        }
    },

    get_webRequest: function() {
        return this._webRequest;
    },

    set_webRequest: function(value) {
        if (this._webRequest !== value) {

            if (this._webRequest)
                this._webRequest.get_executor().abort();

            this._webRequest = value;

            //this._tbody.style.opacity = "0.65";
        }
    },

    get_pageChangedHandler: function() {
        return this._pageChangedHandler;
    },

    set_pageChangedHandler: function(value) {
        if (this._pageChangedHandler !== value) {
            this._pageChangedHandler = value;
        }
    },

    get_pageChangingHandler: function() {
        return this._pageChangingHandler;
    },

    set_pageChangingHandler: function(value) {
        if (this._pageChangingHandler !== value) {
            this._pageChangingHandler = value;
        }
    },

    get_dataSourceHandler: function() {
        return this._dataSourceHandler;
    },

    set_dataSourceHandler: function(value) {
        if (this._dataSourceHandler !== value) {
            this._dataSourceHandler = value;
        }
    },

    get_customCommandHandler: function() {
        return this._customCommandHandler;
    },

    set_customCommandHandler: function(value) {
        if (this._customCommandHandler !== value) {
            this._customCommandHandler = value;
        }
    },

    get_itemDataBoundHandler: function() {
        return this._itemDataBoundHandler;
    },

    set_itemDataBoundHandler: function(value) {
        if (this._itemDataBoundHandler !== value) {
            this._itemDataBoundHandler = value;
        }
    },

    get_itemsPerPage: function() {
        return this._itemsPerPage;
    },

    set_itemsPerPage: function(value) {
        this._itemsPerPage = value;
    },

    get_totalCount: function() {
        return this._totalCount;
    },

    set_totalCount: function(value) {
        this._totalCount = value;
    },

    get_maxItemsPerPage: function() {
        return this._maxItemsPerPage;
    },

    set_maxItemsPerPage: function(value) {
        this._maxItemsPerPage = value;
    },

    get_maxNumberOfPages: function() {
        return this._maxNumberOfPages;
    },

    get_currentPage: function() {
        return this._currentPage;
    },

    set_currentPage: function(value) {
        this._currentPage = value;
    },

    get_pagedList: function() {
        return this._pagedList;
    },

    set_pagedList: function(value) {
        if (this._pagedList !== value) {
            this._pagedList = value;
        }
    },

    get_customArgument: function() {
        return this._customArgument;
    },

    set_customArgument: function(value) {
        if (this._customArgument !== value) {
            this._customArgument = value;
        }
    },

    get_enabled: function() {
        return this._enabled;
    },

    set_enabled: function(value) {
        if (this._enabled !== value) {
            this._enabled = value;
        }
    },

    get_focused: function() {
        return this._focused;
    },

    set_focused: function(value) {
        if (this._focused !== value) {
                this._focused = value;
        }
    },

    get_iconPath: function() {
        return this._iconPath;
    },

    set_iconPath: function(value) {
        if (this._iconPath !== value) {
            this._iconPath = value;
        }
    },

    get_listenControl: function() {
        return this._listenControl;
    },

    set_listenControl: function(value) {
        if (this._listenControl !== value) {
            this._listenControl = value;
        }
    },

    get_dblClickHandler: function() {
        return this._dblClickHandler;
    },

    set_dblClickHandler: function(value) {
        if (this._dblClickHandler !== value) {
            this._dblClickHandler = value;
        }
    },

    get_initialPagedList: function() {
        return this._initialPagedList;
    },

    set_initialPagedList: function(value) {
        if (this._initialPagedList !== value) {
            this._initialPagedList = value;
        }
    },

    get_arrayList: function() {
        return this._arrayList;
    },

    set_arrayList: function(value) {
        if (this._arrayList !== value) {
            this._arrayList = value;
        }
    },


    _setWebRequest: function(webRequest) {
        this.set_enabled(false);
        this.set_webRequest(webRequest);
    },

    _onNextPage: function() {

        if (this.get_currentPage() == this.get_maxNumberOfPages())
            return;

        this._onPage(this.get_currentPage() + 1);
    },

    _onPrevPage: function() {

        if (this.get_currentPage() == 1)
            return;

        this._onPage(this.get_currentPage() - 1);
    },

    onFirstPage: function(clearCache) {

        if (arguments.length > 0)
            if (this._enableCaching && clearCache)
            this.invalidateCache();

        this._onPage(1);
    },

    _onLastPage: function() {

        if (this.get_currentPage() == this.get_maxNumberOfPages())
            return;

        this._onPage(this.get_maxNumberOfPages());
    },

    _getArgs: function(pageNumber) {
        var args = new CorvusCMS.UI.PageIndexChangedArgs(this.get_currentPage(), pageNumber,
             Function.createDelegate(this, this._onSucceded),
              Function.createDelegate(this, this._onFail),
              this.get_itemsPerPage(),
              Function.createDelegate(this, this._setWebRequest));

        if (this.get_customArgument)
            args.set_customArgument(this.get_customArgument());

        return args;
    },

    _onPage: function(pageNumber) {

        this._raiseEvent('pageChanging', this._getArgs(pageNumber));
        this.set_currentPage(pageNumber);

        if (this._arrayList) {
            this._onSucceded(this.getPageFromArray(this._arrayList), this.get_customArgument());
            return;
        }
        if (this._enableCaching) {
            var pl = this._cache.get(pageNumber);
            if (pl) {
                this._onSucceded(pl, this.get_customArgument());
                return;
            }
        }

        this._raiseEvent('dataSource', this._getArgs(pageNumber));
    },

    goToPage: function(pageNumber) {
        if (arguments.length > 1)
            if (this._enableCaching && arguments[1])
                this.invalidateCache();
            
        this._onPage(pageNumber);
    },

    refreshPage: function() {

        this.invalidateCache(this.get_currentPage());

        this._onPage(this.get_currentPage());
    },

    _reloadPage: function() {

        this._onPage(this.get_currentPage());
    },

    _onSucceded: function(pagedList, customArgument, avoidCache) {

        if (pagedList.NumberOfPages && pagedList.CurrentPage > pagedList.NumberOfPages) {
            this._onPage(pagedList.NumberOfPages); //lastPage

            return;
        }

        if (customArgument)
            this.set_customArgument(customArgument);

        this.set_pagedList(pagedList);
        this.set_currentPage(pagedList.CurrentPage);
        this._maxNumberOfPages = pagedList.NumberOfPages;
        this._totalCount = pagedList.TotalCount;

        if (!avoidCache)
            this._cache.put(this.get_currentPage(), pagedList);

        this.set_enabled(true);

        this._raiseEvent('pageChanged', this._getArgs(this.get_currentPage()));
    },

    _onFail: function(err) {
        this.set_enabled(true);
        this._raiseEvent('pageChanged', this._getArgs(this.get_currentPage()));
    },

    _isControlEvent: function(ev) {

        if (!this.get_enabled())
            return false;

        if (this.get_listenControl())
            return true;

        var bounds = Sys.UI.DomElement.getBounds(this.get_element());

        var posx = 0;
        var posy = 0;

        if (ev.rawEvent.pageX || ev.rawEvent.pageY) {
            posx = ev.rawEvent.pageX;
            posy = ev.rawEvent.pageY;
        }
        else if (ev.clientX || ev.clientY) {
            posx = ev.clientX + document.body.scrollLeft
			    + document.documentElement.scrollLeft;
            posy = ev.clientY + document.body.scrollTop
			    + document.documentElement.scrollTop;
        }

        if ((bounds.x < posx) && (posx < (bounds.x + bounds.width)))
            if ((bounds.y < posy) && (posy < (bounds.y + bounds.height)))
            return true;

        return false;

    },


    //    _hadDoubleClick: function() {
    //        var d = new Date();
    //        var now = d.getTime();
    //        if ((now - this._dcAt) < this._dcDelay) {
    //            return true;
    //        }
    //        return false;
    //    },


    //    _handleClick: function(ev) {
    //        switch (ev.type) {
    //            case "click":
    //                if (this._hadDoubleClick()) return false;

    //                this._savEvent = ev;
    //                d = new Date();
    //                this._savEvtTime = d.getTime();
    //                this._savTO = setTimeout(Function.createDelegate(this, this._onControlPreClick), this._dcTime);
    //                break;
    //            case "dblclick":
    //                this._onContolDblClick(ev);
    //                break;
    //            default:
    //        }
    //    },

    //    _onControlPreClick: function() {
    //        if (this.savEvtTime - this._dcAt <= 0) {

    //            return false;
    //        }
    //        this._onControlClick(this._savEvent);

    //    },

    //    _onContolDblClick: function(ev) {
    //        var d = new Date();
    //        this._dcAt = d.getTime();
    //        if (this._savTO != null) {
    //            clearTimeout(this._savTO);          // Clear pending Click  
    //            this._savTO = null;
    //        }

    //        this._dblClickHandler(this._savEvent);
    //    },


    _onControlClick: function(ev) {


        if (this._isControlEvent(ev)) {

            var cmd = ev.target.getAttribute("cName");

            if (cmd) {
                switch (cmd) {
                    case "nextPage": this._onNextPage(); break;
                    case "prevPage": this._onPrevPage(); break;
                    case "firstPage": this.onFirstPage(); break;
                    case "lastPage": this._onLastPage(); break;
                    case "refreshPage": this.refreshPage(); break;
                    case "onPage": this._onPage(parseInt(ev.target.getAttribute("cArg"))); break;
                    default:
                        //this.invalidateCache(this.get_currentPage()); ????
                        this._raiseEvent('customCommand', new CorvusCMS.UI.CommandArgs(ev.target, cmd, ev.target.getAttribute("cArg")));
                        return;
                }

                ev.stopPropagation();
                return;
            }

        }
    },

    _onControlDblClick: function(ev) {

        if (this._isControlEvent(ev)) {
            var cmd = ev.target.getAttribute("cName");
            this._raiseEvent('dblClick', new CorvusCMS.UI.CommandArgs(ev.target, cmd, ev.target.getAttribute("cArg")));
        }
    },

    getPageFromArray: function(arr) {

        var pl = new Corvus.Web.PagedList();
        var startIndex = (this.get_currentPage() - 1) * this.get_itemsPerPage();
        pl.Items = arr.slice(startIndex, startIndex + this.get_itemsPerPage());
        pl.NumberOfPages = Math.ceil(arr.length / this.get_itemsPerPage());
        pl.CurrentPage = this.get_currentPage();
        pl.TotalCount = arr.length;

        if (!pl.NumberOfPages)
            pl.NumberOfPages = 1;

        return pl;

    },


    invalidateCache: function(page) {

        if (arguments.length == 0)
            this._cache = new Hashtable();
        else
            this._cache.remove(page);
    },

    _raiseEvent: function(eventName, eventArgs) {

        var handler = this.get_events().getHandler(eventName);

        if (handler) {
            if (!eventArgs) {
                eventArgs = Sys.EventArgs.Empty;
            }
            handler(this, eventArgs);
        }
    },

    add_event: function(eventName, handler) {
        this.get_events().addHandler(eventName, handler);
    },

    remove_event: function(eventName, handler) {
        this.get_events().removeHandler(eventName, handler);
    }

}




CorvusCMS.UI.PagedListControl.registerClass("CorvusCMS.UI.PagedListControl", Sys.UI.Control, Sys.IDisposable);

if(typeof(Sys)!=='undefined')Sys.Application.notifyScriptLoaded();