/*window.onload = function(){
	calcChars(document.getElementById("smsme_message"));
	document.getElementById("smsme_message").onkeyup = function(){
		calcChars(this);
	}
}

function calcChars(ele){
	concat = 1;
	if(ele.value.length > 160)
		concat = Math.ceil(ele.value.length/153);
	
	charsRemaining = 160 - ele.value.length;
	if(concat > 1)
		charsRemaining = 153*concat - ele.value.length;
	
	document.getElementById("messageLength").innerHTML = ele.value.length + '/' + charsRemaining + ' chars ('+concat+' messages)';
}
*/


$(document).ready(function() {
	
	calcChars("smsme_message");
	$("#smsme_message").keyup(function(){
		calcChars($(this).attr('id'));
	});
	
	$("#smsme form").submit(function() {

		data = $(this).serialize();
		data += '&smsmeSubmit=Send';
		
		form = $(this);
		textarea = form.contents().find("textarea");
		
		if(!textarea.val().replace(/\s/g, '')) {
			
			alert("You might want to enter a message.");
			
			return false;
			
		}

		backgroundImage = textarea.css('background-image');
		backgroundPosition = textarea.css('background-position');
		backgroundRepeat = textarea.css('background-repeat');

		root = form.attr('action').replace(/index\.php/,'');

		textarea.css({'background': 'url('+root+'wp-admin/images/loading.gif) 99% 1% no-repeat'});

		$.post(root+'wp-content/plugins/smsme/ajax.php', data, function(resp) {
			
			textarea.css({'background': backgroundImage+' '+backgroundPosition+' '+backgroundRepeat}).before('<div id="smsme_feedback">'+resp+'</div>');
			
			$("#smsme_feedback").fadeOut(6000, function(){
				$(this).remove();
			});
			
		});
		
		return false;
		
	});
	
});


function calcChars(eleId){
	concat = 1;
	if($('#'+eleId).val().length > 160)
		concat = Math.ceil($('#'+eleId).val().length/153);
	
	charsRemaining = 160 - $('#'+eleId).val().length;
	if(concat > 1)
		charsRemaining = 153*concat - $('#'+eleId).val().length;
	
	$("#messageLength").text( $('#'+eleId).val().length + '/' + charsRemaining + ' chars ('+concat+' messages)' );
}
