document.observe('dom:loaded', function() {
	$('prayer-input').focus();	
	
	//Initiating My Prayer Browser
	prayerBrowser = new PrayerBrowser("prayer-browser");
		
	//Updating Prayer Prayed Counter after Given 5 Seconds
	
	//Updating Prayer Requested Counter after Given 5 Seconds
	new Ajax.PeriodicalUpdater('prayers-added', '/prayer_requests/count', {
    	method: 'get', frequency: 5, decay: 1
    });
			
	
	if ($('post-button')) {
		$('post-button').observe('click',function(){ 
			// Make asynchronous post to server
		    new Ajax.Request('/prayer_requests/new', {
		        method: 'get',
		        parameters: {text: $F('prayer-input'), report_abuse_count: 0},
		        onSuccess: function(request) {
		            $('prayer-input').value ='';
		            $('ask-successful').innerHTML = 'Prayer was successfully created.';
		        },
		        onLoading: function(){
		            $('img-load').show();
		        },
		        onComplete: function(){
		             $('img-load').hide();      
		        }    
		    });
	 	});
	}
	if ($('img-load')) {
		$('img-load').hide();
	}	

    $('prayer-input').onkeyup=function(){
		limitTextArea('prayer-input',123,'charcount');
    }
});


var PrayerRequest = Class.create({
	initialize: function(prayerRequestJSON){
	    var prayerRequest =  prayerRequestJSON.evalJSON(true);
		this.text = prayerRequest['text'];
		this.owner = prayerRequest['owner'];
		this.iPrayed = prayerRequest['iprayed'];
		this.timesPrayed = prayerRequest["timesprayed"];
	}
});


var PrayerBrowser = Class.create({
	initialize: function(parent){
	    this.parent = $(parent);  
	    this.buildContainer();
	
		// set bottom limit before going to get more prayer requests
		this.LOW_BUFFER = 2;
		
		//Prayer Queue for Local Caching of Prayers
		this.prayerQueue=[];	

		//Index for Prayer Browsing			
		this.prayerIndex = -1;

		//Populating the Prayer Queue from Online		
		this.getPrayerRequestQueue();
		
		// add our click observers
		$("next-prayer").observe('click', this.displayNext.bind(this));
		$("prev-prayer").observe('click', this.displayPrev.bind(this));
		
		$("i-prayed").observe('click', this.iPrayed.bind(this));	
		$("report-abuse").observe('click', this.reportAbuse.bind(this));		
		
		// display the first prayer request
		this.displayNext();
		
		//Auto Display of Next Prayer after every 8 seconds
		var j = new PeriodicalExecuter(this.displayNext.bind(this), 8);
		
	},
	buildContainer: function() {
		var child=Builder.node('div', { className:'span-14 prepend-2 append-2 last',id:'prayer-text-display'});		
		this.parent.insert(child);
		
		var element = Builder.node('div', { className:'span-18 last',id: 'prayer-view-actions'}, [

			[Builder.node('div', { className: 'span-2 textcenter',id: 'prev-prayer'},'.')],
			[Builder.node('div', { className: 'span-14 textcenter', id: 'i-prayed'},'.')],
			[Builder.node('div', { className: 'span-2 last textcenter',id: 'next-prayer'},'.')]

		]);		
		this.parent.insert(element);
		
		var child=Builder.node('div', { className:'span-18 last',id:'report-abuse'},'[report abuse]');	
		this.parent.insert(child);	
	},
	displayNext: function() {
		var prayerRequest = this.getNextFromQueue();
		new Effect.Opacity('prayer-text-display', { from: 0.0, to: 1.0, duration: 3.0,queue: 'front' });	
		$('prayer-text-display').innerHTML =  prayerRequest.text;	 
		new Effect.Opacity('prayer-text-display', { from: 1.0, to: 0.2, duration: 0.1,queue: 'end' });	
		new Effect.Opacity('prayer-text-display', { from: 0.2, to: 1.0, duration: 0.1,queue: 'end' }); 
	},
	displayPrev: function() {
		var prayerRequest = this.getPrevFromQueue();	
		new Effect.Opacity('prayer-text-display', { from: 0.0, to: 1.0, duration: 3.0,queue: 'front' });	
		$('prayer-text-display').innerHTML =  prayerRequest.text;	 
		new Effect.Opacity('prayer-text-display', { from: 1.0, to: 0.2, duration: 0.1,queue: 'end' });	
		new Effect.Opacity('prayer-text-display', { from: 0.2, to: 1.0, duration: 0.1,queue: 'end' }); 
	},
	iPrayed: function() {	
		console.log('iPrayed');
				
		this.removePrayerFromQueue();	
		$('prayer-text-display').innerHTML =  " Thank You for Praying";		    
		Effect.Pulsate('prayer-text-display', { pulses: 5, duration: 4 });
		    
		new Effect.Opacity('i-prayed', { from: 1.0, to: 0.1, duration: 0.5,queue: 'front' });
		new Effect.Opacity('i-prayed', { from: 0.1, to: 1.0, duration: 0.1,queue: 'end' });
	},
	reportAbuse: function() {		
 		$('prayer-text-display').innerHTML =  " Thank You for Reporting Abuse";
  		Effect.Pulsate('prayer-text-display', { pulses: 5, duration: 4 });
 		new Effect.Opacity('report-abuse', { from: 1.0, to: 0.1, duration: 0.5,queue: 'front' });
 		new Effect.Opacity('report-abuse', { from: 0.1, to: 1.0, duration: 0.1,queue: 'end' });
  		new Effect.Opacity('i-prayed', { from: 1.0, to: 0.1, duration: 0.5,queue: 'front' });
 		new Effect.Opacity('i-prayed', { from: 0.1, to: 1.0, duration: 0.1,queue: 'end' });
	},
	getPrayerRequestQueue: function(){
		console.log('about to fill prayerQueue');
		this.prayerQueue.clear();	
		// Sample prayerQueue with only Five Prayer Request. We need to discuss the Optimal Total Number (OPT) of Prayer Request to retrieve at One Time.
		var prayer1 = new Hash({'text':'One : I would like some prayer for my grandmother.  One : I would like some prayer for my grandmother One : I    would like some prayer for my grandmother blah  .','owner':'Bikash', 'iprayed':true, 'timesprayed':15});
		var prayer2 = new Hash({'text':'Two : Please pray for baby Birendra.','owner':'Ashis', 'iprayed':true, 'timesprayed':15});
		var prayer3 = new Hash({'text':'Three : Please pray for my neighbor Clinton','owner':'Ashis', 'iprayed':true, 'timesprayed':15});
		var prayer4 = new Hash({'text':'Four : Pray for little Marc Peytons brother.','owner':'Ashis', 'iprayed':true, 'timesprayed':15});
		var prayer5 = new Hash({'text':'Five : Pray they will get the rest of the finances','owner':'Ashis', 'iprayed':true, 'timesprayed':15});

		this.prayerQueue.push(new PrayerRequest(prayer1.toJSON()));
		this.prayerQueue.push(new PrayerRequest(prayer2.toJSON()));
		this.prayerQueue.push(new PrayerRequest(prayer3.toJSON()));
		this.prayerQueue.push(new PrayerRequest(prayer4.toJSON()));
		this.prayerQueue.push(new PrayerRequest(prayer5.toJSON()));

		// Sample Code for retrieving Prayer Request from Online through Ajax

		/*
		var url = '/proxy?url=' + encodeURIComponent('http://www.plzpray.com/prayerrequest/show');

		new Ajax.Request(url, {
			method: 'get',
			onSuccess: function(transport) {
				// Push the Five Newly Retrieved Prayer Request into prayerQueue
			}
		});

		*/

	},
	getNextFromQueue: function(){
		this.prayerIndex = (this.prayerIndex < (this.prayerQueue.length)-1) ? this.prayerIndex + 1 : 0;		
		return this.prayerQueue[this.prayerIndex];	
	},
	getPrevFromQueue: function(){
		this.prayerIndex = (this.prayerIndex == 0) ? this.prayerQueue.length-1 : this.prayerIndex - 1;	
		return this.prayerQueue[this.prayerIndex];	
	},	
	removePrayerFromQueue: function(){
		// Sending Request to Remove the Prayer from the Prayer Queue	
		this.prayerQueue.removeAt(this.prayerIndex+1);

		//If Prayer Queue is less then 2 (which actually will be equal to the Optimal Total Number(OPT)) then retrive Fresh Prayer Requests.
		if (this.prayerQueue.length < this.LOW_BUFFER){
			this.getPrayerRequestQueue();
		}

	}
				
	
});

function limitTextArea(elementId, maxLength, charCountDisplayId){
	
	var text = $F(elementId);
	var remainedlength = maxLength-text.length;
    
	if(!(charCountDisplayId === undefined)){	
		var charCountElement = $(charCountDisplayId);
		//console.log(charCountElement);
				
		if(remainedlength>0){
			$(charCountDisplayId).innerHTML = remainedlength;
			$(charCountDisplayId).style.fontSize = ((Math.floor(remainedlength / 20) + 10) +  "pt");
			$(charCountDisplayId).style.color = "#5C" + ((Math.floor( 5000 / remainedlength) + 5)) +  ((Math.floor( 160 / remainedlength))); 
			
			$('display-charcount').style.fontSize = ((Math.floor(remainedlength / 20) + 10) +  "pt");
			$('display-charcount').style.color = "#5C" + ((Math.floor( 5000 / remainedlength) + 5)) +  ((Math.floor( 160 / remainedlength))); 
			
		}   
	    else{
			$(charCountDisplayId).innerHTML = '0';		
	    }	
	}
	//
	if (!($(elementId).getAttribute("maxLength"))) {
		$(elementId).value = text.substring(0, maxLength - 1);	  	
	}
	
	
}


/*
	Utility Function: Remove element from a javascript array
*/
if (!Array.prototype.removeAt)
{
    Array.prototype.removeAt = function(index) {
            this.splice(index, 1);
    };
}



