$.fn.getRand = function(){
	var rand = Math.floor(Math.random()*10000000001);
	//console.log(rand);
	return rand;
}

$.fn.setLightBoxMenu = function(){
	
	// behavior van lightBox navigation instellen
	$("#lightBoxNavigation li a").click(function(event){
		if($(this).attr("rel")!="active"){
			var reference = $(this).attr('title');
	
			$.get('/xhr/index/case/manage/section/'+reference+'/manage/true/rand/'+$(this).getRand(),{},function(data){
				
				$('#item').html(data);
				
				$(this).setLightBoxMenu();
				$(this).manageMail();
				$(this).openMail();
				$(this).selectRecipients();
				$(this).asyncPost();
				$(this).setCancel();
				
				 $("tr:odd").css("background-color", "#e7e7e7");
				 
				 // this behaviour is set several times throughout the script
				 // and makes sure that in several states of the mail module the close
				 // button knows what it should do when its clicked
				 $("#close a").click(function(event){
						$("#manage").expose({api: true}).close();
						event.stopPropagation();
				 });
				
			});
		}
		return false;
	
	});
}

$.fn.setCancel = function(){

	$(".imagecancel").click(function(event){
		
		event.preventDefault();
		
		$.get('/xhr/index/case/manage/section/inbox/manage/true/rand/'+$(this).getRand(),{},function(data){
			
			$('#item').html(data);
			
			$(this).setLightBoxMenu();
			
			 $("#close a").click(function(event){
					$("#manage").expose({api: true}).close();
					event.stopPropagation();
			 });
			
			$(this).manageMail();
			$(this).openMail();
			$(this).selectRecipients();
			$(this).asyncPost();
			
			event.stopPropagation();
			
		});
	});

}

// managing the mail means marking and deleting
$.fn.manageMail = function(){
	
	$('#pane1').jScrollPane();
	
	// if the user clicks on one of the mailOptions anchors
	$('#mailOptions a').click(function(event){
		
		// we dont want the default anchor behaviour so we prevent it
		event.preventDefault();
		//alert("c"); 
		// the manage actions is defined by the title attribute of the anchor element
		var action = $(this).attr('title');
		
		// the section can be inbox or sent items
		var section = $(this).attr('section');
		
		// we loop trough all the selected checkboxes
		// and for every selected message we call the mark case of the xhr controller
		$('input:checked').each(function(n){
		
			var value = $(this).val();
			//alert('/xhr/index/case/mark/action/'+action+'/id/'+value+'/section/'+section+'/rand/'+Math.floor(Math.random()*11));
			$.get('/xhr/index/case/mark/action/'+action+'/id/'+value+'/section/'+section+'/rand/'+$(this).getRand(),{},function(data){
				
				$('#item').html(data);
				
				$(this).setLightBoxMenu();
				$(this).manageMail();
				$(this).openMail();
				
				$("#close a").click(function(event){
					$("#manage").expose({api: true}).close();
					event.stopPropagation();
				});
				
			});
			$.get('/xhr/index/case/getUnread',{},function(response){
				$('#linksUnreadMessages').html(response);
			});
		});
		
		return false;
		
	});
}

// openening mail can also be goto sender public profile
$.fn.openMail = function(){

	$('a[title="openMail"]').click(function(event){    	
	   	
		event.stopPropagation();
	   	
	   	var id = $(this).attr('message');

	   	$.get('/xhr/index/case/manage/section/message/id/'+id,{},function(data){
			
			$('#item').html(data);
			
			$(this).setLightBoxMenu();
			$("#close").click(function(event){
				$("#manage").expose({api: true}).close();
				event.stopPropagation();
			});
			
			// add behavior to the reply anchor
			$('.mailMessageReply a').click(function(event){
				var action = $(this).attr('action');
				var message = $(this).attr('message');
				
				// for a reply we retrieve the compose message form
				if(action.indexOf("reply") != -1){
					
					
					// for the replyAll we send the recipients along with requesting the compose form
					if(action == "replyAll"){
						var replyAll = 'true';
					} else {
						var replyAll = 'false';
					}
					var recipient = $(this).attr('recipient');
					
					// retrieve the compose form and show it in the item layer
					$.get('/xhr/index/case/manage/section/compose/manage/true/recipient/'+recipient+'/message/'+message+'/replyAll/'+replyAll,{},function(data){
						$('#item').html(data);
						$(this).setLightBoxMenu();
						$(this).manageMail();
						$(this).openMail();
						$(this).selectRecipients();
						$(this).asyncPost();
						$(this).setCancel();
						
						
					
					});
				
				// for anything else wich is decline of accept we process the action
				} else {
				
					var recipient = $(this).attr('recipient');
					
					// retrieve the compose form and show it in the item layer
					$.get('/xhr/index/case/invitation/action/'+action+'/recipient/'+recipient+'/message/'+message,{},function(data){
				
						$('#item').html(data);
						$(this).setLightBoxMenu();
						$(this).manageMail();
						$(this).openMail();
						$(this).selectRecipients();
						$(this).asyncPost();
						$(this).setCancel();
					
					});
				
				}
				event.stopPropagation();
			})
		});
		$.get('/xhr/index/case/getUnread',{},function(response){
			$('#linksUnreadMessages').html(response);
		});
		
		
	});
}

// when a recipient is clicked, the name is shown in the recipients field and the id is stored in the hidden recipients field
$.fn.selectRecipients = function(){

	
	$('#composeRecipients :checkbox').click(function(event){
		
		// retrieve foreach checkbox the corresponding membername
		var rawRecipient = $(this).val().split('|');
		
		var recipient = rawRecipient[0];
		var idRecipient = rawRecipient[1];
		
		// get the current string of recipients
		var currentRecipient = $(':input[name=recipients]').val();
		var currentIdRecipient = $(':input[name=idrecipients]').val();
		
		// when member is clicked, add her to the recipients string
		if($(this).is(':checked')){
		
			var recipients = currentRecipient+recipient+'; ';
			var idRecipients = currentIdRecipient+idRecipient+'; ';
		
		// else remove her from the recipients string
		} else {
		
			var recipients = currentRecipient.replace(recipient+'; ','');
			var idRecipients = currentIdRecipient.replace(idRecipient+'; ','');
			
		}
		
		// show the recipients string in the recipients field
		$(':input[name=recipients]').val(recipients);
		$(':input[name=idrecipients]').val(idRecipients);
		
	});
}

// the method wich takes care of enabling a async post of the compose form in the lightbox
$.fn.asyncPost = function(){
	
	//alert("asyncPost");
	var options = { 
		target: "#item",
	    beforeSubmit:  validateMessage,  	// pre-submit callback 
	    success:       outputMailMessage  		// post-submit callback 
	}; 
			    
    $('.error').hide();
 
    // bind to the form's submit event 
    $('#xhr').submit(function() { 
    	
    	// alert("lightboxsubmit");
        $(this).ajaxSubmit(options); 
		return false;
        
    });
    
    // validate the message to be send
	function validateMessage(formData, jqForm, options) { 
	    var queryString = $.param(formData);
	    var composeNum = 1;
	    
	    if($('input[name="recipients"]').val() == ''){
    	
    		$("#compose1").html('Please select a recipient');
	       	$("#compose1").show();
	       	composeNum++;
	       	
	       	var invalid = true;
    	
    	} else {
    		
    		var invalid = false;
    		 $("#compose1").hide();
    	}
	    
	    for (var i=0; i < formData.length; i++){
	       if(formData[i].value == ''){
	    	   //console.log(formData[i].name);
	       		
	       		var invalid = true;
	       		
	       		if(formData[i].name=="subject"){
	       			$("#compose"+(i+composeNum)).html('Please add a subject for your message');
	       		} else if(formData[i].name=="text"){
	       			$("#compose"+(i+composeNum)).html('Please add your message');
	       		} else{
	       			$("#compose"+(i+composeNum)).html(formData[i].name+' required');
	       		}
	       		
	       		$("#compose"+(i+composeNum)).show();
	       		
	       	} else {
	       		$("#compose"+(i+composeNum)).hide();
	       	}
    	}
    	
    	if(invalid){
    		return false;
    	} else {
    		return true;
	    }
	} 
	 
	// when a message is send
	function outputMailMessage(responseText, statusText)  { 
	 	
		
		/*$('#composeMessage').hide();
		$('#composeRecipients').hide();
		
		$('#xhr').resetForm();
		$('#xhr').hide();
		
		$('#recipients').resetForm();
		$('#recipients').hide();*/
		
		$('#item').html(responseText);
		$(this).setLightBoxMenu();
		
		$(this).oneTime(2000, function(){
			
			$.get('/xhr/index/case/manage/section/inbox/manage/true/rand/'+$(this).getRand(),{},function(data){
			
				$('#item').html(data);
				
				$(this).setLightBoxMenu();
				$(this).manageMail();
				$(this).openMail();
				$(this).selectRecipients();
				$(this).asyncPost();
				
				$("#close a").click(function(event){
					$("#manage").expose({api: true}).close();
					event.stopPropagation();
				});
			
			});
			
		});
		
	return false;   
	}

}

$(function() {

	// setup exposing
	$("#manage").expose({	
		
		// a custom mask ID
		maskId:'mask',

		// grow the ball when exposing starts
		onBeforeLoad: function() {
			
			this.getExposed().animate({
				marginLeft: "0px",
				width: "800px"
				},750);
				
			$('#sections').css({width:"160px"});	
			$('#close').fadeIn('slow');
			
			
		},

		// shrink the ball when exposing closes
		onBeforeClose: function() {
			
			this.getExposed().animate({
				marginLeft: "0px",
				width: "100px"
				},750);
			
			$('#item').hide();
			$("#close").fadeOut('fast');
			$('#sections').css({width:"140px"});
		},
		
		/**
		 * het inladen van manage elementen
		 */
		onLoad: function(){
			
			$('#item').fadeIn('slow');
			
			
			$(this).setLightBoxMenu();
			$(this).manageMail();
			$(this).openMail();
		
			
			/**
			 * when the template is ready, we will add some behavior to the dom
			 * prepare the message form when the DOM is ready
			 */  
			$(document).ready(function() { 
			    
			    $("tr:odd").css("background-color", "#e7e7e7");
			    
			}); 
			
			$("#close").click(function(event){
				$("#manage").expose({api: true}).close();
				event.stopPropagation();
			});
		},
		
		loadSpeed:1250,
		closeSpeed:1250,
		opacity:0.5

	// perform exposing when manage layer is clicked
	})
	$("#manage").click(function(event)  {
		
		var target = (event.target)? event.target : event.srcElement;
		var reference = target.href;
		
		if(reference && reference.indexOf('#') != -1 && !window.cm){
			$(this).expose({api: true}).load();
		}
		
		if(target.href){
			
			var hrefSection = target.href
			var rawSection = hrefSection.split('#');
			var section = rawSection[1];
			//console.log('/xhr/index/case/manage/section/'+section+'/manage/true/rand/'+$(this).getRand());
			$.get('/xhr/index/case/manage/section/'+section+'/manage/true/rand/'+$(this).getRand(),{},function(data){
				$('#item').html(data);
				$(this).setLightBoxMenu();
				$(this).openMail();
				$("#close").click(function(event){
					$("#manage").expose({api: true}).close();
					event.stopPropagation();
				});

			});
		};
	});
	
	////Doorgelinkt vanaf external notifications mail
	var urlForInbox=document.location.href;
	if(urlForInbox.indexOf('inbox/true') != -1 && !window.cm){
		///xhr/index/case/manage/section/inbox/manage/true/rand/226003788
		$('#manage').expose({api: true}).load();
		
			$.get('/xhr/index/case/manage/section/inbox/manage/true/rand/'+$(this).getRand(),{},function(data){
				$('#item').html(data);
				$(this).setLightBoxMenu();
				$(this).openMail();
				$("#close").click(function(event){
					$("#manage").expose({api: true}).close();
					event.stopPropagation();
				});

			});
	}
	// behavior for removing the personal photo
	$('#generalPhoto img').click(function(){
		
		// we use a generic xhr method called updateRegistration
		// in this case we update the registration with an empty photo
		$.post('/xhr/index/case/updateProfile/',{photo: ""},function(data){
			$(this).attr('src','/images/avatars/avatar.gif');
		});
	})
});
