/*\
******************************************
	Pm - javascript lib
******************************************	
\*/
	function Pm(){
		this.unReadPms = {};
		this.box = 0;
		this.box_count = 0;
		this.unreadInbox = 0;
		this.unreadOutbox = 0;
		this.unreadTrash = 0;
		this.currentPage = 1;
		this.removeIds = [];
		this.MailNotificationsCache = false;
		this.status = 'close';
		
		/* actions */
		this.newPmBox = function(fid){
			$.facebox.settings.opacity = 0.5;
			$.facebox.settings.modal = true;
			futboleaLoadingBox();
			
			$.ajax({
				type: "POST",
				dataType: "json",
				url: "ajax/pm_get_send_box.php",	
				data: ({ fid: fid }),
				success: function(data){
					/* evaluate result */
					if ( data.result == 'done') {
						$.facebox(data.html,'',1);
						if (fid == 0){
							$("#msg_to").focus();
						
							$('#msgToBox').tagdragon({
								'field':'msg_to',
								'cache':true,
								'charMin':'3',
								'url':'ajax/member_search_friends_messages.php',
								'tagboxClass': 'msgToBox',
								onSelectedItem: function(val) { 
										$("#msgToBox").hide();
										$("#suggest_help").hide();
										$("#msgToBox").before('<span id="msg_to_span">' +val.member_name+ ' ' +val.member_lastname+ ' <a href="javascript:pm.changeTo();">cambiar</a></span>');
										$("#friend_pid").val(val.member_id);	
										$("#pm_subject").focus();
								}
							});	
						}						
					}
				}
			});
		}

		/* actions */
		this.sendPm = function(prevId, modo){
			var fid;
			var body;
			
			if (modo == 'POPUP'){
				fid = $("#friend_pid").val();
				body = encodeURIComponent($("#pm_pbody").val());
				var subject = encodeURIComponent($("#pm_psubject").val());
			}else{
				$("#ButtonRepply").attr("href", "javascript:void();");
				$("#ButtonRepply").attr("disabled", true );
				$("#ButtonRepply").toggleClass("disabled");
				
				var subject = encodeURIComponent($("#pm_subject").val());
				body = encodeURIComponent($("#pm_body").val());
				fid = $("#friend_id").val();
			}
			
			if ( fid == 0 || fid == ''){
				if (modo == 'POPUP'){
					$("#pm_box_msg").show();
				}	
			}else{
			
				/* pre assign variables */
				
				
				if (modo == 'POPUP'){
					futboleaLoadingBoxNew();
				}else{
				
				}
				
				$.ajax({
					type: "POST",
					dataType: "json",
					url: "ajax/pm_send.php",
					async: true,
					data: ({ fid: fid, subject: subject, body: body, prev_id: prevId}),	
					success: function(json){
						/* evaluate result */
						if ( json.result == 'done')
						{
							if (modo == 'POPUP'){
								$.facebox.settings.opacity = 0;
								$.facebox.settings.modal = false;
								$.facebox(futboleaOkBox(json.msg),'',0);
							}else{
								$("#MessageReplyBox").hide();
								$("#MessageReplyAlertBox").show();
							}
							
							futboleaCloseBoxTimer();
						}
					}
				});			
			}
		}
		
		this.changeTo = function(){
			$("#msgToBox").show();
			$("#suggest_help").show();
			$("#msg_to_span").remove();	
			$("#friend_pid").val(0);
			$("#msg_to").val("");
			$("#msg_to").focus();
		}
		
		this.paging = function(page){
			var me;
			me = this;
			
			/* page */
			if (page == 'next'){
				page = this.currentPage + 1;
			}else if(page == 'prev'){
				page = this.currentPage - 1;
			}
			
			if (page < 1){
				page = 1;
			}
			
			// Hide the AlertBox if any
			$("#AlertBox").hide();
			this._showLoading();
			$("#InfoBox").hide();
			
			$.ajax({
				type: "POST",
				dataType: "json",
				url: "ajax/pm_get_messages.php",
				data: ({page: page, box: this.box, max: $("#display_amount").val(), order: $("#sort_by").val() }),	
				success: function(json){
					/* evaluate result */
					if ( json.result == 'done')
					{
						$("#MessagesList").html(json.private_message_list);
						if (json.update_page != 0){
							me.currentPage = json.update_page;
						}else{
							me.currentPage = page;
						}
						me._setActions();
						me._hideLoading();
					}
					
					me.box_count = json.count;
					if (json.count == 0){
						$("#InfoBox").show();
					}
				}
			});			
		}

		this.getPmsNotifications = function(){
			$("#MailNotificationTab").toggleClass('open');
			$("#MailNotificationTab").toggleClass('close');
			
			if (notification.status == 'open'){
				$("#slNotificationContent").hide();
				$("#slNotificationTab").removeClass('open');
				$("#slNotificationTab").addClass('close');
				notification.status = 'close';
			}				
			if (this.status == 'close'){
				$("#MailNotificationContent").show();
				this.status = 'open';
				if (this.MailNotificationsCache == false){
					this.MailNotificationsCache = true;
					$.ajax({
						type: "POST",
						dataType: "json",
						url: 'ajax/pm_get_messages_notifications.php',
						async: true,
						success: function(data){
							if ( data.result == "done") {
								$("#MailNotificationContent").html(data.html);
								$("#MailNotificationTab").html('<img src="images/system/minialert_mail_off_16x16.png" width="16" height="16" />');
							} else {
								alert(data.result);
							}
						}
					});	
				}
			}else{
				$("#MailNotificationContent").hide();
				this.status = 'close';
			}
		}
	
		this.changeBox = function(box){
			this.box = box;
			this._evalButtonsStates(true);
			if (this.box == 2){
				$("#readAll").hide();
				$("#unreadAll").hide();
			}else{
				$("#readAll").show();
				$("#unreadAll").show();
			}
			
			this.paging(1);
			
			switch(this.box)
			{
				case 0:
					$("#pm_inbox").css("font-weight", "bold");
					$("#pm_outbox").css("font-weight", "normal");
					$("#pm_trash").css("font-weight", "normal");
					$("#deleteAll").html(langPopup['POPUP_PM_DELETE']);
					$("#deleteAll").attr("href","javascript:pm.remove(0, 1, 'CENTER');");
					$("#pm_empty_recycle_li").css("display", "none");
					break;
				case 1:
					$("#pm_inbox").css("font-weight", "normal");
					$("#pm_outbox").css("font-weight", "bold");
					$("#pm_trash").css("font-weight", "normal");
					$("#deleteAll").html(langPopup['POPUP_PM_DELETE']);
					$("#deleteAll").attr("href","javascript:pm.remove(0, 1, 'CENTER');");
					$("#pm_empty_recycle_li").css("display", "none");
					break;
				case 2:
					$("#pm_inbox").css("font-weight", "normal");
					$("#pm_outbox").css("font-weight", "normal");
					$("#pm_trash").css("font-weight", "bold");	
					$("#deleteAll").html(langPopup['POPUP_PM_RESTORE']);
					$("#deleteAll").attr("href","javascript:pm.remove(0, 0, 'CENTER');");
					$("#pm_empty_recycle_li").css("display", "inline");
					break;			
			}	
		}
		
		this.remove = function(id, mode, page){
			var pm_ids = [];
			var me;
			
			pm_ids = this._getChecked(id);
			
			me = this;
			
			if ( pm_ids.length > 0 ){
				$("#LoadingBox").css("visibility", "visible");
				this.removeIds = []; // reset remove array
				$.ajax({
					type: "POST",
					dataType: "json",
					url: "ajax/pm_change_delete_status.php",
					data: ({mode : mode, 'pms[]': pm_ids }),	
					success: function(json){
						/* evaluate result */
						if ( json.result == 'done')
						{
							me._removeComments(pm_ids, mode, page);
						}
						$("#LoadingBox").css("visibility", "hidden");
					}
				});
			}
		}

		this.unDo = function(pm_ids){
			var me;
			var new_unread = 0;
			
			me = this;
			
			if ( pm_ids.length > 0 ){
				$("#LoadingBox").css("visibility", "visible");
				
				$.ajax({
					type: "POST",
					dataType: "json",
					url: "ajax/pm_change_delete_status.php",
					data: ({mode : 0, 'pms[]': pm_ids}),	
					success: function(json){
						$("#LoadingBox").css("visibility", "hidden");
						
						/* getUnreadCount */
						for (var i = 0; i < pm_ids.length; i++) {
							if ( !$("#pm_main_" + pm_ids[i]).hasClass("old") ){
								new_unread = new_unread + 1;
							}
						}
						
						/* Update read status */
						switch(me.box)
						{
							case 0:
								me.unreadInbox = parseInt(me.unreadInbox) + parseInt(new_unread);
								if ( me.unreadInbox > 0){
									$("#unreadCountCenterInbox").html("(" + me.unreadInbox + ")");
								}else{
									$("#unreadCountCenterInbox").html("");	
								}
								break;
							case 1:
								me.unreadOutbox = parseInt(me.unreadOutbox) + parseInt(new_unread);
								if ( me.unreadOutbox > 0){
									$("#unreadCountCenterOutbox").html("(" + me.unreadOutbox + ")");
								}else{
									$("#unreadCountCenterOutbox").html("");
								}
								break;
						}	
						me.unreadTrash = parseInt(me.unreadTrash) - parseInt(new_unread);
						if ( me.unreadTrash > 0){
							$("#unreadCountCenterTrash").html("(" + me.unreadTrash + ")");
						}else{
							$("#unreadCountCenterTrash").html("");
						}
					}
				});
			}
		}
		
		this.changeReadStatus = function(id, status, page){
			var pm_ids = [];
			var me;
			
			pm_ids = this._getChecked(id);	
			
			me = this;
			
			if ( pm_ids.length > 0 ){
				$.ajax({
					type: "POST",
					dataType: "json",
					url: "ajax/pm_change_read_status.php",
					data: ({status : status, 'pms[]' : pm_ids, box : this.box}),	
					success: function(json){
						/* evaluate result */
						if ( json.result == 'done')
						{
							this.unread = json.unread;
							me._changeReadStatus(pm_ids, status, json, page);
						}
						else
						{
							alert(json.result);
						}
					}
				});	
			}				
		}
		
		this.report = function(type, id){
			$.facebox.settings.opacity = 0.5;
			$.facebox.settings.modal = true;
			futboleaLoadingBox();
			
			$.ajax({
				type: "POST",
				dataType: "json",
				url: "ajax/pm_get_report_box.php",	
				data: ({ key: id, type: type }),
				success: function(data){
					/* evaluate result */
					if ( data.result == 'done') {
						$.facebox(data.html,'',1);
					}
				}
			});			
		}
		
		this.emptyRecycle = function(){
			$("#LoadingBox").css("visibility", "visible");
			$.ajax({
				type: "POST",
				dataType: "json",
				url: "ajax/pm_empty_recycle.php",
				success: function(json){
					/* evaluate result */
					if ( json.result == 'done')
					{
						$("#LoadingBox").css("visibility", "hidden");
						$("#InfoBox").fadeIn();
						$("#MessagesList").html("");
						this.unreadTrash = 0;
						$("#unreadCountCenterTrash").html("");
					}
				}
			});		
		}
		
		/* toolbar actions */
		this.changeMax = function(){
			this.paging(1);
		}
		
		this.changeOrder = function(){
			this.paging(1);
		}
		
		this.checkAll = function(){
			$("input[id^='chk_pm_']").attr('checked', true);
			$("div[id^='pm_main_']").addClass('selected');
			this._evalButtonsStates(false);
		}
		
		this.uncheckAll = function(){
			$("input[id^='chk_pm_']").attr('checked', false);
			$("div[id^='pm_main_']").removeClass('selected');
			this._evalButtonsStates(false);
		}
		
		this.chechRead = function(){
			var id = '';
			
			this.uncheckAll();
			$("div[id^='pm_main_']").each( function(){
				if ( $(this).hasClass("old") ){
					id = $(this).attr("id");
					id = id.substring(8);
					$("#chk_pm_" + id).attr("checked", true);
					$("#pm_main_" + id).addClass("selected");
				}
			})
	
			this._evalButtonsStates(false);		
		}

		this.select = function(id){
			$("#pm_main_" + id).toggleClass('selected');
			this._evalButtonsStates(false);		
		}
		
		/* buttons states */
		this._evalButtonsStates = function(disabled){
			var hasChecked = false;
			
			if (disabled == false){
				$("input[id^='chk_pm_']:checked").each(function() {
					hasChecked = true;
					return;
				})	
			}
			
			if (hasChecked){
				$("#readAll").removeClass("disabled");
				$("#unreadAll").removeClass("disabled");
				$("#deleteAll").removeClass("disabled");
				$("#readAll").attr("href", "javascript:pm.changeReadStatus(0, 1, 'CENTER');");
				$("#unreadAll").attr("href", "javascript:pm.changeReadStatus(0, 0, 'CENTER');");
				if (this.box == 2){
					$("#deleteAll").attr("href", "javascript:pm.remove(0, 0, 'CENTER');");
				}else{
					$("#deleteAll").attr("href", "javascript:pm.remove(0, 1, 'CENTER');");
				}
			}else{
				$("#readAll").addClass("disabled");
				$("#unreadAll").addClass("disabled");
				$("#deleteAll").addClass("disabled");
				$("#readAll").attr("href", "javascript:void(0);");
				$("#unreadAll").attr("href", "javascript:void(0);");
				$("#deleteAll").attr("href", "javascript:void(0);");			
			}
		}
		
		/* internal tools */
		this._getChecked = function(id){
			var pm_ids = [];
			
			if (id == 0){
				$("input[id^='chk_pm_']:checked").each(function() {
						pm_ids.push($(this).val());
				})
			}else{
				pm_ids.push(id);
			}
			
			return pm_ids;
		}
		
		/* deprecated */
		this._disableRemoveLinks = function(pm_ids){
			for (var i = 0; i < pm_ids.length; i++) {
				$("#link_remove_" + pm_ids[i]).attr("href", "javascript:void(0);");
			}
		}

		this._enableRemoveLinks = function(pm_ids, mode, page){
			for (var i = 0; i < pm_ids.length; i++) {
				$("#link_remove_" + pm_ids[i]).attr("href", "javascript:pm.remove("+pm_ids[i]+", 1, '"+page+"');");
			}
		}
		/* deprecated */
		
		this._showLoading = function(){
			$("#LoadingBox").css("visibility", "visible");
		}

		this._hideLoading = function(){
			$("#LoadingBox").css("visibility", "hidden");
		}
		
		/*
			change read status
		*/
		this._changeReadStatus = function(pm_ids, status, data, page){
			for (var i = 0; i < pm_ids.length; i++) {
				/* change link and text */
				if (status == 1){
					/*enable mark as read*/
					$("#link_read_"  + pm_ids[i]).attr("href","javascript:pm.changeReadStatus("+pm_ids[i]+",0, '"+ page+"');");
					$("#link_read_"  + pm_ids[i]).html(langPopup['POPUP_PM_SET_UNREAD']);
					$("#pm_author_"  + pm_ids[i]).addClass("old");
					$("#pm_main_"    + pm_ids[i]).addClass("old");
					if (page == 'CENTER'){
						$("#pm_main_"    + pm_ids[i]).removeClass("unread");
					}					
					$("#pm_subject_" + pm_ids[i]).addClass("old");
				}else{
					/*enable mark as unread*/
					$("#link_read_"  + pm_ids[i]).attr("href","javascript:pm.changeReadStatus("+pm_ids[i]+",1, '"+ page+"');");
					$("#link_read_"  + pm_ids[i]).html(langPopup['POPUP_PM_SET_READ']);
					$("#pm_author_"  + pm_ids[i]).removeClass("old");
					$("#pm_main_"    + pm_ids[i]).removeClass("old");
					if (page == 'CENTER'){
						$("#pm_main_"    + pm_ids[i]).addClass("unread");
					}					
					$("#pm_subject_" + pm_ids[i]).removeClass("old");					
				}
				
				
			}
			
			/* Update read status */
			switch(this.box)
			{
				case 0:
					if (data.unread > 0){
						$("#unreadCountCenterInbox").html("(" + data.unread + ")");
					}else{
						$("#unreadCountCenterInbox").html("");
					}
					this.unreadInbox = parseInt(data.unread);
					break;
				case 1:
					if (data.unread > 0){
						$("#unreadCountCenterOutbox").html("(" + data.unread + ")");
					}else{
						$("#unreadCountCenterOutbox").html("");
					}
					this.unreadOutbox = parseInt(data.unread);
					break;
				case 2:
					if (data.unread > 0){
						$("#unreadCountCenterTrash").html("(" + data.unread + ")");
					}else{
						$("#unreadCountCenterTrash").html("");
					}
					this.unreadTrash = parseInt(data.unread);
					break;
			}
			
			/* update notification message box */
			if (this.box == 0){
				if (this.unreadInbox > 0){
					$("#MailNotificationTab").html('<img src="images/system/minialert_mail_on_16x16.png" width="16" height="16" /><span class="status tinyrnd">' +this.unreadInbox+ '</span>');
				}else{
					$("#MailNotificationTab").html('<img src="images/system/minialert_mail_off_16x16.png" width="16" height="16" />');
				}
			}
		}
		
		this._removeComments = function(pm_ids, mode, page){
			var new_count = 0;
			var new_inbox = 0;
			var new_outbox = 0;
			
			for (var i = 0; i < pm_ids.length; i++) {
			
				if (page == 'CENTER'){
					$("#pm_main_" + pm_ids[i]).slideUp();
				}else{
					if (mode == 1){
						$("#link_remove_" + pm_ids[i]).attr("href","javascript:pm.undoComments('READ');");
						$("#link_remove_" + pm_ids[i]).html(langPopup['POPUP_PM_RESTORE']);
					}else{
						$("#link_remove_" + pm_ids[i]).attr("href","javascript:pm.remove("+pm_ids[i]+", 1, 'READ');");
						$("#link_remove_" + pm_ids[i]).html(langPopup['POPUP_PM_DELETE']);
					}
				}
				
				if (mode == 1) {
					this.removeIds.push(pm_ids[i]);
				}
				if ( !$("#pm_main_" + pm_ids[i]).hasClass("old") ){
					if (this.box == 2){
						if ( $("#pm_main_" + pm_ids[i]).hasClass("inbox") ){
							new_inbox++;
						}else{
							new_outbox++;
						}	
					}
					new_count = new_count + 1;
				}
			}
			if (mode == 1){
				$("#AlertBox").slideDown("fast");
			}		
			
			this.box_count = this.box_count - pm_ids.length;

						
			if (new_count > 0){
				//Update unread numbers
				switch(this.box)
				{
					case 0:
						this.unreadInbox = this.unreadInbox - new_count;
						if (this.unreadInbox > 0){
							$("#unreadCountCenterInbox").html("(" + this.unreadInbox + ")");
						}else{
							$("#unreadCountCenterInbox").html("");
						}
						
						this.unreadTrash = this.unreadTrash + new_count;
						if (this.unreadTrash > 0){
							$("#unreadCountCenterTrash").html("(" + this.unreadTrash + ")");
						}else{
							$("#unreadCountCenterTrash").html("");
						}
						
						break;
					case 1:
						this.unreadOutbox = this.unreadOutbox - new_count;
						if (this.unreadOutbox > 0){
							$("#unreadCountCenterOutbox").html("(" + this.unreadOutbox + ")");
						}else{
							$("#unreadCountCenterOutbox").html("");
						}
						
						this.unreadTrash = this.unreadTrash + new_count;
						if (this.unreadTrash > 0){
							$("#unreadCountCenterTrash").html("(" + this.unreadTrash + ")");
						}else{
							$("#unreadCountCenterTrash").html("");
						}
						
						break;
					case 2:
						this.unreadTrash = this.unreadTrash - new_count;
						if (this.unreadTrash > 0){
							$("#unreadCountCenterTrash").html("(" + (this.unreadTrash) + ")");
						}else{
							$("#unreadCountCenterTrash").html("");
						}
						
						this.unreadInbox = this.unreadInbox + new_inbox;
						if (this.unreadInbox > 0){
							$("#unreadCountCenterInbox").html("(" + this.unreadInbox + ")");
						}else{
							$("#unreadCountCenterInbox").html("");
						}
						
						this.unreadOutbox = this.unreadOutbox + new_outbox;
						if (this.unreadOutbox > 0){
							$("#unreadCountCenterOutbox").html("(" + this.unreadOutbox + ")");
						}else{
							$("#unreadCountCenterOutbox").html("");
						}
						
						break;
				}
			}
			
			if (this.box_count == 0 && this.box == 2){
				$("#InfoBox").fadeIn();
			}
		}
		
		this.undoComments = function(page){
			if (page == 'CENTER'){
				for (var i = 0; i < this.removeIds.length; i++) {
					$("#pm_main_" + this.removeIds[i]).slideDown();
				}	
			}else{
				$("#link_remove_" + this.removeIds[0]).attr("href","javascript:pm.remove("+this.removeIds[0]+", 1, 'READ');");
				$("#link_remove_" + this.removeIds[0]).html(langPopup['POPUP_PM_DELETE']);
			}
			
			$("#AlertBox").slideUp("fast");
			
			this.unDo(this.removeIds); //restore
			this.removeIds = [];	
		}
		
		this._setActions = function(){
			$("div[id^='pm_content_']").mouseenter(function() {
				var id;
				$("div[id^='pm_tools_']").hide();
				$(this).children().closest('div').show();
			})
			
			$("div[id^='pm_content_']").mouseleave(function() {
				$("div[id^='pm_tools_']").hide();
			})
		}
	}

	
	$(document).ready (function() {
		pm._setActions();
	})
