var sendMessagePopup = null;
var validSendMessageGroups = null;

function sendMessage_grabPageForm(){
	var f = $('.contentHolder form#pageMessageForm');
	if ( f.length == 0 ) return;
	sendMessage_setupForm( f, false );
}


function sendMessage_showPopup( url ){
	var f = sendMessagePopup.find('form#popupMessageForm');
	f.find('input.clearOnSuccess, textarea.clearOnSuccess').val('');
	f.find('label.emailValidateError').remove();
	f.find('input.emailValidateError, textarea.emailValidateError').removeClass('emailValidateError');

	var group = 'main';
	var p = url.split('/');
	var pAdd = 1;
	var showUser = null;

	if ( $.inArray( p[1], validSendMessageGroups ) == -1 ) pAdd = 0;
	else group = p[1];
	if ( p.length > 3 + pAdd ) showUser = p[ 3 + pAdd ];

	var op = f.find('div#popUpMessage_groupOptions_' + group + ' select option');
	if ( !op.length ) return false;
	var e2 = f.find('select#emailTo');
	e2.find('option').remove();
	op.each( function() {
		if ( $(this).hasClass('listable_Yes') || $(this).attr('value') == showUser ) {
			var c = $(this).clone();
			if ( $(this).attr('value') == showUser ) c.attr( 'selected', 'selected' );
			e2.append(c);
		}
	} );
	if ( !e2.find('option').length ) return false;

	f.find('input[name=emailGroup]').val(group);

	sendMessagePopup.dialog('open');
}


function sendMessage_grabPopupForm(){
	sendMessagePopup = $('<div></div>');
	sendMessagePopup.append( $('#hiddenDivs #sendMessage_popup').remove().html() );
	buttonise(sendMessagePopup);
	var f = sendMessagePopup.find('form#popupMessageForm');
	f.find( '.contactFormSubmitError, .contactFormSubmitError .contactFormSubmitMessageMsg' ).hide();
	sendMessagePopup.dialog( {	title: sendMessagePopup.find('.popupTitle').html(), autoOpen: false, modal: true,
															close: function() { f.find('input.clearOnSuccess, textarea.clearOnSuccess').val(''); } } );

	var width = $(window).width() * 0.8;
	var height = $(window).height() * 0.85;
	if ( width > 420 ) width = 420;
	if ( height > 480 ) height = 480;
	var left = Math.round (( $(window).width() - width ) / 2);
	var top = Math.round (( $(window).height() - height ) / 4);
	sendMessagePopup.dialog( "option", "width", width).dialog( "option", "height", height).dialog( "option", "position", [left, top] );
	sendMessagePopup.find('.modalWindowClose').each( function(){ $(this).click ( function() { sendMessagePopup.dialog('close'); } ) } );

	sendMessage_setupForm( f, true );

	$('a:isKingslandContact:not(.noDynamicLink):not(.newsFeedInternalLink)').live ( 'click', function(event) {
		sendMessage_showPopup( $(this).attr('href') );
		return false;
	} );
}


function sendMessage_setupForm( f, isPopup ){
	f.validate( {	errorClass: 'emailValidateError',

								rules: {	emailContactFromName:		{ required: true, minlength: 3 },
													emailContactFromEmail:	{ required: true, email: true },
													emailSubject:						{ required: true, minlength: 5 },
													emailMessage:						{ required: true, minlength: 20 },
													emailSecCode:						{ required: true, remote: '/ajax/contact/sendMessage/preCheckCode' } },
								messages: { emailContactFromName:		{ required: "You must enter your name",
																											minlength: "We require your name to be at least 3 characters in length" },
														emailContactFromEmail:	{ required: "You must enter an email address",
																											email: 		"We require a valid return email address" },
														emailSubject:						{ required: "You must enter a subject for the message",
																											minlength: "The message's subject should be at least 5 characters long" },
														emailMessage:						{ required: "You must enter the details of your message",
																											minlength: "The message should be at least 20 characters long" },
														emailSecCode:						{ required: "You must enter the security code as shown in the image above",
																											remote:		"The security code is not correct" } },

								showErrors: function( errorMap, errorList ) {
									this.defaultShowErrors();
									f.find('label.emailValidateError:not(.ui-widget)').addClass( 'ui-widget ui-state-error ui-corner-all')
											.prepend('<span class="ui-icon ui-icon-alert" style="float: left; margin-right: .3em;"></span>');
								},

								submitHandler: function(form) {
									var errBox = f.find('.contactFormSubmitError');
									errBox.find('.contactFormSubmitMessageMsg').hide();
									errBox.hide();
									f.find('.contactFormSubmitSuccess').hide();

									f.ajaxSubmit( { dataType: 'json', url: '/ajax/contact/sendMessage/send',
										beforeSubmit: function(arr, $form, options) {
											f.find('select, input, textarea').addClass('sendingNow').attr( 'disabled', true );
											$.jGrowl('<p>Your message is being submitted. Please wait just a moment.</p>', { header: 'Submitting Message', life: 8000 } );
										},
										success: function(data) {
											f.find('select, input, textarea').attr( 'disabled', false ).removeClass('sendingNow');
											if ( data == null ) { alert( "No Data returned by server. This may be a program fault." ); return false; }
											if ( data.error != undefined ) {
												var errMsg = data.error.indexOf(' ') == -1 ? errBox.find( '.contactFormSubmitError_' + jqstr( data.error ) ) : '';
												if ( errMsg.length ) { errBox.show(); errMsg.show(); }
												$.jGrowl('<p></p>' + ( errMsg.length ? errMsg.html() : data.error ), { theme: 'ui-widget ui-state-error', header: 'Message Submission Error' } );
												return false;
											}

											if ( !isPopup ) f.find('.contactFormSubmitSuccess').show();
											else sendMessagePopup.dialog('close');
											$.jGrowl('<p>Your message has been sent and will be dealt with as soon as possible.</p>', { theme: 'ui-widget ui-state-highlight', header: 'Message Successfully Submitted' } );
											f.find('input.clearOnSuccess, textarea.clearOnSuccess').val('');
									} } );
								} } );
}


$(document).ready( function(){
	validSendMessageGroups = new Array();
	$('#sendMessage_popup div[id^=popUpMessage_groupOptions_]').each( function() {
		validSendMessageGroups.push( $(this).attr('id').replace( /^popUpMessage_groupOptions_/, '' ) );
	} );

	$.expr[':'].isKingslandContact = function( obj, index, meta, stack ){
		var url = $(obj).attr('href');
		if ( url == undefined ) return false;
		if ( !url.match( /\/contact\/sendMessage/ ) ) return false;
		if ( url.match( /^\/contact\/sendMessage(\/|$)/ ) ) return true;
		var i;
		for ( i in validSendMessageGroups ) {
			if ( url.match( new RegExp( '\/' + validSendMessageGroups[i] + '\/contact\/sendMessage(\/|$)' ) ) ) return true;
		}
		return false;
	};

	sendMessage_grabPageForm();
	sendMessage_grabPopupForm();
} );

