var grayOutInputs = function() {
	$("input.grayOut").each(function(){
		if (this.value != this.title && $(this).hasClass("grayOut")) {
			$(this).removeClass("grayOut");
		}
		
		$(this).focus(function () {
			if (this.value == this.title) {
				this.value = "";
				$(this).removeClass("grayOut");
			}
		});
		$(this).blur(function () {
			if (this.value == "") {
				$(this).addClass("grayOut");
				this.value = this.title;
			}
		});		   
	 });
};

var showError = function(input) {
	if (input) {
		$("#errorField").html(input);
		$("#errorField").fadeIn();
		$("#errorField").queue(function () {
			setTimeout(function(){
				$("#errorField").fadeOut();
			},5000);
			$(this).dequeue();
		});
		$("#errorField").dequeue();
	}
};

var checkErrors = function() {
	if (error) {
		showError(error);
	}		 
};


var addCommentsHandler = function () {
	if ($('div.comments')) {
		
		// add toggle handler to "kommenteeri" links
		$('a.commentsLink').click(function(e) {
			e.preventDefault();
			var idAsArray = this.id.split("-");
			var postType = idAsArray[1];
			var postId = idAsArray[2];
			var commentsBlock = "#comments-"+postType+"-"+postId;
			$(commentsBlock).slideToggle(200);
		});
		
		// add post comment handler
		$('input.submitComment').click(function() {
			this.disabled = true;
			var idAsArray = this.id.split("-");
			var postType = idAsArray[1];
			var postId = idAsArray[2];
			if (postId) {
				var commentContent = $('#commentContent-'+postType+'-'+postId).val();
				if (commentContent.length > 0) {
					$.post("/apps/commentshandler.php", { postId: postId, commentType: postType, commentContent: commentContent },
						function(data){
							if (data['error']) {
								showError(data['error']);
							} else {
								$("#postCommentFields-"+postType+"-"+postId).after($("<div class='comment newComment'>"));
								var commentHtml = "<h3><strong><a href=\"/liikmed/#profile|"+data['userid']+"\">"+data['name']+"</a></strong><small class='gray'>"+data['commentDate']+"</small></h3><p>"+data['commentContent']+"</p>";
								$("div.newComment", "#comments-"+postType+"-"+postId).html(commentHtml);
								$("div.newComment").removeClass("newComment");
								$('#commentContent-'+postType+'-'+postId).val("");
							}
						}, "json");
				} else {
					showError("Kommentaaril puudub sisu!");
				}
			}
			this.disabled = false;
		});
		
	}
};

var addFancybox = function () {
	$("a.fancySingle").fancybox({
		'titleShow' : false,
		'type' : 'image',
		'hideOnContentClick' : true
	});
};

var trainersInSidebar = function () {
	$("#trainersCycle").cycle({
		delay:	2000,
		speed:	500
	});
};


$(document).ready(function(){
	grayOutInputs();
	checkErrors();
	addCommentsHandler();
	addFancybox();
	trainersInSidebar();
});