(function ( $ ) {

	PB.Overview = $.Class({
		
		resultStr: '',
		
		noResultStr: '',
		
		constructor: function ( config ) {			
			
			this.page = 0;
			
			Object.extend(this, config);
			
			this.initRequest();
			this.translate();
			this.handler.on('click', this.next.bind(this))
		},
		
		setTemplate: function ( html ) {
			
			this.tpl = new $.Template(html);
		},

		translate: function(){
			
			if(PB.lang == 'en'){
				
				this.resultStr = 'Load message :current to :next of total :total messages';
			}else{
				this.resultStr = 'Laad bericht :current t/m :next van de :total berichten';
			}

			if(PB.lang == 'en'){
				
				this.noResultStr = 'There are no more messages to show';
			}else{
				
				this.noResultStr = 'Er zijn geen verdere berichten te laden';
			}
		},
		
		initRequest: function () {
			
			this.request = new $.Request({
				url: '/:lang/news/read_all_with_pager'.replace(':lang', PB.lang),
				method: 'GET'
			});
			
			this.request.on('end', function ( request, code ) {
				
				this.handler.morph({opacity: 1}).removeClass('loading');
				
				switch( code ) {
					
					case 200:
						this.render( request.responseJSON );
						break;
						
					default:
						this.handler.html('Failed to load');
						break;
				}
			}.bind(this));
		},
		
		next: function ( e ) {
			
			e.stop();
			
			this.send();
		},
		
		send: function () {
			
			if( this.free === false ) {
				
				return;
			}
			
			this.free = false;
		
			this.page++;
			
			this.handler.addClass('loading').morph({opacity: .6}).html('');
			this.request.set('data', {limit: this.limit, page: this.page}).send();
		},
		
		addEvents: function ( nodes ) {
			
			nodes.forEach(function ( element ){
				
				// Should be A
				if(element.nodeName !== 'A'){
					return;
				}
		
				element.attr('href', '/'+PB.lang+element.attr('href'));
			});
		},
		
		render: function ( data ) {
			
			var nodes = this.tpl.appendTo(this.renderTo, data);
			
			this.addEvents( nodes );
			
			this.handler.appendTo(this.renderTo);
			
			var currentItem = this.page * this.limit,
				lastDisplayItem = currentItem + this.limit;
			
			lastDisplayItem = lastDisplayItem > this.totalResults ? this.totalResults : lastDisplayItem;

			

			if( currentItem < this.totalResults ) {
				
				this.free = true;
				this.handler.html( this.resultStr.replace(':current', currentItem).replace(':next', lastDisplayItem).replace(':total', this.totalResults) );
			} else {
				
				this.handler.html( this.noResultStr );
			}
		}
	});
})( PB );
