$(document).ready(function(){
	if (casUid && casUid != 0){
		setInterval( "checkMessages()", 180000 );
	}
	
	$("form#sendMessageForm").submit(function(event){
		event.preventDefault();
		event.stopPropagation();
		var _sendMessage = function(){
			$.post( $("form#sendMessageForm").attr('action') , 
					{
					 subject: $("#subject").val(),
					 body: $("#body").val(),
					 uid: $("#uid").val()
					}, 
				function(msg){
					$("#subject").val('');
					$("#body").val('');
					alert(msg);
				}
			);
		};
		loginCheck(_sendMessage);
	});
	
	$('#sendToFriend-dialog').detach().dialog({
		autoOpen: false,
		width: 400,
		height: 300,
		modal: true,
		zIndex : 12000,
		overlay: {
			opacity: 0.5,
			background: 'black'
		}
	});
	
	$('#sendToFriend-alert').detach().dialog({
		autoOpen: false,
		width: 400,
		height: 300,
		modal: true,
		zIndex : 12000,
		overlay: {
			opacity: 0.5,
			background: 'black'
		},
		buttons: {
			'Ok' : function () {
				$(this).dialog('close');
			}
		}
	});

	$(".sendToFriend").live("click", function(event){
		event.preventDefault();
		event.stopPropagation();
		var url = $(this).attr('href');
		var openDialog = function(){
			$.ajax({
				url: url,
				success: function(msg){
					$("#sendToFriend-dialog").html(msg);
					//$(".sendToFriendMsg").html(msg);
					//$(".sendToFriendMsg").show('fast');
					$("#sendToFriend-dialog").dialog("open");
				}
			});
		};
		loginCheck(openDialog);	
	});		
	
	$("#submitSendToFriend").live('click', function(event){
		event.preventDefault();
		event.stopPropagation();
		var type = $("#objType").val();
		$.post( $("form#sendToFriendForm").attr('action') , 
				{
			     objId: $("#objId").val(), 
				 objType: type,
				 to: $("#to").val(),
				 body: $("textarea#body").val()
				}, 
			function(msg){
				$("#sendToFriend-dialog").dialog("close");
				$('.sendToFriendAlert').html(msg);
				$('.sendToFriendAlert').show('fast');
				$('#sendToFriend-alert').dialog('open');
			}
		);
	});
});

function checkMessages(){
	if (casUid != 0) {
		$.ajaxSetup({async: false});
		$.getJSON(baseUrl+'auth/login-check',function(uid) {
			if(uid != 0) {
				casUid = uid;
			}
		});
		$.ajaxSetup({async: true});
		
		if (casUid != 0) {
			$.ajax({
				url: baseUrl + 'messages/index/check',
				success: function(msg){
					if (msg != '0'){
						$("#headerBoxLogin").html(msg);
					}
				}
			});
		}
	}
}

