
var ldcms_js_debug_switch = false ;

function dates_check(form_id,select_name_prefix,start_end) {

	var formref = document.getElementById(form_id);
	var selects = ['year','month','day','hour','min'];
	var datetypes = ['start','end'];
	var datevals = ['',''];

	if ( formref.elements[select_name_prefix + 'end' + '_hour'].value == '' || formref.elements[select_name_prefix + 'end' + '_min'].value == '' ) {
		// only work on dates
		selects = ['year','month','day'];
	}
	
	for (n = 0; n < datetypes.length; n++) {
		
		for (i = 0; i < selects.length; i++) {
			var temp_value = formref.elements[select_name_prefix + datetypes[n] + '_' + selects[i]].value;
			if (temp_value == '9999') {
				datevals[n] += '0000';
			} else if (temp_value == '99') {
				datevals[n] += '00';
			} else if (temp_value == '') {
				if (selects[i] == 'year') {
					datevals[n] += '0000';
				} else {
					datevals[n] += '00';
				}
			} else {
				datevals[n] += temp_value;
			}
		}
		if (ldcms_js_debug_switch) {
			alert(datetypes[n] + ': ' + datevals[n]);
		}
	}

	if (datevals[0] > datevals[1]) {
		if (start_end == 'end') {
			datetypes = ['end','start'];
		}
		for (i=0; i<selects.length; i++) {
			formref.elements[select_name_prefix + datetypes[1] + '_' + selects[i]].selectedIndex = formref.elements[select_name_prefix + datetypes[0] + '_' + selects[i]].selectedIndex;
		}
	}

}


function showimage()
{
if (!document.images)
return
document.images.con_imgs.src=
document.con_form.con_img.options[document.con_form.con_img.selectedIndex].value
}


function checkAll(formId, cName, check ) {
	for (i=0,n=formId.elements.length;i<n;i++)
	if (formId.elements[i].className.indexOf(cName) !=-1)
		formId.elements[i].checked = check;
}


function openWin(url,name) {
	window.open(url, help, 'Width=300,Height=450,SCROLLBARS=1,RESIZABLE=1')
}


function icon_help_win(help_url) {
	var mainWin=null;
	if (navigator.appName == "Microsoft Internet Explorer") {
		mainWin = window.open(help_url, 'help', 'Width=300,Height=450,top=0,left=0,menubar=0,toolbar=0, SCROLLBARS=1');
   	}
	if (navigator.appName == "Netscape") {
		mainWin = window.open(help_url, 'help', 'Width=300,Height=450,top=0,left=0,menubar=0,toolbar=0, scrollbars=yes');
   	}	
   	self.name = "main";
}

function validate_mailer_form() {
	if ((! document.getElementById('choose_individuals_all') ) || document.getElementById('choose_individuals_all').checked) {
		// option to send to all users in selected groups is checked, or doesn't exist on the page meaning that we've got a list of users to choose from
		if (document.getElementById('mailing_subject').value.length > 0) {
			return confirm('Send broadcast e-mail now?');
		} else {
			alert('You must enter an e-mail subject before attempting to send your message.');
			document.getElementById('mailing_subject').focus();
			return false;
		}
	} else {
		return true;
	}
}




/**
 * This script contains embed functions for common TinyMCE plugins. This scripts are complety free to use for any purpose.
 */

function writeFlash(p) {
	writeEmbed(
		'D27CDB6E-AE6D-11cf-96B8-444553540000',
		'http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,40,0',
		'application/x-shockwave-flash',
		p
	);
}

function writeShockWave(p) {
	writeEmbed(
	'166B1BCA-3F9C-11CF-8075-444553540000',
	'http://download.macromedia.com/pub/shockwave/cabs/director/sw.cab#version=8,5,1,0',
	'application/x-director',
		p
	);
}

function writeQuickTime(p) {
	writeEmbed(
		'02BF25D5-8C17-4B23-BC80-D3488ABDDC6B',
		'http://www.apple.com/qtactivex/qtplugin.cab#version=6,0,2,0',
		'video/quicktime',
		p
	);
}

function writeRealMedia(p) {
	writeEmbed(
		'CFCDAA03-8BE4-11cf-B84B-0020AFBBCCFA',
		'http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,40,0',
		'audio/x-pn-realaudio-plugin',
		p
	);
}

function writeWindowsMedia(p) {
	p.url = p.src;
	writeEmbed(
		'6BF52A52-394A-11D3-B153-00C04F79FAA6',
		'http://activex.microsoft.com/activex/controls/mplayer/en/nsmp2inf.cab#Version=5,1,52,701',
		'application/x-mplayer2',
		p
	);
}

function writeEmbed(cls, cb, mt, p) {
	var h = '', n;

	h += '<object classid="clsid:' + cls + '" codebase="' + cb + '"';
	h += typeof(p.id) != "undefined" ? 'id="' + p.id + '"' : '';
	h += typeof(p.name) != "undefined" ? 'name="' + p.name + '"' : '';
	h += typeof(p.width) != "undefined" ? 'width="' + p.width + '"' : '';
	h += typeof(p.height) != "undefined" ? 'height="' + p.height + '"' : '';
	h += typeof(p.align) != "undefined" ? 'align="' + p.align + '"' : '';
	h += '>';

	for (n in p)
		h += '<param name="' + n + '" value="' + p[n] + '">';

	h += '<embed type="' + mt + '"';

	for (n in p)
		h += n + '="' + p[n] + '" ';

	h += '></embed></object>';

	document.write(h);
}


// JQUERY STUFF

var arrow_up_html = '&#x25BC;' ;
var arrow_down_html = '&#x25B2;' ;

$(document).ready(function(){
	
	setup_collapible('fieldset.collapsible','legend');

	setup_collapible();
	
	ee_setup_buttons();

});


// SETUP COLLAPSIBLE STUFF

function setup_collapible( collapsible_selector, toggle_selector ) {

	if (collapsible_selector==null) {
		collapsible_selector = '.collapsible' ;
	}

	if (toggle_selector==null) {
		toggle_selector = '.collapse-toggle' ;
	}

	if ($(collapsible_selector).length) {

		$(collapsible_selector+' '+toggle_selector).append('<span class="collapse-arrow"> ' + arrow_down_html + '</span>').wrapInner('<a href="#"></a>');
	
		$(collapsible_selector+' '+toggle_selector+' a').click( function(){
			var thisfieldset = $(this).parent().parent() ;
			thisfieldset.children().filter("p,table,div").toggle('fast');
			if ( thisfieldset.hasClass('collapsed') ) {
				thisfieldset.find('.collapse-arrow').html(' ' + arrow_down_html);
				thisfieldset.removeClass('collapsed');
				$(this).attr('title','Click to show');
			} else {
				thisfieldset.find('.collapse-arrow').html(' ' + arrow_up_html);
				thisfieldset.addClass('collapsed');
				$(this).attr('title','Click to hide');
			}
			return false;
		} );
	
		// TOGGLE UP/DOWN ARROW ON HOVER
		$(collapsible_selector+' '+toggle_selector+' a').hover( function(){
			$(this).find('.collapse-arrow').html(' ' + ($(this).parent().parent().hasClass('collapsed') ? arrow_down_html : arrow_up_html));
		}, function(){
			$(this).find('.collapse-arrow').html(' ' + ($(this).parent().parent().hasClass('collapsed') ? arrow_up_html : arrow_down_html));
		} );
	
		// COLLAPSE ANY FIELDSETS THAT ARE MEANT TO START OUT COLLAPSED
		$(collapsible_selector).filter('.collapsed').find(toggle_selector+' a').trigger('click');
		
	}

}




// POP-UP DIALOGUE OFFERING TEMPLATE FOR NEW CONTENT / CATEGORY / SECTION PAGES

function confirm_show_tinymce_templates(pg_title) {
	$(document).ready(function() {
		$("body").append('<div id="tinymce-tmpl-dialogue"><p>Do you want to start with a template or a blank page?<\/p><\/div>');
		$("#tinymce-tmpl-dialogue").dialog({
			bgiframe: true,
			resizable: false,
			title: pg_title,
			modal: true,
			overlay: {
				backgroundColor: '#000',
				opacity: 0.5
			},
			buttons: {
				'blank page': function() {
					$(this).dialog('close');
				},
				'template': function() {
					$(this).dialog('close');
					$("#tinymce_editor").tinymce().execCommand('mceTemplate',true);
				}
			}
		});
	});
}



/*
function jquialert1(title,msg,urlredirect) {
	$('body').append('<div id="jquialert" style="color: #900; font-weight: bold; display:none;"><\/div>');
	$('#jquialert').text(msg);
	$('#jquialert').dialog({
		autoOpen: true,
		modal: true,
		'title': title,
		width: 400,
		buttons: { 'OK': function(){
			$(this).dialog('close');
			$('#jquialert').remove();
			if (urlredirect) {
				window.location = urlredirect;
			}
		} }
	});
}
*/


// MISC USEFUL DIALOGUE BOX
function jquialert(title,msg,urlredirect) {
	jquidialogue( 'jquialert', title, $('<div/>').text(msg).html(), 'color: #900; font-weight: bold;', {
		autoOpen: true,
		modal: true,
		width: 400,
		buttons: {
			'OK': function(){
				$(this).dialog('close');
				if (urlredirect) {
					window.location = urlredirect;
				}
			}
		}
	} );
}





// HELPER FUNCTIONS FOR DIALOGUES

function jquidialogue(id,title,html,style,dialog_options) {
	if (! $('#'+id).length ) {
		$('body').append('<div id="'+id+'" style="display:none; '+style+'"><\/div>');
	}
	$('#'+id).html(html);
	if (! $('#'+id).hasClass('ui-dialog-content')) {
		$('#'+id).dialog(dialog_options);
	}
	$('#'+id).dialog('option','title',title);
	$('#'+id).dialog('open');
}


function jqui_dialogue_height(dialogue_selector) {
	if ($(dialogue_selector).hasClass('ui-dialog-content')) {
		return $(dialogue_selector).dialog('widget').parent().height();
	} else {
		return null;
	}
}


function jqui_close_and_remove_dialog(dialogue_selector) {
	if ($(dialogue_selector).hasClass('ui-dialog-content')) {
		$(dialogue_selector).dialog('close');
	}
	$(dialogue_selector).remove();
}


function jquiprogress_show(title,msg) {
	if (! $('#jquiprogress').length) {
		$('body').append('<div id="jquiprogress" style="color: #900; font-weight: bold; display:none;"><\/div>');
	}
	if (! $('#jquiprogress').hasClass('ui-dialog-content')) {
		$('#jquiprogress').html(msg);
		$('#jquiprogress').dialog({
			autoOpen: false,
			modal: true,
			width: 400
		});
	}
	$('#jquiprogress').dialog('option','title',title);
	$('#jquiprogress').html(msg);
	$('#jquiprogress').dialog('open');
}


function jquiprogress_hide() {
	jqui_close_and_remove_dialog('#jquiprogress');
}




/*
function ee_check_caq(pagetype,pageid) {
	$.getJSON(
		('/index.lasso?pg=ajax&f=check-caq&type=' + pagetype + '&id=' + pageid + '&' + g_sessionid),
		function(data){
			if (! data.success) {
				jquialert('Error','Sorry, there is already an update to the content pending approval.');
			}
		}
	);
}


function ldcms_verify_login(successfunction,errorfunction) {
	$.ajax({
		async: true,
		url: ('/index.lasso?pg=ajax&f=verify-login&' + g_sessionid),
		dataType: 'json',
		success: successfunction
	});
}
*/



// EASY-EDIT IN-PAGE EDITING

var ee_config_dialogue_done = false;


function ee_launch_step1(pagetype,pageid,srcid) {
	if ($("#"+srcid).length) {
		if (! ee_config_dialogue_done) {
			ee_config_dialogue();
			ee_config_dialogue_done = true;
		}
		var eed = $("#easy-edit-dialogue") ;
		eed.data('close-confirmed',false);
		eed.data('page-id',pageid);
		eed.data('page-type',pagetype);
		eed.data( 'page-is-html', $("#"+srcid).hasClass('page-text-html') );
		eed.data('elem-id',srcid);
		jquiprogress_show('Progress','Validating - please wait &hellip;');
		ee_launch_step2();
	} else {
		jquialert('Error','Could not locate content to be edited on this page. This is likely to be a bug with the web site - please contact the site admin with the URL of the page you are currently viewing and details of the content you tried to edit.');
	}
}


function ee_launch_step2() {
	var eed = $("#easy-edit-dialogue") ;
	$.ajax({
		async: true,
		url: ('/index.lasso?pg=ajax&f=ee-preflight-check&type='+eed.data('page-type')+'&id='+eed.data('page-id')+'&' + g_sessionid),
		dataType: 'json',
		success: function(result){
			if (result.success) {
				if (result.caqid) {
					// user can edit their existing update from the CAQ
					jquidialogue( 'editcaq', 'Update awaiting approval', 'You have already submitted an update to this content that is awaiting approval from an administrator.', 'color: #900; font-weight: bold;', {
						autoOpen: true,
						modal: true,
						width: 400,
						buttons: {
							'OK': function(){
								jquiprogress_hide();
								$(this).dialog('close');
							},
							'Make further changes': function(){
								$(this).dialog('close');
								ee_launch_step3(true,result.caqid);
							}
						}
					})
				} else {
					// user can edit OK
					ee_launch_step3(true);
				}
			} else {
				jquiprogress_hide();
				if (result.caqid) {
					// admin can't edit as update in CAQ, but could approve
					jquidialogue( 'updateawaiting', 'Update awaiting approval', result.msg, 'color: #900; font-weight: bold;', {
						autoOpen: true,
						modal: true,
						width: 400,
						buttons: {
							'OK': function(){
								$(this).dialog('close');
							},
							'Review update now': function(){
								$(this).dialog('close');
								window.location = ('/index.lasso?pg=9cb6379be4be93755e881e88c2449c2a&a=view&id='+result.caqid+'&'+g_sessionid);
							}
						}
					});
				} else {
					// can't update for whatever reason - show error msg
					jquialert('Error',result.msg);
				}
			}
		},
		error: function(xhr,textStatus){
			jquiprogress_hide();
			jquialert('Error',('Sorry, an error occurred while attempting to validate this editing session.' + ( textStatus!=null ? (" ("+textStatus+")") : "" )));
		}
	});
}


function ee_launch_step3(via_ajax,caqid) {

	var eed = $("#easy-edit-dialogue") ;

	if (via_ajax) {
	
		jquiprogress_show('Progress','Getting content to edit - please wait &hellip;');
		
		if (caqid) {
			eed.data('page-type','caq') ;
			eed.data('page-id',caqid) ;
		}
		
		$.ajax({
			async: true,
			url: ('/index.lasso?pg=ajax&f=get-content&type='+eed.data('page-type')+'&id='+eed.data('page-id')+'&' + g_sessionid),
			dataType: 'json',
			success: function(result){
				if (result.success) {
					ee_launch_step4(result.content)
				} else {
					jquiprogress_hide();
					jquialert('Error',result.msg);
				}
			},
			error: function(xhr,textStatus){
				jquiprogress_hide();
				jquialert('Error',('Sorry, an error occurred while attempting to get the content for editing.' + ( textStatus!=null ? (" ("+textStatus+")") : "" )));
			}
		});
	
	} else {

		ee_launch_step4( $("#"+eed.data('elem-id')).html() );

	}

}


/*
		if (eed.data('page-is-html')) {
			$("#tinymce_editor").val( $("#"+srcid).html() );
		} else {
			$("#tinymce_editor").val( $.trim( $("#"+srcid).html().replace(/<br(?: \/)?>/gi, '\n') ) );
		}
*/


function ee_launch_step4(content) {
		jquiprogress_hide();
		var eed = $("#easy-edit-dialogue") ;
		if (eed.data('page-is-html')) {
			$("#tinymce_editor").val( content );
		} else {
			$("#tinymce_editor").val( $.trim(content) );
		}
		eed.dialog('option','width',($(window).width() - 40));
		eed.dialog('open');
		eed.css('height',($(window).height() - 40 - (jqui_dialogue_height("#easy-edit-dialogue") - eed.height())));
		eed.trigger('resize');
}


function ee_setup_buttons() {
	$("span.ee-button-placeholder").html('<a href="">EasiEdit</a> ');
	$("span.ee-button-placeholder a").click(
		function(){
			var this_id = $(this).parent().attr('id') ;
			var id_parts = this_id.split(/-/) ;
			var srcid = ('page-text-'+id_parts[2]+'-'+id_parts[3]) ;
			if ($(this).parent().hasClass('ee-req-approval')) {
				$('#'+srcid).addClass('ee-check-caq');
			}
			ee_launch_step1(id_parts[2],id_parts[3],srcid);
			return false;
		}
	);
}


function ee_config_dialogue() {
	$("#easy-edit-dialogue").dialog({
		autoOpen: false,
		modal: true,
		bgiframe: true,
		title: 'Edit content',
		width: ($(window).width() - 40),
		position: [20,20],
		overlay: { backgroundColor: '#000', opacity: 0.5 },
		resizable: true,
		open: function(){
			if ($("#easy-edit-dialogue").data('page-is-html')) {
				cv_tinymce_setup("#tinymce_editor");
			}
		},
		close: function(){
			if ($("#easy-edit-dialogue").data('page-is-html')) {
				cv_tinymce_hide("#tinymce_editor");
			}
		},
		beforeclose: function(){
			if ($("#easy-edit-dialogue").data('close-confirmed')) {
				return true;
			} else {
				ee_dialogue_confirm_close();
				return false;
			}
		},
		buttons: {
			'Save changes': function() {
				if ($("#easy-edit-dialogue").data('page-is-html')) {
					var updated_content = $('#tinymce_editor').tinymce().getContent() ;
				} else {
					var updated_content = $('#tinymce_editor').val() ;
				}
				var postdata = ('f=easyedit&id=' + $(this).data('page-id') + '&type=' + $(this).data('page-type') + '&text=' + encodeURIComponent(updated_content)) ;
				$.ajax({
					type: "POST",
					url: ('/index.lasso?pg=ajax&' + g_sessionid),
					data: postdata,
					timeout: 5000,
					dataType: "json",
					success: function(result){
						if (result.success) {
							if ($("#easy-edit-dialogue").data('page-is-html')) {
								cv_tinymce_hide("#tinymce_editor");
								$('#'+$('#easy-edit-dialogue').data('elem-id')).html(updated_content);
							} else {
								$('#'+$('#easy-edit-dialogue').data('elem-id')).html( updated_content.replace(/\n/gi,'<br />') );
							}
							$("#easy-edit-dialogue").data('close-confirmed',true);
							$('#easy-edit-dialogue').dialog('close');
							if (result.msg.length) {
								jquialert('EasiEdit',result.msg);
							}
						} else {
							jquialert('Error',result.msg);
						}
					},
					error: function(xhr,textStatus){
						jquialert('Error',('Sorry, an error occurred while attempting to update this.' + ( textStatus!=null ? (" ("+textStatus+")") : "" )));
					}
				});
			},
			'Cancel': function() {
				$(this).dialog('close');
			}
		}
	});
}


function ee_dialogue_confirm_close() {
	$('body').append('<div id="jquiconfirm" title="Warning" style="color: #900; font-weight: bold; display:none;">Are you sure you want to cancel your editing? Any changes you have made will be lost.<\/div>');
	$('#jquiconfirm').dialog({
		autoOpen: true,
		modal: true,
		width: 400,
		buttons: {
			'OK': function(){
				$(this).dialog('close');
				$('#jquiconfirm').remove();
				$("#easy-edit-dialogue").data('close-confirmed',true);
				$("#easy-edit-dialogue").dialog('close');
			},
			'Cancel': function(){
				$(this).dialog('close');
				$('#jquiconfirm').remove();
			}
		}
	});
}