var update = "";
function RunAJAX(file, vars) 
{
   $.ajax({
   url: file,
   type: 'POST',
   dataType: 'html',
   data: vars,
   timeout: 5000,
   async:false,
   error: function(){
    RunAJAX(file, vars);
   },
   success: function(html){
	   update = html;
   }
  });
}


$(document).ready(function(){

/*

Al enviar la peticion de update o delete de un msj, validar en el php que 
el usuario registrado en la session sea el verdadero dueño del msj en cuestion.

*/

// OPEN MESSAGES


	// Display message
	$(".msg_read").click(function(){
		var id = $(this).parent().parent().attr("id");
		// Call function #1 || 1 = ok / 0 = error
		RunAJAX(base+'modules/actions/message.php?action=1','id='+ id);
		if (update == '1') {
			if ($(this).parent().parent().hasClass("item_unread")){
				$(this).parent().parent().addClass("item");	
				$(this).parent().parent().removeClass("item_unread");	
			}
			$("#msg" + id).slideToggle("slow");
		}
	});
	// Display message - END
	
	// Delete Message
	$(".msg_delete").click(function(){
		// Call function #2
		var id = $(this).parent().parent().attr("id");
		if(confirm('Are you sure you want to delete this message?'))
		{
			RunAJAX(base+'modules/actions/message.php?action=2','id='+ id);
			if (update == '1') {
			if ($("#msg" + id).css("display") != 'none'){
				$("#msg" + id).slideToggle("slow");	
				}
			}
			$(this).parent().parent().fadeOut("slow");
		}
		
	});
	// Delete Message - END
	
	// Reply Message
	$(".msg_reply").click(function(){
		// Call function #2
		var id = $(this).parent().parent().attr("id");
		var to = $(this).parent().attr("rel");
		
		RunAJAX(base+'modules/actions/message.php?action=1','id='+ id);
		if (update == '1') 
			location.href=base+'send/'+to;	
		
	});
	// Reply Message - END	

// SEND MESSAGES

	$(".change_dest").click(function(){
		var platestate = $(this).parent().parent().attr("id");								 
		var pieces = platestate.split("-");
		$("#plate").val(pieces[0]);
		$("#state").val(pieces[1]);
		
		
	})

	

})