//initialize the TinyMCE editor
tinyMCE.init({
	mode : "exact",
	elements : "txtPrayer",
	theme : "advanced",
	plugins : "safari,paste,fullscreen",

	theme_advanced_buttons1 : "bold,italic,strikethrough,|,cut,copy,paste,pastetext,pasteword,|,bullist,numlist,|,undo,redo,|,fullscreen",
	theme_advanced_buttons2 : "",
	theme_advanced_toolbar_location : "top",
	theme_advanced_toolbar_align : "left",
	theme_advanced_statusbar_location : "bottom",
	theme_advanced_resize_horizontal : false,
	theme_advanced_resizing : true,

	content_css : "/css/tinymce.css"
});

//make room on the DOM for the AJAX loaded prayer requests
var requests, AJAXData;

//regex to clean out bad HTML from prayer requests
var clean=new RegExp("((class|style)=\"[^\"]*\")|(</?span[^>]*>)|(</?div>)|(<p[^>]*>(\\s|&nbsp;)*</p>)","gi");

//function that sends the message
var sendMessage=function() {
	$('#msg').hide()
	
	data={
		'id' : $('#hidId').val(),
		'author' : $('#txtMsgAuthor').val(),
		'email' : $('#txtMsgEmail').val(),
		'subject' : $('#txtMsgSubject').val(),
		'message' : wysiwyg('txtMsg')
	};

	tinyMCE.execCommand('mceRemoveControl', false, 'txtMsg');

	$('#dialog').dialog('close');
	
	$('#txtMsgAuthor').val('Put your name here');
	$('#txtMsgEmail').val('Put your email address here');
	$('#txtMsgSubject').val('Your prayer request on rivchurch.com');
	$('#txtMsg').val('');

	//change the processing message
	$('#processing').html('<img src="/images/loading2.gif" alt=""> <b>Sending Message</b>');

	//hide the form and show the processing status
	$('#processing').show("blind",{},500, function() {
		tinyMCE.execCommand('mceRemoveControl', false, 'txtPrayer');
		$('#txtPrayer').hide();
		$('#frmRequest').hide("blind",{},200, function() {
		});
	});

	$.post('/process/send-message/', data, function(msg) {
		AJAXData=msg;
		$('#processing').hide("blind",{},500, function() {
			$('#frmRequest').show("blind",{},500,function() {
				//change the processing message
				$('#processing').html('<img src="/images/loading2.gif" alt=""> <b>Processing your Prayer Request</b>');

				$('#txtPrayer').show();
				tinyMCE.execCommand('mceAddControl', false, 'txtPrayer');

				if(AJAXData=="success") {
					//show the success message
					$('#msg').html('<b>Your message was sent.</b>');
					$('#msg').css('color','green');
					$('#msg').css('border-color','green');
					$('#msg').show();
				} else {
					//show the failure message
					$('#msg').html('<b>Sorry, an error occurred and your message was not sent.</b>');
					$('#msg').css('color','red');
					$('#msg').css('border-color','red');
					$('#msg').show();
				}
			});
		});
	});
}

//initial prayer load
var loadPrayer = function() {
	$.getJSON("/process/load-prayer/", {}, function(data) {
		requests=data;
		
		renderPrayer(0,5);
		
		checkQuickPrayers();
		
		var pos=document.location.href.indexOf('#')
		if(pos >= 0) {
			scrollTo(document.location.href.substr(pos));
		}
	});
}

//renders the prayer requests from the DOM object
//and writes them to the div where id=prayer
var renderPrayer=function(start, count) {
	var html=new Array();
	
	for(var i=start; i<(start+count); i++) {
		var item=requests[i];
		
		author=item.author;
		body=item.body.replace(clean,"");
		
		if(author=='') author="Anonymous";
		
		html.push('<div id="request_');
		html.push(item.id);
		html.push('"><b>');
		html.push(author + ":");
		html.push("</b><br>");
		html.push(body + '<p>');
		
		if(item.email) {
			html.push('<a href="javascript: showMessageForm(')
			html.push(i)
			html.push(');">Send a message to ');
			html.push(author);
			html.push('</a> | ');
			html.push(genQuickPrayerLink(i));
		} else {
			html.push('(Email address not provided)');
		}
		
		html.push('</p><span style="font-size: 9px;">Posted on ');
		html.push(item.date)
		html.push('</span>');
		html.push('</div>');

		html.push("<hr>");
		html.push("<br>");
	}
	
	$("#prayer").html(html.join(''));
}

//shows the message form and populates some of the data
var showMessageForm=function(item) {
	$("#txtMsgAuthor").focus(defaultFocus);
	$("#txtMsgAuthor").blur(defaultBlur);

	$("#txtMsgEmail").focus(defaultFocus);
	$("#txtMsgEmail").blur(defaultBlur);

	$('#lblTo').html(requests[item].author);
	$('#hidId').val(requests[item].id);
	$('#dialog').dialog('open');
	
	tinyMCE.execCommand('mceAddControl', false, 'txtMsg');
}

//sends a quick prayer
var sendQuickPrayer=function(i) {
	AJAXData=i;
	$('#quickPrayer_'+i).html('<b>Sending quick prayer...</b>');
	$.get("/process/quick-prayer/", {'id':requests[i].id, 'code':code}, function(data) {
		if(data.substr(0,4)=='fail') {
			alert(data);
			var id=data.substr(5);
		} else {
			var id=data;
		}

		var numTimes=0;
		
		if($.cookie('quickPrayer_'+id)!=null) numTimes=Number($.cookie('quickPrayer_'+id))
		numTimes++;
		
		$.cookie('quickPrayer_'+id, numTimes, {'expires': 90})
		
		$('#quickPrayer_'+id).html(genQuickPrayerLink(AJAXData)+genNumPrayers(numTimes));
	});
}

//shows the quick prayer count
var checkQuickPrayers=function() {
	$(".qp").each(function() {
		if($.cookie(this.id)!=null) {
			times=$.cookie(this.id);
			$('#'+this.id).append(genNumPrayers(times));
		}
	});
}

//generates the HTML for the number
//of quick prayers send
var genNumPrayers=function(numTimes) {
	var tmp=new Array();
	tmp.push(' <span class="quickPrayer">(You have sent them Quick Prayer ');
	tmp.push(numTimes);
	tmp.push(' time');
	tmp.push(((numTimes>1)?'s':''));
	tmp.push(')</span>');
	
	return tmp.join('');
}

//generates the link for a quick prayer
var genQuickPrayerLink=function(i) {
	var tmp=new Array();
	tmp.push('<span id="quickPrayer_');
	tmp.push(requests[i].id);
	tmp.push('" class="qp">');
	tmp.push('<a href="javascript: sendQuickPrayer(');
	tmp.push(i);
	tmp.push(');">Quick Prayer</a></span>');
	
	return tmp.join('');
}

//grabs the HTML from a TinyMCE instance
var wysiwyg=function(instance) {
	var content = tinyMCE.get(instance).getContent();
	content = content.replace(/\+/g, "&#43");
	content = content.replace(/\\/g, "&#92");

	return content;
}

var pageClickHandler=function(e) {
	e.preventDefault();
	var num=$(this).html().substr(2,2);
	
	clearCurPage(curPage);
	makeCurPage(num);
	
	curPage=num;

	renderPrayer((num-1)*5,5);
	checkQuickPrayers();
}

var makeRequest=function() {
	//hide the success message from earlier
	$('#msg').hide()

	//grab the data from the form
	data={
		'author' : $('#txtName').val(),
		'email' : $('#txtEmail').val(),
		'text' : wysiwyg('txtPrayer'),
		'ip' : $('#hidIp').val()
	};
	
	//hide the form and show the processing status
	$('#processing').show("blind",{},500, function() {
		tinyMCE.execCommand('mceRemoveControl', false, 'txtPrayer');
		$('#txtPrayer').hide();
		$('#frmRequest').hide("blind",{},200, function() {
		});
	});


	//send the prayer
	$.post('/process/request-prayer/', data, function(msg) {
		AJAXData=msg;
		$('#processing').hide("blind",{},500, function() {
			$('#frmRequest').show("blind",{},500,function() {
				//clear the form for any other requests
				$('#txtName').val('');
				$('#txtEmail').val('');
				
				$('#txtPrayer').val('');
				$('#txtPrayer').show();
				tinyMCE.execCommand('mceAddControl', false, 'txtPrayer');

				//reload the requests
				loadPrayer();
				
				//add the quick prayer functionality to new requests
				checkQuickPrayers();
				
				if(AJAXData=="success") {
					//show the success message
					$('#msg').html('<b>Your Prayer Request was added.</b>');
					$('#msg').css('color','green');
					$('#msg').css('border-color','green');
					$('#msg').show();
				} else {
					//show the failure message
					$('#msg').html('<b>Sorry, an error occurred and your Prayer Request was not added.</b><br><br>'+data);
					$('#msg').css('color','red');
					$('#msg').css('border-color','red');
					$('#msg').show();
				}
			});
		});
	}, 'text');
}

//removes link and changes color for the current page
var makeCurPage=function(pageNum) {
	$('#pg'+pageNum).html("[ "+pageNum+" ]")
	$('#pg'+pageNum).css("background","#e0e0e0")
	$('#pg'+pageNum).css("color","#000")
}

//re-adds the link and removes the color for non-current page
var clearCurPage=function(pageNum) {
	$('#pg'+pageNum).html("<a class=\"pageLink\" href=\"\">[ "+pageNum+" ]</a>");
	$('#pg'+pageNum).css("background","");
	$('#pg'+pageNum).css("color","");

}

$(function() {
	//add click handler to page links
	$('a[class=pageLink]').live("click", pageClickHandler);
	
	//set the current page style
	makeCurPage(curPage);
	
	//initialize the message form
	$("#dialog").dialog({
		bgiframe: true,
		autoOpen: false,
		height: 550,
		width: 550,
		modal: true,
		resizable: false,
		buttons: {
			'Send': sendMessage,
			'Cancel' : function () {
				$(this).dialog('close');
			}
		}
	});
	
	//add click handler to the post request button
	$('#btnPost').click(makeRequest);
});

