var currentId;

$(document).ready(initIndex);

function initIndex()
{
//	$(".detailIt textarea").countChars();
	$(".detailIt").css("display","none");
	$(".contactBtn").click(showForm);
	$(".cancelBtn").click(hideForm);
	$(".sendBtn").click(sendMessage);	

	$("a.smallPicWrap").fancybox({
				'transitionIn'	: 'elastic',
				'transitionOut'	: 'elastic',
				'speedIn'		: 500, 
				'speedOut'		: 500,
				'overlayOpacity': 0.4,
				'easingIn'      : 'easeOutBack',
				'easingOut'     : 'easeInBack',
				'overlayColor'	: "black"
			});
}

function sendMessage()
{
	var message = $("#msg_"+currentId).val();

	if (message.length == 0) 
	{
		showMessage(gettext("The message can't be empty"));
		return false;
	}
	if (message.length > 140)
	{
		showMessage(gettext("Messge can't have more than 140 characters"));
		return false;
	}	
	
	$("#detail_"+currentId+" textarea").attr("disabled", "disabled");
	$("#loader_"+currentId).css("display","inline");
	$("#sendMsg_"+currentId+"_wrap").css("display", "none");
		
	var result = 
		$.ajax(
		{
			type: "POST",
			url: "/itinerary/message/"+currentId,
			data: "message="+message,
			success: successSendMsg,
			error: errorSendMsg
		});
	return false;
}

function errorSendMsg(response)
{
	$("#detail_"+currentId+" textarea").removeAttr("disabled");
	$("#loader_"+currentId).css("display","none");
	$("#sendMsg_"+currentId+"_wrap").css("display", "block");
	var error = response.responseText.split("error::")[1];
	if (error)
		showMessage(error);
	else
		showMessage(gettext("An unexpected error occured. Please try again in a moment."));
}

function successSendMsg(data)
{
	$("#detail_"+currentId+" textarea").removeAttr("disabled");
	$("#loader_"+currentId).css("display","none");
	$("#sendMsg_"+currentId+"_wrap").css("display", "block");
	
	hideForm();
	showMessage(gettext("The message was successfully sent"));
}

function showForm()
{
	if (currentId)
		hideForm();
	var id = $(this).attr("id").split("_")[1];
	
	//used to hide from outside
	currentId = id;
	
	$(this).parent().css("display", "none");
	
	$("#itinerary_"+id+" .searchUser .userInfoBtn").appendTo("#detail_"+id);
	$("#detail_"+id).css("display","block");
	$("#detail_"+id+" textarea").focus();
}

function hideForm()
{
	$("#contact_"+currentId).parent().css("display", "block");	
	$("#detail_"+currentId+" .userInfoBtn").appendTo("#itinerary_"+currentId+" .searchUser");
	$("#detail_"+currentId).css("display","none");
	$("#detail_"+currentId+" textarea").val("");
	currentId = null;
}


