var Message = Message ? Message : function() {
	var public = {
		template : null,
		popup_container: null,
		tooltip_parent: null,
		compose_tooltip_parent: null,
		mode: 'compose',
		initilize : function() {
			Message.template = $('#compose-message');
			Message.compose_tooltip_parent = $('#nav-message-compose');
		},
		targetedShowForm : function(el, roster_id, roles, from, to) {
			Message.showForm(el, 'compose');
			
			Message.popup_container.find('#MessageTargetingSpecificStaff').attr('checked', 'checked');
			
			if(roster_id) {
				Message.popup_container.find('#MessageTargetRoster').attr('checked', 'checked');
				Message.popup_container.find('#MessageTargetRosterId').val(roster_id);
			}
			
			if(from) {
				Message.popup_container.find('#MessageTargetDays').attr('checked', 'checked');
				Message.popup_container.find('#MessageTargetDayRangeFrom').val(from);
			}
			
			if(to) {
				Message.popup_container.find('#MessageTargetDays').attr('checked', 'checked');
				Message.popup_container.find('#MessageTargetDayRangeTo').val(to);
			}
			
			if(roles) {
				Message.popup_container.find('#MessageTargetRoles').attr('checked', 'checked');
				
				for (index in roles) {
					Message.popup_container.find('#Role' + roles[index] + 'Id').attr('checked', 'checked');
				}				
				Message.popup_container.find('.selector-area').each( function() {								
					var checked_elements = $(this).find('input:checkbox:checked');
					$(this).find('.selector-subgroup-toggler > .selected-count').html(checked_elements.length);
				});
			}
			
			Message.updateTargetDisplay();
			
			Message.tooltip_parent.qtip('api').updatePosition();
			
			Message.calculateRecipients();
		},
		targetedOneContactShowForm : function(el, contact_id) {
			Message.showForm(el, 'compose');
			
			Message.popup_container.find('#MessageTargetingOneStaff').attr('checked', 'checked');
			
			Message.popup_container.find('#MessageTargetToId').val(contact_id);			
			
			Message.updateTargetDisplay();
			
			Message.tooltip_parent.qtip('api').updatePosition();
			
			Message.calculateRecipients();
		},
		targetedAllContactsShowForm : function() {
			Message.showForm(el, 'compose');
			
			Message.updateTargetDisplay();
			
			Message.tooltip_parent.qtip('api').updatePosition();
			
			Message.calculateRecipients();
		},
		showForm : function(el, mode) {
			Message.mode = mode;
			
			Message.compose_tooltip_parent = el;
			
			if(Message.mode == 'compose') {
				Message.tooltip_parent = Message.compose_tooltip_parent;
			}
			
			$('#qtip_on').val('0');
			
			Helpers.checkAndQtip(Message.tooltip_parent);
			
			Message.tooltip_parent.qtip('api').options.position.target = $(Helpers.cm_target);
			Message.tooltip_parent.qtip('api').updatePosition();
			Message.tooltip_parent.qtip('show');
			Message.popup_container = Message.tooltip_parent.qtip('api').elements.content;
			
			Message.popup_container.html( Message.template.html() );

			Message.tooltip_parent.qtip('api').elements.title.find('.popup-title').html(Message.popup_container.find('.popup-header:first').html());
			
			// Bind events
			Message.bindEvents();
			setTimeout(function() {
				Message.popup_container.find('#MessageSubject').focus(); }, 1000);
		},
		archiveMessage : function(el, status) {
			el.find('.loading-cell').html('<img src="/img/loadingSmall.gif"/>');
			$.get('/manage/messages/ajax_message_delete/' + el.attr('rel') + '/' + status, function(data) {
				if(data.match(/^error/i)) {
					alert(data);
				} else {
					if(status == 1) {
						el.remove();
					} else {
						el.find('.loading-cell').html('&nbsp;');
					}
				}
			});
		},
		fillOutMessageTemplate : function(messagetempalte_id) {			
			$.get('/manage/messages/json_messagetemplate/' + messagetempalte_id, function(data) {
				var row = eval('(' + data + ')');
				Message.popup_container.find('#MessageMessagetemplateId').val(row.Messagetemplate.id);
				Message.popup_container.find('#MessageSubject').val(row.Messagetemplate.subject);
				Message.popup_container.find('#MessageBody').val(row.Messagetemplate.body);
				Message.popup_container.find('#MessageAllowReply' + row.Messagetemplate.allow_reply).attr('checked', 'checked');
				
				Message.calculateCharCount();
			});
		},
		bindEvents: function() {		
			Message.popup_container.find('#accordian-wrapper').accordion( { animated: false, autoHeight: false } );
			
			// Fix up rogue ids (ids that are deliberatly wrong in template)
			Message.popup_container.find('.rogue-ids').each(function() {
				var rogue_id = $(this).attr('id');
				$(this).attr('id', rogue_id.replace('rogue', ''));
			})
			
			// Init datepickers			
			var dates = Message.popup_container.find('#MessageTargetDayRangeFrom, #MessageTargetDayRangeTo').datepicker({
				defaultDate: "+1w",
				showAnim: 'slideDown',
				firstDay: 1,
				dateFormat: Helpers.Company.datepicker_format,
				showOtherMonths: true,
				selectOtherMonths: true,
				onSelect: function(selectedDate) {
					var option = this.id == "MessageTargetDayRangeFrom" ? "minDate" : "maxDate";
					var instance = $(this).data("datepicker");
					var date = $.datepicker.parseDate(instance.settings.dateFormat || $.datepicker._defaults.dateFormat, selectedDate, instance.settings);
					dates.not(this).datepicker("option", option, date);
				}
			});
			
			// Close popup
			Message.popup_container.find('.cancel').click( function() {
				Message.tooltip_parent.qtip('hide');
				return false;
			});
			
			// Message body changed
			Message.popup_container.find('#MessageBody').keyup(function(){
				Message.calculateCharCount();
			});
			
			// Message subject changed
			Message.popup_container.find('#MessageSubject').keyup(function(){
				Message.calculateCharCount();
			});
			
			// Message reply changed			
			Message.popup_container.find('input:radio[name="data[Message][allow_reply]"]').click(function(){
				Message.calculateCharCount();
			});
			
			// Use template radio changed
			Message.popup_container.find('input:radio[name="data[Message][use_template]"]').click(function(){
				if($(this).val() == 1) {
					Message.popup_container.find('#TemplateRow').show();
					// Get template message data and fill out
					Message.fillOutMessageTemplate(Message.popup_container.find('#MessageMessagetemplateId').val());
				} else {
					Message.popup_container.find('#TemplateRow').hide();
				}
				Message.tooltip_parent.qtip('api').updatePosition();
			});
			
			// Use template drop down changed
			Message.popup_container.find('#MessageMessagetemplateId').change(function(){
				// Get template message data and fill out
				Message.fillOutMessageTemplate($(this).val());
				Message.tooltip_parent.qtip('api').updatePosition();
			});
			
			// Targeting radio changed
			Message.popup_container.find('input:radio[name="data[Message][targeting]"]').click( Message.showRecalcualte );
			
			// Area name clicked and needs to slide
			Message.popup_container.find('.selector-subgroup-toggler').click( function() {
				var parent = $(this).parent();
				if(parent.hasClass('off')) {
					parent.parent().find('.on').removeClass('on').addClass('off').find('.selector-sub-roles').slideUp('slow');
					parent.removeClass('off').addClass('on').find('.selector-sub-roles').slideDown('slow');
					parent.find('.display-status').html('HIDE');
				} else {
					parent.removeClass('on').addClass('off').find('.selector-sub-roles').slideUp('slow');
					parent.find('.display-status').html('SHOW');
				}
			});
			
			// Role ticked/unticked need to update area totals
			Message.popup_container.find('.selector-sub-roles input:checkbox').click( function() {
				var container = $(this).parents('.selector-area:first');
				var checked_elements = container.find('input:checkbox:checked');
				container.find('.selector-subgroup-toggler > .selected-count').html(checked_elements.length);
				
				Message.showRecalcualte();
			});
			
			// Date fields blurred
			Message.popup_container.find('#MessageTargetDayRangeFrom, #MessageTargetDayRangeTo').keyup( Message.showRecalcualte );
			
			// Specific roster checkbox ticked/unticked
			Message.popup_container.find('#MessageTargetRoster').click( Message.showRecalcualte );
			
			// Specific days checkbox ticked/unticked
			Message.popup_container.find('#MessageTargetDays').click( Message.showRecalcualte );
			
			// Specific staff changed
			Message.popup_container.find('#MessageTargetToId').change( Message.showRecalcualte );
			
			// Specific roles checkbox ticked/unticked
			Message.popup_container.find('#MessageTargetRoles').click( Message.showRecalcualte );
			
			// Calculate pressed, post form via ajax and return list of possible recipients
			Message.popup_container.find('.calculate').click( function() {
				Message.calculateRecipients();
				return false;
			});
			
			// Validate, then move onto review section
			Message.popup_container.find('.review').click( function() {
				/* Validate and move onto review section */
				Message.popup_container.find('.invalid-icon').hide();
				var valid = true;
				
				var message = Message.popup_container.find("#MessageBody");
				if(message.val() == '') {
					message.parent().find('.invalid-icon').show();
					message.parents('.ui-accordion-content:first').prev().find('.invalid-icon').show();
					valid = false;
				}
				
				if(Message.popup_container.find('#RecipientsTableContainer input:checkbox:checked').length == 0) { 
					Message.popup_container.find('#RecipientsRow .invalid-icon').show();
					Message.popup_container.find('#RecipientsRow').parents('.ui-accordion-content:first').prev().find('.invalid-icon').show();
					valid = false;
				}
				
				if(valid) {
					Message.popup_container.find('#SendLink').hide();
					Message.popup_container.find('#MessageComposeContainer').hide();
					var review_container = Message.popup_container.find('#MessageReviewContainer');
					review_container.find('#MessageReviewTableContainer').html('<img id="RecipientsLoader" src="/img/loadingSmall.gif" alt="Loading..." />');
					review_container.show();
					
					var post_data = Message.popup_container.find('form').serialize();
					$.post('/messages/ajax_review_panel', post_data, function(data) {
						if(data.match(/^error/i)) {
							review_container.hide();
							Message.popup_container.find('#MessageComposeContainer').show();
							alert(data);
						} else {
							review_container.find('#MessageReviewTableContainer').html(data);
							Message.popup_container.find('#TemplateSave').click( function() {
								if($(this).attr('checked')) {
									Message.popup_container.find('#TemplateNameRow').show();
								} else {
									Message.popup_container.find('#TemplateNameRow').hide();								
								}
								Message.tooltip_parent.qtip('api').updatePosition();
							});
							Message.popup_container.find('#SendLink').show();
						}
					});
				}
				return false;
			});
			
			// Validate, save, send and close popup
			Message.popup_container.find('.send').click( function() {							
				/* Validate and post form */
				Message.popup_container.find('.invalid-icon').hide();
				
				var valid = true;
					
				var save_template = Message.popup_container.find('#TemplateSave');
				if(save_template && save_template.attr('checked')) {
					if(Message.popup_container.find('#TemplateSubject').val() == '') {
						Message.popup_container.find('#TemplateNameRow .invalid-icon').show()
						valid = false;
					}
				}
					
				var post_data = Message.popup_container.find('form').serialize();
				if(valid) {
					var review_container = Message.popup_container.find('#MessageReviewContainer');
					review_container.hide();
					var sending_loader_container = Message.popup_container.find('#SendingLoader');
					sending_loader_container.show();
					
					$.post('/messages/ajax_message_send', post_data, function(data) {
						if(data.match(/^error/i)) {
							review_container.show();
							sending_loader_container.hide();
							alert(data);
						} else {
							Message.tooltip_parent.qtip('hide');							
						}						
					});
					
				}
				return false;
			});
			
			// Validate, save, send and close popup
			Message.popup_container.find('.back').click( function() {							
				/* Remove all invalid fields and move back to compose stage */
				Message.popup_container.find('.invalid-icon').hide();
				
				Message.popup_container.find('#MessageComposeContainer').show();
				Message.popup_container.find('#MessageReviewContainer').hide();
				return false;
			});
		},
		showRecalcualte : function() {			
			Message.updateTargetDisplay();
			
			// Hide Staff chooser and loader and show recalculate link
			Message.popup_container.find('#CalculateContainer').show();
			Message.popup_container.find('#RecipientsLoader').hide();
			Message.popup_container.find('#RecipientsContainer').hide();
			Message.popup_container.find('#RecipientsRow .invalid-icon').hide();
			
			Message.tooltip_parent.qtip('api').updatePosition();
		},
		updateTargetDisplay : function() {
			var targeting_options = Message.popup_container.find('input:radio[name="data[Message][targeting]"]:checked');
			if(targeting_options.val() == 'Specific staff') {
				Message.popup_container.find('.specific-staff-row').show();
				Message.popup_container.find('#OneStaffRow').hide();
				
				if(Message.popup_container.find('#MessageTargetRoster').attr('checked')) {
					Message.popup_container.find('#SpecificRosterRow').show();
				} else {
					Message.popup_container.find('#SpecificRosterRow').hide();
				}
				
				if(Message.popup_container.find('#MessageTargetDays').attr('checked')) {
					Message.popup_container.find('#SpecificDaysRow').show();
				} else {
					Message.popup_container.find('#SpecificDaysRow').hide();
				}
				
				if(Message.popup_container.find('#MessageTargetRoles').attr('checked')) {
					Message.popup_container.find('#SpecificRolesRow').show();
				} else {
					Message.popup_container.find('#SpecificRolesRow').hide();
				}
			} else if(targeting_options.val() == 'One staff') {
				Message.popup_container.find('.specific-staff-row').hide();
				Message.popup_container.find('#OneStaffRow').show();
			} else {
				Message.popup_container.find('.specific-staff-row, .specific-staff-sub-row').hide();
				Message.popup_container.find('#OneStaffRow').hide();
			}
			
			Message.tooltip_parent.qtip('api').updatePosition();
		},
		calculateRecipients : function() {
			var calculate_container = Message.popup_container.find('#CalculateContainer');
			calculate_container.hide();
			Message.popup_container.find('#CalculateContainer a').html('Recalculate and edit possible recipients');
			var recipients_loader = Message.popup_container.find('#RecipientsLoader');
			recipients_loader.show();				
			
			var post_data = Message.popup_container.find('form').serialize();
			$.post('/messages/ajax_get_recipients', post_data, function(data) {
				recipients_loader.hide();
				if(data.match(/^error/i)) {
					calculate_container.show();
					alert(data);
				} else {
					Message.popup_container.find('#RecipientsContainer').show();
					Message.popup_container.find('#RecipientsTableContainer').html(data);						
				}
			});
		},
		calculateCharCount : function() {
			var subject = Message.popup_container.find('#MessageSubject').val();
			var body = Message.popup_container.find('#MessageBody').val();
			var respond = Message.popup_container.find('#MessageAllowReply1');
			var company_id = Message.popup_container.find('#MessageCompanyId').val();
			var staff_backend = Message.popup_container.find('#MessageStaffBackend').val();
			var char_count = body.length;
			if(subject != '') {
				char_count += 8 + subject.length;
			}
			if(respond.attr('checked')) {
				char_count += 52 + staff_backend.length + company_id.length;
			} else {
				char_count += 19 + staff_backend.length + company_id.length;
			}
			var sms_count = Helpers.calculateSMSCredits(char_count);
			Message.popup_container.find('#char-count').html(char_count + ' Chars.(' + sms_count + ' SMS credits)');
		}
	}
	return public;
}();
