var story = Class.create();

story.prototype = {
	page_count:     null, 
	pages: 			null,
	pager:          new Array(),  
	story: 			null, 
	text:     		null,
	page_length: 	2000, 

	initialize: function(story) {
		this.story = $(story); 
		this._ajaxStrip(); 
	},
	
	_ajaxStrip: function() {
		var ajax = new Ajax.Request('/story/StripTags', {
		    method:'post',
			parameters: {	story_text: this.story.innerHTML },
			onComplete: this._init.bind(this),
			evalScripts: true  
		});
	},
	
	_init: function(transport){
		this.text = transport.responseText;
		this._split();
		this._createPages();
		this._show();
	},
	
	_split: function(){
		var index = 1;
		if(this.text.length > this.page_length){ //if char count of the story is bigger than page lenght (2000 char)
			var text_index = 1;
			var section_text = 0;
			while(section_text < this.text.length){
				var current_char = this.text.substring(this.page_length+section_text,this.page_length+section_text+text_index);
				while(	current_char != ' ' 
						&& current_char != ''){
					current_char = this.text.substring(this.page_length+section_text+text_index,this.page_length+section_text+text_index+1);
					text_index++;
				}
				this.pager[index] = this.text.substring(section_text,this.page_length+section_text+text_index);
				section_text = section_text+this.page_length+text_index;
				index++;
			}
		} else { // else create on div
			this.pager[index] = this.text;
		}
	},
	
	_createPages: function(){
		$('pages').innerHTML = "";
		this.page_count = Math.ceil((this.text.length)/this.page_length);
		for(page=1;page<=this.page_count;page++){
			var page_elem = new Element("a", { 
				href : 'javascript:void(0)',
			 	id : page
				}).update(page);
			$('pages').appendChild( page_elem );
			page_elem.addClassName('pager');
			Event.observe(page_elem, 'click', this._show.bind(this), false);
			if(page == 1)
				page_elem.addClassName('current');
		}
	},
	
	_show: function(event){
		var current_page = 1;
		if(event){
			$$('.pager').invoke('removeClassName', 'current');
			var element = Event.element(event);
			element.addClassName('current');
			current_page = element.id;
		}
		this.story.update(this.pager[current_page]);
		this.story.setStyle('display:block'); 
	}
}