$(function()
{	
	window.quickpost = {};
	
	var quickpostTextarea = $(".quickpost textarea");
	var quickpostControl = $(".quickpost-control");
	
	$(quickpostTextarea).keyup(function(){		
		quickpost.syncQuickPost();			
	});	
	
	$(quickpostTextarea).focus(function(){
		$(this).attr("rows", 3);
		$(quickpostControl).show();
	});	
	
	$('#quickpost-form').submit(function() {
		$('.quickpost-loader').show();
		$(".quickpost-button").attr("disabled", "disabled");
		$(this).serialize()
		$.post(
			$(this).attr("action"),
			$(this).serialize(),
			function (response) {
				var spot = new EJS({
					'url' : '/views/quickpost/spot.ejs'
				});
				$('.quickpost-loader').hide();
				$('.quickpost textarea').val('');
				quickpost.syncQuickPost();
				
				$('.tbl:first').before(spot.render(response));
				$('.tbl:first').hide().fadeIn(500);				
				
			},
			'json'
		);
		return false;
	});	
	
	
	quickpost.syncQuickPost = function(elem) {	
		var quickpostTextarea = $(".quickpost textarea");
		var len = $(quickpostTextarea).val().length;
		var counter = $(".quickpost-counter");
		$(counter).text(140 - len);
		
		if (len < 130) {
			$(quickpostTextarea).css({
				'background' : 'white',
				'border' : '1px solid #999'				
			});
			$(counter).css('color', '#999');
		} 
		else if (len <= 140) {
			$(quickpostTextarea).css('background', '#effaba');
			$(counter).css('color', 'orange');
		}
		else{
			$(quickpostTextarea).css('background', '#ffc1be');
			$(counter).css('color', 'red');
		}
		
		if (quickpost.isActiveState(len)) {
			$(".quickpost-button").removeAttr("disabled");
		}
		else{
			$(".quickpost-button").attr("disabled", "disabled");
		}	
	}
	
	quickpost.isActiveState = function(len){
		return (len > 0 && len <= 140);
	}

});


