pager = {};
pagers = {};

lang.pager = {
	'es':{next:"Siguiente",
		  prev:"Anterior",
		  load:"Cargando página",
		  page_display:{page:'Página', of:'de'},
		  start: 'Inicio',
		  end: 'Fin'
		  },
	'en':{next:"Next",
		  prev:"Previous",
		  load:"Loading page",
		  page_display:{page:'Page', of:'of'},
		  start: 'Start',
		  end: 'End'
		  }
	};

PagerComponent = Class.create();
PagerComponent.prototype = {
	
	initialize: function(id, app, options, history_update, use_comments, multiple) {
			
			this.id = id;
			this.self = $(this.id);
			this.self.style.display = '';
			this.body = $(this.id+'_body');
			
			this.pager_ob_str = (multiple) ? "pagers['"+this.id+"']" : "pager";
			
			this.setOptions(options);
					
			var s_col = status_color || 'white';
			s_col = this.options.args.color || s_col;
			this.status = new StatusComponent(this.id+'_status_indicator', s_col);
			
			this.top_wrapper = $(this.id+'_upper');
			this.bottom_wrapper = $(this.id+'_lower');
	
			this.historyUpdate = history_update || false;
			this.use_comments = use_comments || false;		
			this.app = app;
			
			if (this.options.type) this.type = this.options.type;
			
			if (typeof(this.options.args) != 'undefined') {
				this.id_target = this.options.args.target || null;	
			}
	
			this.centerStatus();
			
			this.updater = new Updater(this.id, this.app, '', {parent:this});
			
			this.index = {};	
			
			var me = this;
			page_init.scripts[this.id] = function() {
				//me.loadFormat();
			};
			
			this.injectNavigation();
		
	},
	
	onUpdatePage: function() {},
	
	setOptions: function(options) {
		this.options = {
			page_amount: 3,
			cur_page:0,
			index_display:5,
			style:'both',
			format_template:'pager_load_formats',
			args:{}
		};
		Object.extend(this.options, options || {});
		if (console) console.log(this.options.parse_scripts);
	},
	
	genIndexInterface: function(new_total) {	
	
		if (new_total) {
			this.options.total = new_total;
			this.index.total = Math.ceil(this.options.total/this.options.amount);
			if (this.index.total < this.options.index_display) this.options.index_display = this.index.total;
			this.index.limit = Math.floor(this.options.index_display/2);
			this.index.cur_page = this.options.cur_page;
			this.index.pnum = this.index.cur_page + 1;	
		}
		
		if (this.options.total) {									
			//var pnum = this.options.cur_page + 1;				
		} else {return false;}
		
		if (this.index.total) {
			
			var start,end = false;
			var left,right = 0;
			
			var s_page,e_page;
		
			if (this.index.pnum > this.index.limit) { 
				if ((this.index.total - this.index.pnum) < this.index.limit) { // At the end of the index
					e_page = this.index.total;					
					s_page = this.index.total - this.options.index_display;
					start = true;
				} else { // In the middle
					s_page = this.options.cur_page - this.index.limit;
					e_page = this.options.cur_page + this.index.limit+1;					
					
					start = true;
					end = true;
				}
			} else { // At the start of the index
				s_page = 0;
				e_page = this.options.index_display;
				end = true;
			}
			
			if (this.options.total) {
				this.updatePageDisplay();
			}

			if (start && this.options.index_display != this.index.total) {			
				start = this.options.format.start.replace(/#start_index#/g,0);
			} else { start ='';}
						
			if (end && this.options.index_display != this.index.total) {
				end = this.options.format.end.replace(/#end_index#/g,this.index.total-1);
			} else {end = '';}
			
			
			var str = ''+start;
			
			for(var i=s_page; i<e_page; ++i) {
				var s_range = (i*this.options.amount)+1;	
				var e_range = ((s_range + this.options.amount - 1)> this.options.total) ? this.options.total: (s_range + this.options.amount - 1);
								
				var temp = (i == this.options.cur_page) ? this.options.format.range_active : this.options.format.range;
				
				temp = temp.replace(/#id#/g, this.id);
				temp = temp.replace(/#index#/g, i);
				temp = temp.replace(/#s_range#/g, s_range);
				temp = temp.replace(/#e_range#/g, e_range);
				temp = temp.replace(/#page_num#/g, parseInt(i)+1);
				
				str += temp;
								
			}
			
			str += end;
			if (this.index.div_top) this.index.div_top.innerHTML = str;
			if (this.index.div_bottom) this.index.div_bottom.innerHTML = str;
			
		}
		
	},
	
	updatePageDisplay: function() {
		if (this.options.cur_page_display && this.options.total) {
			if (console) console.log('new pnum: ' + this.index.pnum);
			var temp = this.options.format.page_display.replace(/#cur_page#/g, this.index.pnum);
			var str = temp.replace(/#total_pages#/g, this.index.total);	
			
			if (this.top_cur_page) this.top_cur_page.innerHTML = str;
			if (this.bottom_cur_page) this.bottom_cur_page.innerHTML = str;
		}
	},
		
	sortPage: function(filter) {
		this.options.args.f = filter;
		this.loadPage(0);
	},
	
	loadPage: function(entry, amount, id_target) {
		
		
		if (entry > 0 || entry === 0) {
			var effect = new Effect.Opacity(this.body.id, {duration:0, from:0.15,to:0.15});
			this.centerStatus();
			this.status.show(lang.pager[cur_lang].load);
			
			var callParams = [];
			callParams.push('p=' + entry);
			var amount = amount || this.options.amount;
			callParams.push('lim=' + amount);
			if (this.type) {
				callParams.push('type=' + this.type);
			}
			if (typeof(this.options.args) != 'undefined') {
				for(var key in this.options.args) {
					if (key !== 'extend') {
						callParams.push('args['+key+']='+this.options.args[key]);	
					}
				}
			}
			if (id_target) {
				this.id_target = id_target;	
			}
			this.updater.callService(this.app+'.getPage', callParams);
		}
	},
	
	//this is called after the server answers with an Ajax message
	ajaxUpdate: function(ajaxResponse) {
		
	
		var title = ajaxResponse.getElementsByTagName('title')[0];
		var next = ajaxResponse.getElementsByTagName('next')[0];
		var previous = ajaxResponse.getElementsByTagName('prev')[0];
		var main_body = ajaxResponse.getElementsByTagName('main_body')[0];
		
		var page = ajaxResponse.getElementsByTagName('page')[0];
		this.options.cur_page = parseInt(page.getAttribute('cur_page'));
		
		main_body = RicoUtil.getContentAsString(main_body);
		//if (console) console.log('MAIN BODY '+main_body);
		this.body.innerHTML = main_body;
		
		if (this.options.parse_scripts) {
			if (browser.isIE) {  
				ApexUtil.evalScripts(main_body, true);
			} else {
				ApexUtil.evalScripts(this.body);
			}
		}
		
		var effect = new Effect.Opacity(this.body.id, {duration:0, from:1.0,to:1.0});
		this.status.hide();
		
		if(previous){
			
			var label = RicoUtil.getContentAsString(previous) || lang.pager[cur_lang].prev;
			
			if (this.nav.bottom) {
				this.nav.bottom.prev.innerHTML = this.options.format.prev.replace(/#label#/g, label);
				this.nav.bottom.prev.href = "javascript:"+this.pager_ob_str+".loadPage(" + previous.getAttribute('id') + ")";
				this.nav.bottom.prev.style.display = '';
			}
			
			if (this.nav.top) {
				this.nav.top.prev.innerHTML = this.options.format.prev.replace(/#label#/g, label);
				this.nav.top.prev.href = "javascript:"+this.pager_ob_str+".loadPage(" + previous.getAttribute('id') + ")";
				this.nav.top.prev.style.display = '';
			}
			
		}else{	
			if (this.nav.bottom) this.nav.bottom.prev.style.display = 'none';
			if (this.nav.top) this.nav.top.prev.style.display = 'none';
		}
		
		if(next){
			
			var label = RicoUtil.getContentAsString(next) || lang.pager[cur_lang].next;
			
			if (this.nav.bottom) {
				this.nav.bottom.next.href = "javascript:"+this.pager_ob_str+".loadPage(" + next.getAttribute('id') + ")";
				this.nav.bottom.next.innerHTML = this.options.format.next.replace(/#label#/g, label);
				this.nav.bottom.next.style.display = '';
			}
			if (this.nav.top) {
				this.nav.top.next.href = "javascript:"+this.pager_ob_str+".loadPage(" + next.getAttribute('id') + ")";
				this.nav.top.next.innerHTML = this.options.format.next.replace(/#label#/g, label);
				this.nav.top.next.style.display = '';
			}
		}else{			
			if (this.nav.bottom) this.nav.bottom.next.style.display = 'none';
			if (this.nav.top) this.nav.top.next.style.display = 'none';
		}	
		
		this.updateHistory(RicoUtil.getContentAsString(title));
		
		if (this.use_comments) {
			this.updateComments(ajaxResponse);	
		}
		
		this.genIndexInterface(parseInt(page.getAttribute('total')));
		
		
		if (this.id_target) {
			if (this.loadAnchor(this.id_target)) {
				this.id_target = null;								  
			}
		}
		
		this.onUpdatePage();
	
	},
	
	loadAnchor: function(target) {
		if (target) {
			var loc = ""+self.location;
			var dest = loc.split('#');
			if (dest.length > 1) {
				dest.pop();
			}
			dest.push(target);
			self.location = dest.join('');
			if (console) console.log('CUR LOCATION: '+self.location);
			return true;
		}
	},
	
	injectNavigation: function() {
		
		var top = this.options.format.top.replace(/#id#/g, this.id);		
		this.top_wrapper.innerHTML = top;
		
		var bottom = this.options.format.bottom.replace(/#id#/g, this.id);
		this.bottom_wrapper.innerHTML = bottom;
		
		this.nav = {top:{}, bottom:{}};
		
		if (this.options.style == 'both' || this.options.style == 'top') {
			
			if (typeof this.nav.top !== 'undefined') {
				
				if (console) console.log('PARSING TOP NAV');
				
				this.nav.top.prev = $(this.id + '_prev_top');
				this.nav.top.next = $(this.id + '_next_top');
				
				if (this.nav.top.prev) { 
					if (parseInt(this.options.prev_value)) {
						var label = this.options.prev_label || lang.pager[cur_lang].prev;
						this.nav.top.prev.innerHTML = this.options.format.prev.replace(/#label#/g, label);
						this.nav.top.prev.href = "javascript:"+this.pager_ob_str+".loadPage(" + this.options.prev_value + ")";
					} 
				}
					
				if (this.nav.top.next) {
					if (parseInt(this.options.next_value)) {
						var label = this.options.next_label || lang.pager[cur_lang].next;
						this.nav.top.next.innerHTML = this.options.format.next.replace(/#label#/g, label);	
						this.nav.top.next.href = "javascript:"+this.pager_ob_str+".loadPage(" + this.options.next_value + ")";
					}
				}

				this.index.div_top = $(this.id + '_index_top');	
				this.top_cur_page = $(this.id + '_cur_page_top');
				
				this.showTopNav();
			}
		}
		
		if (this.options.style == 'both' || this.options.style == 'bottom') {

			if (typeof this.nav.bottom !== 'undefined') {
				
				if (console) console.log('PARSING BOTTOM NAV');
				
				this.nav.bottom.prev = $(this.id + '_prev_bottom');
				this.nav.bottom.next = $(this.id + '_next_bottom');
				
				if (this.nav.bottom.prev) {
					if (parseInt(this.options.prev_value)) {			
						var label = this.options.prev_label || lang.pager[cur_lang].prev;
						this.nav.bottom.prev.innerHTML = this.options.format.prev.replace(/#label#/g, label);
						this.nav.bottom.prev.href = "javascript:"+this.pager_ob_str+".loadPage(" + this.options.prev_value + ")";
					}
				}
				
				if (this.nav.bottom.next) {
					if (parseInt(this.options.next_value)) {
						var label = this.options.next_label || lang.pager[cur_lang].next;
						this.nav.bottom.next.innerHTML = this.options.format.next.replace(/#label#/g, label);	
						this.nav.bottom.next.href = "javascript:"+this.pager_ob_str+".loadPage(" + this.options.next_value + ")";
					}					
				}

				this.index.div_bottom = $(this.id + '_index_bottom');				
				this.bottom_cur_page = $(this.id + '_cur_page_bottom');
				
				this.showBottomNav();
			}
		}
				
		this.genIndexInterface(this.options.total);
		
		if (typeof(this.options.args) != 'undefined') {
			this.loadAnchor(this.options.args.target);
		}
		
	},
	
	showTopNav: function() {this.top_wrapper.style.display = '';},	
	showBottomNav: function() {this.bottom_wrapper.style.display = '';},
	
	showPage: function(ajaxResponse){				
		if (!this.type) this.type = RicoUtil.getContentAsString(ajaxResponse.getElementsByTagName('type')[0]);
		
		var index = ajaxResponse.getElementsByTagName('index')[0];
		if (index) {
			this.genIndexInterface(parseInt(index.getAttribute('total')));
		}		
		
		var body = ajaxResponse.getElementsByTagName('body')[0];
		var indexlinks = ajaxResponse.getElementsByTagName('indexlinks')[0];
				
		//var entry = ajaxResponse.getElementsByTagName('entry')[0];
		var previous = ajaxResponse.getElementsByTagName('previous')[0];
		var next = ajaxResponse.getElementsByTagName('next')[0];
		//var index = ajaxResponse.getElementsByTagName('index')[0];
				
		//this.center.innerHTML = RicoUtil.getContentAsString(index);
		this.body.innerHTML = RicoUtil.getContentAsString(body);
		new Effect.Opacity(this.body.id, {from:1.0,to:1.0});
		this.status.hide();
		
		
	},
	
	updateComments: function(ajaxResponse) {
		var comments = ajaxResponse.getElementsByTagName('comments')[0];	
		
		if (comments) {
			var content_id = comments.getElementsByTagName('content_id')[0];
			comment.content_id = RicoUtil.getContentAsString(content_id);
			comment.wrapper.innerHTML = RicoUtil.getContentAsString(comments.getElementsByTagName('listing')[0]);
		}
	},
	
	updateHistory: function(label) {
		if (typeof(histpath) != 'undefined') {
			if (this.historyUpdate && label) {
				var index = this.historyUpdate
				histpath.updateElement(index, label);
			}
		}
	},
	
	centerStatus: function() {
		
		
		this.status.self.style.visibility = 'hidden';
		this.status.self.style.display = '';
		
		this.status.self.style.width = "100px";
		
		var w = this.status.self.offsetWidth;
		var h = this.status.self.offsetHeight;	
		
		//var pos = RicoUtil.toDocumentPosition(this.self);
		var pageScroll = ApexUtil.getPageScroll();
		var pageSize = ApexUtil.getPageSize();
		
		var pos = RicoUtil.toDocumentPosition(this.body);
		var dims = {width:this.body.offsetWidth, height:this.body.offsetHeight};
		
		//if (console) console.log("Screen Overlay : " + screen_overlay);
		//var top = screen_overlay.arrayPageScroll[1] + 100;
		
		
		var left = pos.x + ((dims.width - w) / 2);
		//var top = (false) ? ((pageSize[3] - h) / 2) + pageScroll[1]: pos.y + ((dims.height - h) / 2);
		var top = pos.y + ((dims.height - h) / 2);
		//top = top+pageScroll;
		//if(console) console.log('top: ' + top + ' pageScroll: ' + pageScroll);
		//if (console) console.log('top: ' + top);
		
		//this.self.style.top = (top < 0) ? "0px" : top + "px";
		if (browser.isMoz) {
			pageScroll[1] = 0;	
		}
		
		this.status.self.style.top = (top < 0) ? "0px" : (pageScroll[1]+top) + "px";
		this.status.self.style.left = (top < 0) ? "0px" : left + "px";
		
		this.status.self.style.display = 'none';
		this.status.self.style.visibility = '';
		
		
	}		
};


