﻿

/*
    <div class="Pager">
        <table border="0">
            <tr>
                <td>
                    <div class="PagerLinks" /></td>
                <td>Go to Page:</td>
                <td><input type="text" class="PagerGoToPage" style="width: 35px; height: 13px;" autocomplete="off" /></td>
                <td><img class="PagerGoButton" src="../Resources/Images/button_go.gif" width="41" height="18" alt="GO" /></td>
            </tr>
        </table>
    </div>
*/

C4.SitePager = function(PagerDivClass, linkDivClass, PageClass, GoToPageInputClass, GoToPageButtonClass, RecordClass, PageCountDivClass, RecordCount){

    this.PagerDivClass = PagerDivClass;
    this.linkDivClass = linkDivClass;
    this.PageClass = PageClass;
    this.GoToPageInputClass = GoToPageInputClass;
    this.GoToPageButtonClass = GoToPageButtonClass;
    this.RecordClass = RecordClass;
    this.RecordCount = 0;    
    this.PageCountDivClass = PageCountDivClass;
    this.PagerDisplaySize = 10;
    this.currentPageIndex = 0; 
    this.RecordCount = RecordCount;
    
    this.linkTemplate = new Ext.Template(
        '<a href="" class = "activeLink" onclick="return false;" id="PagerLink_{div}_{page}">',
            '{label}',
        '</a>&nbsp;&nbsp;'
    );

         
};
Ext.extend(C4.SitePager, Ext.util.Observable, {
    Initialize : function(){
    
        this.InitPages();
        if( this.pages.length > 1 ){
            
            try {
                for (var i = 0; i < this.pages.length; i++) {
                    if (this.pages[i].dom.attributes.DefaultToThisPage.value == '1') {
                        this.SwitchToPage(i, false);
                    }
                }
            } catch (e) {
                this.SwitchToPage(this.currentPageIndex);
            }
            
        
        }
    },
    
    InitPages:function()
    {
        this.pagerDivs = Ext.select('.' + this.PagerDivClass).elements;
        for (var i = 0; i < this.pagerDivs.length; i++) {
            this.pagerDivs[i] = Ext.get(this.pagerDivs[i]);
        }

        this.pagerLinkDivs = Ext.select('.' + this.linkDivClass).elements;
        for (var i = 0; i < this.pagerLinkDivs.length; i++) {
            this.pagerLinkDivs[i] = Ext.get(this.pagerLinkDivs[i]);
            this.pagerLinkDivs[i].update('');
        }

        this.GoToPageInputs = Ext.select('.' + this.GoToPageInputClass).elements;
        for (var i = 0; i < this.GoToPageInputs.length; i++) {
            this.GoToPageInputs[i] = Ext.get(this.GoToPageInputs[i]);
        }

        this.GoToPageButtons = Ext.select('.' + this.GoToPageButtonClass).elements;
        for (var i = 0; i < this.GoToPageButtons.length; i++) {
            this.GoToPageButtons[i] = Ext.get(this.GoToPageButtons[i]);
        }

        this.PageCountDivs = Ext.select('.' + this.PageCountDivClass).elements;
        for (var i = 0; i < this.PageCountDivs.length; i++) {
            this.PageCountDivs[i] = Ext.get(this.PageCountDivs[i]);
        }

        this.addEvents({"pagechange": true });
    
     
        this.GenerateLinks();
        
         for (var i = 0; i < this.GoToPageInputs.length; i++) 
        {
            var n = new Ext.form.NumberField({ el: this.GoToPageInputs[i],
                                                                allowDecimals: false,
                                                                allowNegative: false,
                                                                maxValue: this.pages.length,
                                                                minValue: 1,
                                                                allowBlank: true
                                                        });
            n.applyTo(this.GoToPageInputs[i]);
            n.on('focus', this.ClearAllInputs, this);
            this.GoToPageInputs[i] = n;
        }
                
        for (var i = 0; i < this.GoToPageButtons.length; i++) 
        {
            this.GoToPageButtons[i].on('click', this.onGoButtonClick, this);
        } 
        
        
        this.RecordCountCalc = Ext.select('.' + this.RecordClass).elements.length;
        var countString = '';
        
        if (this.RecordCount) {
            countString = this.RecordCount + " item";
            if (this.RecordCount != 1) { countString += "s"; }
        } else {
            countString = this.RecordCountCalc + " item";
            if (this.RecordCountCalc != 1) { countString += "s"; }
        }
    
        countString += " found on " + this.pages.length + " page";
        if (this.pages.length != 1) { countString += "s"; }
        countString += ".";
        
        for (var i = 0; i < this.PageCountDivs.length; i++) 
        {
            this.PageCountDivs[i].dom.textContent = countString;
        } 
        
        
        
       
    },
    GenerateLinks: function()
    {
            this.pagerLinkDivs = Ext.select('.' + this.linkDivClass).elements;
            for (var i = 0; i < this.pagerLinkDivs.length; i++) {
                this.pagerLinkDivs[i] = Ext.get(this.pagerLinkDivs[i]);
                this.pagerLinkDivs[i].update('');
            }
        
            this.pages = Ext.select('.' + this.PageClass).elements;
                        
            // Calculate From and To pages.
            var from = 0;
            var to = this.pages.length;
            if( this.currentPageIndex + 1 <=  Math.ceil(this.PagerDisplaySize/2))
            {
                if ( this.pages.length >=  this.PagerDisplaySize)
                {
                    to = this.PagerDisplaySize;
                }
            }
            else
            {
                  from = this.currentPageIndex  - Math.ceil(this.PagerDisplaySize/2);
                  to = this.currentPageIndex  + Math.ceil(this.PagerDisplaySize/2);
                  if( to >= this.pages.length)
                  {
                    to = this.pages.length;
                  }
                  if( this.pages.length >= this.PagerDisplaySize )
                  {
                      if ( to-from != this.PagerDisplaySize)
                      {
                        from = from - (this.PagerDisplaySize - (to-from));
                      }
                  }
                  else
                  {
                    from = 0;
                  }
            }
            
            if (this.pages.length <=1) 
            {
                for (var i = 0; i < this.pagerDivs.length; i++) 
                {
                    this.pagerDivs[i].setVisibilityMode(Ext.Element.DISPLAY);
                    this.pagerDivs[i].setVisible(false);
                }
            } 
            else 
            {
                this.AttachFirstLinks();
                
                
                for (var i = 0; i < this.pages.length; i++) 
                {
                    this.pages[i] = Ext.get(this.pages[i]);
                    this.pages[i].setVisibilityMode(Ext.Element.DISPLAY);
                    if (i > 0) 
                    {
                        this.pages[i].setVisible(false);
                    }
                }
                
                for( var i = from ; i < to ;i++)
                {
                    for (var j = 0; j < this.pagerLinkDivs.length; j++) 
                    {
                        this.linkTemplate.append(this.pagerLinkDivs[j], {div: j, page: i + 1, label: i + 1});
                        var l = Ext.get('PagerLink_' + j + '_' + (i+1));
                        l.on('click', this.onPagerLinkClick.createDelegate(this, [i]), this);
                    }
                }
                
                this.AttachLastLinks();
                
            } 
        },
    AttachFirstLinks: function() 
    {       
        for (var i = 0; i < this.pagerLinkDivs.length; i++) {
            this.linkTemplate.append(this.pagerLinkDivs[i], {div: i, page: -2, label: '<<'});
            var l = Ext.get('PagerLink_' + i + '_-2');
            l.on('click', this.onPagerLinkClick_First, this);
            
            this.linkTemplate.append(this.pagerLinkDivs[i], {div: i, page: -1, label: '<'});
            var l = Ext.get('PagerLink_' + i + '_-1');
            l.on('click', this.onPagerLinkClick_Previous, this);
            
            this.linkTemplate.append(this.pagerLinkDivs[i], {div: i, page: -5, label: '|'});
            var l = Ext.get('PagerLink_' + i + '_-5');
            l.dom.className="inactiveLink";
        }
    },
    
    
    AttachLastLinks: function() {       
        for (var i = 0; i < this.pagerLinkDivs.length; i++) {
            
            this.linkTemplate.append(this.pagerLinkDivs[i], {div: i, page: -6, label: '|'});
            var l = Ext.get('PagerLink_' + i + '_-6');
            l.dom.className="inactiveLink";
            
            this.linkTemplate.append(this.pagerLinkDivs[i], {div: i, page: -3, label: '>'});
            var l = Ext.get('PagerLink_' + i + '_-3');
            l.on('click', this.onPagerLinkClick_Next, this);
            
            this.linkTemplate.append(this.pagerLinkDivs[i], {div: i, page: -4, label: '>>'});
            var l = Ext.get('PagerLink_' + i + '_-4');
            l.on('click', this.onPagerLinkClick_Last, this);
        }
    },
    
    ClearAllInputs: function() {
        for (var i = 0; i < this.GoToPageInputs.length; i++) {
            this.GoToPageInputs[i].setValue('');
        }
    },
    
    GetGoToPageValue: function() {
        for (var i = 0; i < this.GoToPageInputs.length; i++) {
            if (this.GoToPageInputs[i].isValid() && this.GoToPageInputs[i].getValue() != '') {
                return this.GoToPageInputs[i].getValue();
            }
        }
        return 0;
    },
    
    onPagerLinkClick_First: function() {
        this.SwitchToPage(0);
        return false;
    },
    
    onPagerLinkClick_Previous: function() {
        this.SwitchToPage(Math.max(0, this.currentPageIndex - 1));
        return false;
    },
    
    onPagerLinkClick_Next: function() {
        this.SwitchToPage(Math.min(this.pages.length - 1, this.currentPageIndex + 1));
        return false;
    },
    
    onPagerLinkClick_Last: function() {
        this.SwitchToPage(this.pages.length - 1);
        return false;
    },
    
    onPagerLinkClick: function(pageIndex) {
        this.SwitchToPage(pageIndex);
        return false;
    },
    
    SwitchToPage: function(pageIndex, doRedirect){
        if (typeof(doRedirect) == 'undefined') {
            doRedirect = true;
        }
        
        //Get the history iFrame, and then set the query on it for state.
        var iFrameHistory = Ext.get('paginationHistory');
        if(iFrameHistory != null)
        {
            //Only add history if the page selection changes.
            var location = 'PaginationHistory.htm?pager=' + pageIndex;
            
            //check to ensure that we will be pulling this out of the templates directory.
            var source = parent != null ? parent.location : location;
            var path = source.href.substring(0,source.href.lastIndexOf("/")+1);
            if(path.indexOf('/Templates') == -1)
            {
                location = '/Templates/' + location;
            }
            
            var bIsFrameSet = iFrameHistory != null && iFrameHistory.dom.src.indexOf('PaginationHistory.htm') >= 0;
            if( (!bIsFrameSet && pageIndex != 0) || 
                (bIsFrameSet && iFrameHistory.dom.src.indexOf(location) == -1) )
            {
                iFrameHistory.dom.src = location;
            }
        }
        
        if (doRedirect) {
            try {
                if (this.pages[pageIndex].dom.attributes.Href.value != '') {
                    location.href = this.pages[pageIndex].dom.attributes.Href.value;
                    return;
                }
            } catch (e) {}
        }
        

         if (this.currentPageIndex != pageIndex) {
            this.pages[this.currentPageIndex].setVisible(false);
            this.currentPageIndex = pageIndex;            
            
            
            this.InitPages();
            this.pages[pageIndex].setVisible(true);
            this.fireEvent("pagechange");
        }
        //Make the new current page index inactive
        for (var j = 0; j < this.pagerLinkDivs.length; j++) {
            
            var elName = 'PagerLink_' + j + '_' + (parseInt( this.currentPageIndex )+1);
            var l = Ext.get(elName);
            if(l != null)
            {
                l.dom.className="inactiveLink";
            }
            
            if( this.currentPageIndex <= 0 ) 
            {
                //MovePrevious
                var l = Ext.get('PagerLink_' + j + '_-1');
                l.dom.className="inactiveLink";
                
                //MoveFirst
                var l = Ext.get('PagerLink_' + j + '_-2');
                l.dom.className="inactiveLink";
            }
            
            if( this.currentPageIndex >= this.pages.length-1)
            {
                //MoveNext 
                var l = Ext.get('PagerLink_' + j + '_-3');
                l.dom.className="inactiveLink";
                
                //MoveLast
                var l = Ext.get('PagerLink_' + j + '_-4');
                l.dom.className="inactiveLink";
            }
        }
      
    },
    
    IFrameCallback : function(search)
    {
        //Called back from PaginationHistory.htm.  this will get called into with the query string
        // that was used within the SwithToPage() function.
        //
        // ex url: http://localhost/PaginationHistory.html?pager=2
        
        var tokens = search.split('=');
        var pageIndex = 0;
        for(var i = 0 ; (i + 1) < tokens.length ; i+=2)
        {
            var key = tokens[i];
            var value = tokens[i+1];
            if(key == 'pager')
            {
                pageIndex = value;
            }
        }
        
        //check to ensure that the dom is ready before we allow the call to pass through.
        Ext.onReady(function(){
            SitePager.SwitchToPage(pageIndex);
        });
    },
    
    onGoButtonClick: function() {
        var v = this.GetGoToPageValue();
        if (v > 0) {
            this.SwitchToPage(v - 1);
            this.ClearAllInputs();
        }
    }
    
    
});