var PollListing = function(){
	var dialog,conn,loading,pollHolder,curr,displayPage,pageNav,totalPages;
	return {
		init : function() {
			conn=new Ext.data.Connection();
			pollHolder=Ext.get("pollHolder");
			loading=Ext.get("loading");
			curr=0;
			displayPage=Ext.get("current-page");
			pageNav=Ext.get("pageNav");
			PollListing.refreshState();
			Ext.get("pc-next").on("click",this.nextPage,this);
			Ext.get("pc-prev").on("click",this.prevPage,this);
			Ext.get("pc-first").on("click",this.firstPage,this);
			Ext.get("pc-last").on("click",this.lastPage,this);
		},
		refreshState : function(){
			totalPages=parseInt(document.getElementById("totalPages").value);
			if(totalPages==0) {
				curr=0;
				displayPage.update("Page 0 of 0");
				pageNav.hide();
			}
			else if(curr<totalPages) {
				pageNav.show();
				displayPage.update("Page "+(curr+1)+" of "+totalPages);
			}
			else{
				--curr;
				pageNav.show();
				PollListing.loadItems();
			}
		},
		prevPage : function(e){
			if(curr>0){
				--curr;
				this.loadItems();
			}
		},
		nextPage : function(e){
			if(curr<totalPages-1){
				++curr;
				this.loadItems();
			}
		},
		firstPage : function(e){
			if(curr>0){
				curr=0;
				this.loadItems();
			}
		},
		lastPage : function(e){
			if(curr<totalPages-1){
				curr=totalPages-1;
				this.loadItems();
			}
		},
		loadItems : function(){
			pollHolder.hide();
			loading.setX(pollHolder.getX()+10);
			loading.setY(pollHolder.getY()+10);
			loading.show();
			if(conn.isLoading())conn.abort();
			conn.request({
				url:"/ajax/polls/get.aspx?rand="+Math.random()+"&p="+curr,
				method:"get",
				scope:this,
				callback:function(options,bSuccess,response){
					try {
						if(bSuccess){
							pollHolder.update(response.responseText);
							loading.hide();
							pollHolder.show();
							PollListing.refreshState();
						}
						else throw "exception";
					}
					catch(e){
						Ext.Msg.confirm('','The server encountered an error while loading polls. Try again?',
							function(btn) {if(btn=='yes')PollListing.loadItems();});
					}
				}
			});
		}
};}(); 
Ext.onReady(PollListing.init,PollListing,true);


