function login() {

	var username = $('#username').val();
	var password = $('#password').val();

	$.post("collabtweet.php?action=validate", { username: username, password: password} , 
	
		function(data){
		  if (data != '0') {
			  $('#body').slideUp(1000, function() {
				document.getElementById('bodycontent').innerHTML = data;
				document.getElementById('titlecontent').innerHTML = username+', you are logged in | <a href=\"javascript:void(0)\" onclick=\"javascript:logout()\">logout</a>';
				$('#body').slideDown(500);	  
			  });
		  
		  } else {
			  $('#username').css('border-color','#fc4f73');
			  $('#username').css('border-width','1px');
			  $('#username').css('margin','1px');
			  $('#password').css('border-color','#fc4f73');
			  $('#password').css('border-width','1px');
			  $('#password').css('margin','1px');
		  }
		}
	);
}

function tweetagain() {

	$.get("collabtweet.php?action=validate", { } , 
	
		function(data){
		  if (data != '0') {
			  $('#body').slideUp(1000, function() {
				document.getElementById('bodycontent').innerHTML = data;
				$('#body').slideDown(500);	  
			  });
		  
		  } else {
			  document.location.reload();
		  }
		}
	);
}

function tweet() {
	var tweet = $('#tweet').val();
	$('#loader').show();
	$.post("collabtweet.php?action=tweet", { tweet: tweet} , 
		function(data) {
			if (data != 0) {
			  $('#body').slideUp(1000, function() {
				document.getElementById('bodycontent').innerHTML = 'Your twitter profile has been successfully updated.<br/><br/><a class="link" href="http://twitter.com/'+data+'" target="blank">Click here to view your tweet</a><br/><a class="link" href="#" onclick="javascript:tweetagain()">Click here to tweet again</a>';
				$('#body').slideDown(500);	  
			  });
			} else {
				alert('Something went terribly wrong. Please try again.');	
			}
		}
	);
}

function logout() {

	$.post("collabtweet.php?action=logout", {} , 
		function(data) {
			if (data == 1) {
			  $('#body').slideUp(1000, function() {
				document.getElementById('bodycontent').innerHTML = 'You may safely close the browser window.<br/><br/><a class="link" href="javascript:void()" onclick="javascript:window.location.reload()">Click here to login again</a>';
				document.getElementById('titlecontent').innerHTML = 'You have logged out successfully';
				$('#body').slideDown(500);	  
			  });
			 }
		}
	);
}

var limit = 0;

function tweetcount() {
	if (limit == 0) {
		limit = document.getElementById('twittercount').innerHTML;
		limit = parseInt(limit);
	}

	var text = $('#tweet').val();
	if (text.length > limit) {
		$('#tweet').val(text.substring(0, limit));
	} else {
		document.getElementById('twittercount').innerHTML = limit - text.length;
	}
}

$(document).ready(function(){
	if ($('#username')) {
		$('#username').focus();
	} else if ($('#tweet')) {
		$('#tweet').focus();
	}
});