//handles transition and page control for 
//top page item blocks
//
//

var itemblockPager = new Class.create();

itemblockPager.prototype = {

	initialize: function () {

        if(! $$('div.itemblockPage') ) {
            return;
        }

        //get state from hash
        this.currHash = null;
        
        //get current state
        this.state = this.getLocationHash();

        //refs to the individual page elements
        this.pages = $$('div.itemblockPage');
        this.pageCount = this.pages.length;
        
        //keeps track of where we are and where we are going
        this.pageIndex = 0;
        this.pageCurrent = 0;

        //holds refs to the individual ul pager navs
        this.pageNavs = null;

        //time in secods for the transition duration
        this.transitionDuration = .1;
        
        //holds our navblock refs
       this.navBlocks =  $$('div.itemblockNav');
        
        //enable navigation?
        if(this.pages.length > 1) {
        
            //hide all the pages
            for( i=0; i<this.pages.length; i++) {
                $(this.pages[i]).hide();
            }

            //build the links so we can switch pages easily 
            this.buildPageNavigation();

            //show or hide the next/prev page links
            this.showNextPrevPage();
            
            //show the page nav blocks and setup the observe
            for( i=0; i<this.navBlocks.length; i++) {
                $(this.navBlocks[i]).show();
                $(this.navBlocks[i]).observe('click',  this.clickHandler.bindAsEventListener(this));
            };

            if(this.state['Page']) {
                this.pageCurrent = 0;
                this.pageIndex = (parseInt(this.state['Page']) - 1)
            }

            //check if the bookmark > current page count
            if(this.pageIndex > (this.pageCount - 1)) {
                this.pageIndex = this.pageCount - 1;
            }
            
            this.state['Page'] = this.pageIndex + 1;

            window.location.hash = '#!' + $H(this.state).toQueryString(); 
            this.currHash = window.location.hash;

            this.switchPage({
                newPage: this.pageIndex
            });

            this.startPoll();
        
        }        
    },

    stopPoll: function() {
    
        clearTimeout(this.interval);
    
    },
    
    startPoll: function() {
    
        //start polling for changes of hash
        this.interval = setInterval(function(){ 
        if (this.currHash != window.location.hash) 
        { 
            this.anchorAltered(); 
         } 
        }.bind(this), 500); // check every half second 
    
    },

    anchorAltered: function() {

        this.stopPoll();

        var currState = this.getLocationHash();

        if(currState['Page']) {
            var newPage = parseInt(currState['Page']);

            if(isNaN(newPage)) {
                window.location.hash = this.currHash;
                this.startPoll();
                return;
            }
        
            if(newPage > (this.pages.length) ) {
                window.location.hash = this.currHash;
                this.startPoll();
                return;
            }                
        
            if(newPage <= 0) {
                window.location.hash = this.currHash;
                this.startPoll();
                return;
            }                

            this.state['Page'] = newPage;
      
            //set the hash up 
            window.location.hash = '#!' + $H(this.state).toQueryString(); 
            this.currHash = window.location.hash;
    
            var currPage = this.pageIndex;
            this.pageIndex = newPage - 1;
    
            this.switchPage({
                currPage: currPage,
                newPage: this.pageIndex
            });

        }
        else
        {
            //fix the state
            window.location.hash = this.currHash;            
        }
        
        this.startPoll();

        return;
      
    },

    //returns an array of the state stored in location.hash
    getLocationHash: function () {

        var hash = window.location.hash;

        hash = hash.substr(2);
        hash = hash.replace(/\|/g, '&');
        hash = hash.replace(/\:/g, '=');
        hash = hash.parseQuery();

        return hash;
    
    },

    //handles clicks from the navblocks
    clickHandler: function(event) {
		var element = event.element(event);

        this.stopPoll();
        
		if( (element.tagName).toLowerCase() != "a") {
		    element = element.up('a');
		}
		
		var relAttr = element.readAttribute('rel');

        if (relAttr == "prev") {
				this.prevPage();
		} else if (relAttr == "next") {
				this.nextPage();
		} else if (relAttr == "jumper") {
                this.jumpPage(element);
		}

        this.startPoll();

    },			

    jumpPage: function(element) {
        var id = element.identify();

        id = id.replace(/[^0-9]/g, '');
        
        this.pageCurrent = this.pageIndex;
        this.pageIndex = id - 1;

        this.switchPage({
            currPage: this.pageCurrent, 
            newPage: this.pageIndex
            });

    },

    updateHash: function() {

        this.state['Page'] = this.pageIndex + 1;
        this.currHash = '#!' + $H(this.state).toQueryString(); 
        window.location.hash = this.currHash;
        
    },

    showNextPrevPage: function() {
       
        var currPage = this.pageIndex;
        var nextPage = currPage + 1;

        $$('div.itemblockNav a[rel=prev]').each(function(e) { 
            $(e).setAttribute('href', '#!' + Object.toQueryString({Page: (currPage + 1)})  ); 
        });
        
        $$('div.itemblockNav a[rel=next]').each(function(e) { 
            $(e).setAttribute('href', '#!' + Object.toQueryString({Page: nextPage}) ); 
        });
       
        if( this.pageIndex == 0) {
            $$('div.itemblockNav a[rel=prev]').each(function(e) { $(e).hide(); });
            }
        else
            {
            $$('div.itemblockNav a[rel=prev]').each(function(e) { $(e).show(); 
                });
        }

        if( this.pageIndex == (this.pageCount - 1) ) {
            $$('div.itemblockNav a[rel=next]').each(function(e) { $(e).hide(); });
            }
        else
            {
            $$('div.itemblockNav a[rel=next]').each(function(e) { $(e).show(); });
        }
        
    },

	buildPageNavigation: function () {
        var liTemplate = new Template('<li style="display:inline;"><a href="javascript:" id="jumper_#{pageNumber}" rel="jumper">#{pageNumber}</a></li>');

		var nav = $('itemblockPager');
        var i;
        //generate the jump buttons
        for (i = 1; i <= this.pageCount; i++) {
            $(nav).insert(
                liTemplate.evaluate({pageNumber: i})
                );
        }

        this.pageNavs = $$('ul#itemblockPager li');
        //$(this.pageNavs[0]).addClassName('highlight');
    },

    nextPage: function() {
        
        this.pageCurrent = this.pageIndex;
        this.pageIndex += 1;
        
        if(this.pageIndex > (this.pageCount - 1)) {
            this.pageIndex = this.pageCount - 1;
            }
    
        this.switchPage({
            currPage: this.pageCurrent, 
            newPage: this.pageIndex
            });
    },

    switchPage: function(oArg) {

        if(typeof oArg.currPage !== "undefined") {
            $(this.pageNavs[oArg.currPage]).removeClassName('highlight');
            $(this.pages[oArg.currPage]).hide();
        }
        
        $(this.pages[oArg.newPage]).show();
        $(this.pageNavs[oArg.newPage]).addClassName('highlight');

        this.showNextPrevPage();

        this.updateHash();
  
    },

    prevPage: function() {

        this.pageCurrent = this.pageIndex;
        this.pageIndex -= 1;
        
        if(this.pageIndex < 0 ) {
            this.pageIndex = 0;
            }
    
        this.switchPage({
            currPage: this.pageCurrent, 
            newPage: this.pageIndex
            });
        }
}


document.observe('dom:loaded', function() {
    return new itemblockPager;
});


