pager = {};

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) {
		this.id = id;
		this.self = $(this.id);
		this.self.style.display = '';
		this.body = $(this.id+'_body');
		this.indexlinks = $('indexlinks');//still needed?
				

		var s_col = status_color || 'white';
		s_col = (options.color) ? options.color : s_col;
		this.status = new StatusComponent('pager_status', s_col);
		
		this.top_wrapper = $('incremental_navigation');
		this.bottom_wrapper = $('lower_navigation');

		this.historyUpdate = history_update || false;
		this.use_comments = use_comments || false;		
		this.app = app;
		this.setOptions(options);
		
		if (this.options.type) this.type = this.options.type;

		this.centerStatus();
		//this.status.show(lang.pager[cur_lang].load);
		this.initAjax();
		
		this.index = {};	
		//this.loadFormat();
		
		var me = this;
		page_init.scripts[this.id] = function() {
			me.loadFormat();
		};
		
	},
	
	setOptions: function(options) {
		this.options = {
			page_amount: 3,
			cur_page:0,
			index_display:5,
			style:'both'
		}
		Object.extend(this.options, options || {});
		if (console) console.log(this.options.parse_scripts);
	},
	
	genIndexInterface: function() {				
		if (this.options.total) {						
			//this.index.total = Math.ceil(this.options.total/this.options.page_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.pnum = this.index.cur_page + 1;				
		} else {return false;}
			
		if (console) console.log('pnum: ' + this.index.pnum);	
		if (console) console.log('cur page: ' + this.index.cur_page);	
		
		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.index.cur_page - this.index.limit;
					e_page = this.index.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();
			}
			//start = (start && this.options.index_display != this.index.total) ? '<a href="javascript:pager.loadPage(0);" onfocus="this.blur();">&lt;&lt;&nbsp;' + lang.pager[cur_lang].start + '</a>&nbsp;&nbsp;' : '';
			if (start && this.options.index_display != this.index.total) {
				var pattern = /#start_index#/g;				
				start = this.format.start.replace(pattern,0);
			} else { start ='';}
						
			//end = (end && this.options.index_display != this.index.total) ? '<a href="javascript:pager.loadPage(' + (this.index.total-1) + ');" onfocus="this.blur();">' + lang.pager[cur_lang].end + '&nbsp;&gt;&gt;</a>' : '';
			if (end && this.options.index_display != this.index.total) {
				var pattern = /#end_index#/g;
				end = this.format.end.replace(pattern,this.index.total-1);
			} else {end = '';}
			
			
			var str = ''+start;
			
			for(var i=s_page; i<e_page; ++i) {
				var s_range = (i*this.options.page_amount)+1;	
				var e_range = ((s_range + this.options.page_amount - 1)> this.options.total) ? this.options.total: (s_range + this.options.page_amount - 1);
								
				var temp = (i == this.index.cur_page) ? this.format.range_active : this.format.range;
				
				var pattern = /#index#/g;
				temp = temp.replace(pattern, i);
				
				var pattern = /#s_range#/g;
				temp = temp.replace(pattern, s_range);
				
				var pattern = /#e_range#/g;
				temp = temp.replace(pattern, e_range);
				
				var pattern = /#page_num#/g;
				temp = temp.replace(pattern, 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) {
			//var str = lang.pager[cur_lang].page_display.page + ' ' + this.index.pnum + ' ' + lang.pager[cur_lang].page_display.of + ' ' + this.index.total;
			if (console) console.log('new pnum: ' + this.index.pnum);
			var pattern = /#cur_page#/g;
			var temp = this.format.page_display.replace(pattern, this.index.pnum);
			var pattern = /#total_pages#/g;
			var str = temp.replace(pattern, 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;
		}
		
		
		if (this.options.hide_index) {
			Element.hide(this.id+'_index_title_top');
			Element.hide(this.id+'_index_title_bottom');
		}
	},
		
	initAjax: function() {
		ajaxEngine.registerRequest(this.id + '_request', this.app);
		ajaxEngine.registerRequest(this.id + '_load_request', '/sys/components/Pager/index.php');
		ajaxEngine.registerAjaxObject(this.id + '_load', this);
		ajaxEngine.registerAjaxObject(this.id + '_format_load', this);
	},
	
	callRicoAjaxEngine: function(callParams) {
		var additionalParams = this.options.requestParameters || [];
		for (var i=0; i < additionalParams.length; i++) callParams.push(additionalParams[i]);
		if (console) console.log('PARAMS: '+callParams);
		ajaxEngine.sendRequest.apply(ajaxEngine, callParams);
	},
	
	loadPage: function(entry, amount) {
		if (entry > 0 || entry === 0) {
			new Effect.Opacity(this.body.id, {from:0.15,to:0.15});
			this.centerStatus();
			this.status.show(lang.pager[cur_lang].load);
			var callParams = [];
			callParams.push( this.id + '_request');
			callParams.push('cmd=LoadPage');
			callParams.push('id=' + this.id);
			callParams.push('entry=' + entry);
			var amount = amount || this.options.page_amount;
			callParams.push('amount=' + amount);
			if (this.type) {
				callParams.push('type=' + this.type);
			}
			
			this.callRicoAjaxEngine(callParams);
		}
	},
	
	loadFormat: function() {
		if (console) console.log('Load Format');
		var callParams = [];
		callParams.push( this.id + '_load_request');
		callParams.push('cmd=LoadFormat');
		callParams.push('id=' + this.id);
		this.callRicoAjaxEngine(callParams);
	},
	
	//this is called after the server answers with an Ajax message
	ajaxUpdate: function(ajaxResponse) {
		switch(ajaxResponse.getAttribute('id')) {
			case this.id+'_load': this.showPage(ajaxResponse); break;
			case this.id+'_format_load': 
				this.injectContent(ajaxResponse);
				this.status.hide();
				
				//this.genIndexInterface();
				break;
		}
	},
	
	injectContent: function(resp) {
		this.format = {};
		var fields = resp.getElementsByTagName('field');
		for (var i=0; i<fields.length; ++i) {
			var name = fields[i].getAttribute('id');
			this.format[name] = RicoUtil.getContentAsString(fields[i]);								 
		}
	
		this.top_wrapper.innerHTML = this.format.top;
		this.bottom_wrapper.innerHTML = this.format.bottom;		
		
		
		this.nav = {top:{}, bottom:{}};
		
		if (this.options.style == 'both' || this.options.style == 'top') {
			
			this.nav.top.prev = $(this.id + '_prev_top');
			this.nav.top.next = $(this.id + '_next_top');
			
			if (parseInt(this.options.prev_value)) {
				var pattern = /#label#/g;
				var label = this.options.prev_label || lang.pager[cur_lang].prev;
				this.nav.top.prev.innerHTML = this.format.prev.replace(pattern, label);
				this.nav.top.prev.href = "javascript:pager.loadPage(" + this.options.prev_value + ")";
			}
			
			if (parseInt(this.options.next_value)) {
				var pattern = /#label#/g;
				var label = this.options.next_label || lang.pager[cur_lang].next;
				this.nav.top.next.innerHTML = this.format.next.replace(pattern, label);	
				this.nav.top.next.href = "javascript:pager.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') {

			this.nav.bottom.prev = $(this.id + '_prev_bottom');
			this.nav.bottom.next = $(this.id + '_next_bottom');
			if (parseInt(this.options.prev_value)) {			
				var pattern = /#label#/g;
				var label = this.options.prev_label || lang.pager[cur_lang].prev;
				this.nav.bottom.prev.innerHTML = this.format.prev.replace(pattern, label);
				this.nav.bottom.prev.href = "javascript:pager.loadPage(" + this.options.prev_value + ")";
			}
		
			if (parseInt(this.options.next_value)) {
				var pattern = /#label#/g;
				var label = this.options.next_label || lang.pager[cur_lang].next;
				this.nav.bottom.next.innerHTML = this.format.next.replace(pattern, label);	
				this.nav.bottom.next.href = "javascript:pager.loadPage(" + this.options.next_value + ")";
			}
			
			this.index.div_bottom = $(this.id + '_index_bottom');				
			this.bottom_cur_page = $(this.id + '_cur_page_bottom');
			
			this.showBottomNav();
		}
		
		if (this.options.total) {						
				this.index.total = Math.ceil(this.options.total/this.options.page_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;	
				this.genIndexInterface();
		}
		
		this.updatePageDisplay();
		
	},
	
	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.index.total = Math.ceil(index.getAttribute('total')/this.options.page_amount);
			this.index.cur_page = index.getAttribute('page') * 1;
			this.index.pnum = this.index.cur_page + 1;
			this.genIndexInterface();
		}		
		
		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();
		
		if(indexlinks) {			
			this.indexlinks.innerHTML = RicoUtil.getContentAsString(indexlinks);
		}
		
		if (this.options.parse_scripts) {
			ApexUtil.evalScripts(this.body);
		}
		
		if(previous){
			if (previous.getAttribute('value') === '') {
				this.nav.bottom.prev.style.border = 0;
				this.nav.top.prev.style.border = 0;
			}
			this.nav.bottom.prev.href = "javascript:pager.loadPage(" + previous.getAttribute('value') + ")";
			
			var pattern = /#label#/g;
			var label = RicoUtil.getContentAsString(previous) || lang.pager[cur_lang].prev;
			this.nav.bottom.prev.innerHTML = this.format.prev.replace(pattern, label);
			this.nav.bottom.prev.style.display = '';
			this.nav.top.prev.href = "javascript:pager.loadPage(" + previous.getAttribute('value') + ")";
			this.nav.top.prev.innerHTML = this.format.prev.replace(pattern, label);
			this.nav.top.prev.style.display = '';
		}else{		
			this.nav.bottom.prev.style.display = 'none';
			this.nav.top.prev.style.display = 'none';
		}
		
		if(next){
			if (next.getAttribute('value') === '') {
				this.nav.bottom.next.style.border = 0;
				this.nav.top.next.style.border = 0;
			}
			
			var pattern = /#label#/g;
			var label = RicoUtil.getContentAsString(next) || lang.pager[cur_lang].next;
			this.nav.bottom.next.href = "javascript:pager.loadPage(" + next.getAttribute('value') + ")";
			this.nav.bottom.next.innerHTML = this.format.next.replace(pattern, label);
			this.nav.bottom.next.style.display = '';
			this.nav.top.next.href = "javascript:pager.loadPage(" + next.getAttribute('value') + ")";
			this.nav.top.next.innerHTML = this.format.next.replace(pattern, label);
			this.nav.top.next.style.display = '';
		}else{			
			this.nav.bottom.next.style.display = 'none';
			this.nav.top.next.style.display = 'none';
		}	
		
		this.updateHistory(RicoUtil.getContentAsString(ajaxResponse.getElementsByTagName('title')[0]));
		
		if (this.use_comments) {
			this.updateComments(ajaxResponse);	
		}
	},
	
	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 (this.historyUpdate && label) {
			var index = this.historyUpdate
			histpath.updateElement(index, label);
		}
	},
	
	centerStatus: function() {
		
		
		this.status.self.style.visibility = 'hidden';
		this.status.self.style.display = '';
		
		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";
		this.status.self.style.top = (top < 0) ? "0px" : top + "px";
		this.status.self.style.left = (top < 0) ? "0px" : left + "px";
		
		this.status.self.style.display = 'none';
		this.status.self.style.visibility = '';
		
		
	}		
};