$(function(){
	var INCLUDES_PATH = "/tale/components/includes/";
		
	// Utility functions
	Array.max = function( array ){
		return Math.max.apply( Math, array );
	};
	Array.min = function( array ){
		return Math.min.apply( Math, array );
	};
	
	refreshResource = function(uid, index)
	{
		$.get(INCLUDES_PATH + "singleResource.html", { uid: uid, index: index }, function(data) {
			$("#resource" + index).closest("li").attr("innerHTML", data);
		});
	};
	
	refreshMySavedItems = function()
	{
		$("#myResources").load(INCLUDES_PATH + "myResourcesList.html");
		$("#myLists").load(INCLUDES_PATH + "myListsList.html");
		$("#mySearches").load(INCLUDES_PATH + "mySearchesList.html");
	};
	
	// Initialise external links.
	$("a[rel=trap], a[rel=external]").live("click", function(){
			$(this).attr("target", "_blank");
	});
	
	// Show/Hide additional search criteria
	if ($('#optional_search_criteria .inner').children().length) {
		$('<div class="toggle_options"><a href="#optional_search_criteria">More options</a></div>').appendTo('#search').find('a').bind('click', function(e){
			e.preventDefault();
			if (e.type == 'click') {
				if ($('#optional_search_criteria').is(':hidden')) {
					$(this).parent().addClass('expanded').end().text('Hide options');
					$('#optional_search_criteria').slideDown('fast');
				} else {
					$(this).parent().removeClass('expanded').end().text('More options');
					$('#optional_search_criteria').slideUp('fast');
				}
			}
		});
	}
	
	// Tab functionality used throughout the site
	// - all tabs need to have a href which points to a corresponding unique ID for the .tab_content below it
	function buildTabs(el){
		var tabs = $(el);
		if (!tabs.hasClass('static')) {
			var activeTab = tabs.find('.current'),
				triggers = tabs.find('a'),
				targets = triggers.map(function(){ return $(this).attr('href') });

			$(activeTab.find('a').attr('href')).addClass('active_tab');

			triggers.click(function(e){
				e.preventDefault();
				$(targets.get().toString()).removeClass('active_tab');
				tabs.find('li').removeClass('current');
				$(this).parent('li').addClass('current');
				$($(this).attr('href')).addClass('active_tab');
			});
		}
	};
	
	$('.tabs').each(function(){ buildTabs(this); });

	// Zebra striping of tables
	$('.my_lists').find('tbody tr:even').addClass('alt');
	
	// Add a class to every third row for the columns of checkboxes
	$('.option_list').each(function(){ $(this).find('span').filter(function(i){ return !(i%3); }).addClass('first'); });

	// Main category (primary/secondary/tafe/all) dropdown changes which sets of checkboxes are available
	$('#selSector').change(function(){
		var val = $(this).val().toLowerCase();
		
		if (val === 'secret') {
			$('.cat_primary, .cat_secondary, .cat_tafe').removeClass('hidden_options');
		} else if (val === 'primary' || val === 'secondary') {
			$('.cat_primary, .cat_secondary').removeClass('hidden_options');
			$('.cat_tafe').addClass('hidden_options').find(':checkbox').removeAttr('checked').each(function(){
				var panel = $(this).closest('.options'),
					labels = panel.find('.option_list').not('.hidden_options').find(':checked + label').map(function(){ return $(this).text() }).get().join(', ');
				
				labels.length ? panel.prev('.options_selected').find('span').text(labels) : panel.prev('.options_selected').find('span').text('All');
			});
		} else if (val === 'tafe') {
			$('.cat_tafe').removeClass('hidden_options');
			$('.cat_primary, .cat_secondary').addClass('hidden_options').find(':checkbox').removeAttr('checked').end().each(function(){
				var panel = $(this).closest('.options').get(),
					labels = $(panel).find('.option_list').not('.hidden_options').find(':checked + label').map(function(){ return $(this).text() }).get().join(', ');

				labels.length ? $(panel).prev('.options_selected').find('span').text(labels) : $(panel).prev('.options_selected').find('span').text('All');
			});
		}
	}).change();
	
	// Search panel dropdowns/overlay checkbox panels
	var search_trigger;
	$('.options_selected').attr('tabindex','0').each(function(i){
		var	dropdown = $(this),
			options = dropdown.next('.options'),
			$popup = $('#popup'),
			updateDropdown = function(e){ // Populate the dropdown text with the checkbox options selected
				var container = (arguments.length === 0 ? options : $(e.target).closest('.options')),
					trigger = search_trigger || dropdown,
					labels = container.find('.option_list').not('.hidden_options').find(':checked + label').map(function(){ return $(this).text() }).get().join(', ');

				labels.length ? $(trigger).find('span').text(labels) : $(trigger).find('span').text('All');
				if ($popup[0]) {
					$popup.css({ top: parseInt($(trigger).offset().top, 10) + $(trigger).height() + 4, left: $(trigger).offset().left - 1 });
				}
			};

		updateDropdown();

		// Click/Keyup event for the checkboxes
		$('.options :checkbox').bind('click keyup', updateDropdown);
		
		dropdown.bind('click keyup', function(e){
			e.stopPropagation();
			e.preventDefault();
			
			if (e.type == 'click' || e.which == 13 || e.which == 10) {
				$popup = $('#popup');

				if ($('#popup').length && $(search_trigger).attr('id') !== dropdown.attr('id')) {
					$popup.find('.buttons button').click();
				}

				search_trigger = dropdown;
				
				if ($('#popup').length && $(search_trigger).attr('id') === dropdown.attr('id')) {
					$popup.find('.buttons button').click();
				} else {
					var leftOffset = dropdown.offset().left - 1,
						topOffset = parseInt(dropdown.offset().top, 10) + dropdown.height() + 4,
						holder = $('<div id="popup" class="search_form_popup"><div class="top_left"><div class="top_right"></div></div><div class="middle_left"><div class="middle_right" id="popup_content"><div class="buttons"><a href="#">Choose all</a><button type="submit" value="Done" class="input_submit"><span>Done</span></button></div></div></div><div class="bottom_left"><div class="bottom_right"></div></div></div>');

					holder.appendTo('body').css({ top: topOffset, left: leftOffset }).bgiframe();
					$popup = $('#popup');
					$popup
						.find('.buttons a')
							.click(function(e){
								e.preventDefault();
								$popup.find('.options').removeData('checked');
								$popup.find('.option_list:visible :checked').unbind('click keyup').removeAttr('checked').bind('click keyup',updateDropdown);
								$(search_trigger).find('span').text('All').click();
							})
						.end()
						.find('.buttons button')
							.click(function(e){
								e.preventDefault();
								var $checked = $popup.find(':checked'),
									$options = $popup.find('.options');
								$options.data('checked', $checked);
								$options.hide().insertAfter(search_trigger);
								$popup.remove();
								search_trigger.next().find(':checkbox').removeAttr('checked');
								$($checked).attr('checked','checked');
							})
						.end()
						.click(function(e){
							e.stopPropagation();
						});

					var data = options.data('checked');
					if (data) {
						options.prependTo('#popup_content').show().find(':checkbox').removeAttr('checked');
						$(data).attr('checked', 'checked');
					} else {
						options.prependTo('#popup_content').show();
					}
				}
			}
		});
	});

	// Remove the popups and put their content back where it belongs when the body is clicked
	$('body').click(function(e){
		if ($('#popup')[0]) {
			$(search_trigger).click();
		}
	});
	
	// My Lists table
	$("#my_items table.my_lists td.name").bind("mouseover", function(e) {
		$(this).addClass("hover");
	}).bind("mouseout", function() {
		$(this).removeClass("hover");
	});
	
	// My saved searches table
	/*
	$('#my_saved_searches').each(function(){
		var $this = $(this),
			action = $this.parent('form').attr('action'),
			liClass = function(){ $('#my_saved_searches').find('li').removeClass('first last').end().find('li:first').addClass('first').end().find('li:last').addClass('last').end().find('.saved_search_info').removeClass('hover'); },
			showControls = function(el){
								var el = $(el),
									html = $('<p class="reorder"><a href="#" class="move_up">move up</a><br /><a href="#" class="move_down">move down</a></p>').hide();
								
								el.append(html).find('.reorder').fadeIn();
								if (el.parent().hasClass('first')) {
									el.find('.move_up').addClass('disabled move_up_disabled');
								} else if (el.parent().hasClass('last')) {
									el.find('.move_down').addClass('disabled move_down_disabled');
								}
							},
			hideControls = function(el){ $(el).find('.reorder').remove(); },
			reorder = function(e){
							var control = $(e.target),
								searchId,
								isLegacy,
								topItem,
								bottomItem;

							if (!control.hasClass('disabled') && control.hasClass('move_up')) {
								e.preventDefault();
								topItem = control.closest('.item').prev('.item');
							} else if (!control.hasClass('disabled') && control.hasClass('move_down')) {
								e.preventDefault();
								topItem = control.closest('.item');
							} else {
								return;
							}
							searchId = topItem.find('.search_id').val();
							isLegacy = topItem.find(".is_legacy").val();
							$.ajax({
								type: "POST",
								url: action,
								data: 'savedSearchId=' + searchId + "&isLegacy=" + isLegacy,
								success: function(msg) {
									if ($.trim(msg) == "success") {
										bottomItem = topItem.next('.item');
										$('#my_saved_searches').find('.saved_search_info').unbind('mouseenter mouseleave');
										topItem.fadeOut('slow', function(){ $('.reorder').remove(); $(this).find('.saved_search_info').removeClass('hover').end().insertAfter(bottomItem).fadeIn('slow', function() { liClass(); $('#my_saved_searches').find('.saved_search_info').hover(function() { itemOver(this); }, function() { itemOut(this); }); }); });
									} else {
										$(msg).modal({
											closeClass: 'modal_close',
											closeHTML: '<a href="#" title="Cancel and close" class="modal_close close_button">Cancel and close</a>',
											overlayId: 'modal_overlay',
											containerId: 'modal_container',
											onOpen: modal_form.open,
											onShow: modal_form.show,
											onClose: modal_form.close
										});
									}
								}
							});
						},
			itemOver = function(el){
							$(el).addClass('hover');
							showControls(el);
						},
			itemOut = function(el){
							$(el).removeClass('hover');
							hideControls(el);
						};
		liClass();
		$this.find('.saved_search_info').hover(function() { itemOver(this); }, function() { itemOut(this); }).click(reorder);
	});
	*/
	
	// Text Size
	$('.text_size a').click(function(e) {
		var increase = $(this).hasClass('larger'),
				newClass = "";
		e.preventDefault();
		if ($('body').hasClass('large')) {
			increase === true ? $('body').removeClass('large').addClass('largest') : $('body').removeClass('large');
			newClass = (increase) ? "largest" : "";
		} else if ($('body').hasClass('largest')) {
			increase === true ? null : $('body').removeClass('largest').addClass('large');
			newClass = (increase) ? "" : "large";
		} else {
			increase === true ? $('body').addClass('large') : $('body').addClass('smallest');
			newClass = (increase) ? "large" : "smallest";
		}
		$.post(INCLUDES_PATH + "setUserPreference.html", { optionName: "global_textSize", optionValue: newClass });
	});
	
	// Select search results
	$('input[name=resource_uid[]]').click(function(){
		$(this).closest('li').toggleClass('selected',$(this).is(':checked'));
	});

	// Populate suggested tags
	$('.suggested_tags em').live('click', function(){
			var suggestion = $(this).text(),
				tags = $('#tags');
				
			if (tags.val()) {
				if (tags.val().indexOf(suggestion) == -1) {
					tags.val(tags.val() + ' ' + suggestion);
				}
			} else {
				tags.val(suggestion);
			}
	});
	
	// Reveal the new list text input field
	function newListDD() {
		$('#listId').bind('change keyup', function(){
			if ($(this).val() === '-1') {
				$(this).next('.conditional:hidden').show().focus();
			} else {
				$(this).next('.conditional:visible').hide();
			}
		});
	};
	
	// Bind event to Delete link in modals
	$('#modal_container .buttons .delete').live('click', function(e){
		var $this = $(e.target),
				loading = $('<div id="modal_loading">Loading, please wait...</div>').hide();
		$('#modal_container')
				.find('.modal_content').css('height', $('#modal_container .modal_content').height()).end() // change height from auto to fixed for animating
				.find('.close_button').hide().end()
				.find('form').fadeOut(200, function(){
					$('#modal_container')
						.find('form').remove().end()
						.find('.modal_content').animate({ height: '158px' }, function() {
							$(loading).appendTo('#modal_container .modal_content').fadeIn(400, function(){
								var postData = ((window.location.href.indexOf("guidedsearch.jsp") != -1) ? "src=search" : "");
								$.post($this.attr("href"), postData, function(data) {
									$('#modal_loading').fadeOut(400, function() {
										$('#modal_loading').remove();
										
										// Load the deletion form.
										$(data).find("form").hide().appendTo('#modal_container .modal_content');
										$('#modal_container').find('.modal_content').animate({ height: "250px" }, function() {
											$("#modal_container").find(".modal_content").css({ height: "auto" }).find("form").fadeIn(400);
											$("#modal_container").find("form").fadeIn(400);
											
											// Initialise Stuff.
											modal_form.show();
											
											$('#modal_container').find('.close_button').fadeIn(200).end().find('.close_link, .cancel').click(function(e){
												e.preventDefault();
												$.modal.close();
											});
										})
									});
								});
							});
						});
				});
		e.preventDefault();
	});
	
	// Bind the close modal function to any close links included in the response messages
	$('.modal_content .close_link').live('click', function(e){
		e.preventDefault();
		$.modal.close();
		//modal_form.close();
	});
	
	// Closes the modal when they haven't selected any resources, selects all resource checkboxes on the page and reopens the dialog
	$('.save_all').live('click', function(e){
			e.preventDefault();
			$.modal.close();
			$('.resource_uid').not(':checked').click();
			setTimeout(function() { $(modal_trigger).click(); }, 800);
	});
	
	// Clickable links that reveal content in a div targeted using the ID
	$('.revealer').live('click', function(e){
			var target = $('#'+$(this).attr('href').split('#')[1]);
			e.preventDefault();
			target.slideToggle();
	});
	
	// Rotator behaviour
	$('.rotator').each(function(){
		
		window.control = function(direction) {
			if (direction === 'prev') {
				//var last = rotator.find('.item:last');
				//last.hide().prependTo(rotator).slideDown(700);
				var current = rotator.find('.current'),
						prev = (current.prev(".item").length > 0) ? current.prev(".item") : rotator.find(".item:last");
				current.removeClass("current").fadeOut(350, function() {
					prev.addClass("current").fadeIn(350);
				});
			} else if (direction === 'next') {
				//var first = rotator.find('.item:first');
				//first.slideUp(700, function(){ first.appendTo(rotator).show(); });
				var current = rotator.find('.current'),
						next = (current.next(".item").length > 0) ? current.next(".item") : rotator.find(".item:first");
				current.removeClass("current").fadeOut(350, function() {
					next.addClass("current").fadeIn(350);
				});
			} else if (direction === 'play') {
				controls.find('.next').click();
				controls.find('.play').parent().hide();
				controls.find('.pause').parent().show();
				rotateItems = setInterval("control('next');", 5000);
			} else if (direction === 'pause') {
				controls.find('.pause').parent().hide();
				controls.find('.play').parent().show();
				clearInterval(rotateItems);
			}
		};
			
		var rotator = $(this),
			controls = $('<div class="controls"><ul><li><a href="#" class="prev">Previous</a></li><li><a href="#" class="play">Play</a></li><li><a href="#" class="pause">Pause</a></li><li><a href="#" class="next">Next</a></li></ul></div>').appendTo(rotator).fadeIn(),
			items = rotator.find('.item'), //.fadeIn(500),
			heights = [],
			rotateItems = 0,
			controlRotator = function(e) {
						var target = $(e.target);
						e.preventDefault();
		
						if (target.hasClass('prev')) {
							control('prev');
							control('pause');
						}
						if (target.hasClass('next')) {
							control('next');
							control('pause');
						}
						if (target.hasClass('play')) {
							control('play');
						}
						if (target.hasClass('pause')) {
							control('pause');
						}
					};
			
		for (var i = 0; i < items.length; i++) 
		{
			if (i < 1) 
			{
				$(items[i]).addClass("current").fadeIn(700);
			}
			else
			{
				$(items[i]).hide();
			}
			heights.push($(items[i]).innerHeight());
		}
		items.parent().andSelf().css('height', Array.max(heights));

		rotator.show();
		controls.show();

		control('play');
		rotator.find('.controls').live('click', controlRotator);
	});

	// Feedback form trigger
	$('input[name=lookingFor]').live('click', function(){
		var found = $(this).val();
		if (found == 'yes') {
			$('#feedback_holder').slideUp(400, function(){ 
				$('#modal_container')
						.find('.feedback_no').hide().end()
						.find('.feedback_yes').show(); 
				$('#feedback_holder').slideDown(400); 
			});
			$("feedbackType").val("Positive");
		} else if (found == 'no') {
			$('#feedback_holder').slideUp(400, function(){  
				$('#modal_container')
						.find('.feedback_yes').hide().end()
						.find('.feedback_no').show(); 
				$('#feedback_holder').slideDown(400); 
			});
			$("feedbackType").val("Negative");
		}
	});
	
	// Modal popup windows
	var modal_trigger;
	$('a[rel="modal"], .feedback_question :radio').live('click',function(e){
		var trigger = $(this),
			url = '',
			action = '',
			data = '';

		// Get the form post url
		if (trigger.is(':radio')) {
			url = $('.feedback_question').attr('action');
			action = trigger.val() == 'yes' ? 'found=yes' : 'found=no';
			data = action;
		} else {
			e.preventDefault();
			url = trigger.attr('href');
		}

		// Set the global var so other apps can use the reference
		modal_trigger = trigger.get();
		
		// Post different data for the various links
		if (trigger.hasClass('.save_multiple')){
			if ($('.resource_uid:checked').length == 1 && $('.resource_uid:checked').closest('.resource').hasClass('saved')) {
				action = '&form_action=edit';
			} else {
				action = '&form_action=save';
			}
			data = trigger.parents('form').serialize() + action + '&resource_count=' + $('.result_list').find('.resource').length; // Serialise the Data for the same multiple only
		} else if (trigger.hasClass('save')) {
			action = '&form_action=save';
			data = 'resource_uid=' + trigger.closest('.resource').find('.resource_uid').val() + action;
		} else if (trigger.hasClass('edit')) {
			action = '&form_action=edit';
			data = 'resource_uid=' + trigger.closest('.resource').find('.resource_uid').val() + action;
		} else if (trigger.hasClass('delete')) {
			action = '&form_action=delete';
			data = trigger.parents('form').serialize() + action + '&resource_count=' + $('.result_list').find('.resource').length; // Serialise the Data for the same multiple only			
		} else if (trigger.hasClass('rename_list') || trigger.hasClass('delete_list')) {
			//data = 'bookmarkListId=' + $('#bookmarkListId').val();
			// Data is appended to the URL.
		} else if (trigger.hasClass('rename_tag') || trigger.hasClass('delete_tag')) {
			data = 'tag_uid=' + $(modal_trigger).parent('li').find('.tag_uid').text();
		} else if (trigger.hasClass('rename_search') || trigger.hasClass('delete_search')) {
			// Data is appended to the URL.
		} else if (trigger.hasClass('trap_save')) {
			action = '&form_action=save';
			data = 'resource_uid=' + $('.resource_uid').text() + action;
		} else if (trigger.hasClass('trap_edit')) {
			action = '&form_action=edit';
			data = 'resource_uid=' + $('.resource_uid').text() + action;
		}
		else if (trigger.hasClass("email_list"))
		{
			// Data is appended to the URL.
		}
		else if (trigger.hasClass("email_multiple"))
		{
			data = trigger.parents('form').serialize();
		}
		else if (trigger.hasClass("pdf") || trigger.hasClass("print"))
		{
			data = trigger.parents('form').serialize();
			if (data.indexOf("resources") != -1)
			{
				// Search Results Page (print)
				var rIds = $("[name=rId]"),
						rId = "";
				for (var i = 0; i < rIds.length; i++)
				{
					if ($(rIds[i]).parent().find("[name=resources]").attr("checked"))
					{
						rId += ((rId != "") ? "," : "") + rIds[i].value;
					}
				}
				//window.open(url + "?" + data);				
				window.open(url + "?rIds=" + rId);
				return false;
			}
			else if ($("#uid").length > 0)
			{
				// TRAP
				window.open(url + "?resources=" + escape($("#uid").val()));
				return false;
			}
		}
		else if (trigger.hasClass("email"))
		{
			data = "uid=" + escape($("#uid").val());
		}

		// load the contact form using ajax
		$.post(url, data, function(data){
			// create a modal dialog with the data
			$(data).modal({
				closeClass: 'modal_close',
				closeHTML: '<a href="#" title="Cancel and close" class="modal_close close_button">Cancel and close</a>',
				overlayId: 'modal_overlay',
				containerId: 'modal_container',
				onOpen: modal_form.open,
				onShow: modal_form.show,
				onClose: modal_form.close
			});
		});
	});
	
	$(".tab_content ul, .panel ul").each(function() {
		if ($(this).attr("class") == "")
		{
			$(this).addClass("square_bullet");
		}
	});

	var modal_form = {
		message: null,
		open: function (dialog) {
			dialog.overlay.fadeIn(200, function () {
				dialog.data.show();
				$('#modal_container').css({'height': 'auto'});
				dialog.container.fadeIn(200);
				
				// Create Tags lookup.
				if ($('#modal_container').find("#tags").length > 0)
				{
					new DET.tale.ui.TagLookup("tags", INCLUDES_PATH + "getMyTags.html");
				}
				else if ($('#modal_container').find("#tagName").length > 0)
				{
					new DET.tale.ui.TagLookup("tagName", INCLUDES_PATH + "getMyTags.html");
				}
				if ($("#feedback_holder").length != 0)
				{
					// Feedback Form.
					new DET.tale.ui.AjaxLookup("workplace", "/tfdi/ajax/getLocations.do");
					var info = new DET.tale.util.BrowserDetails();
					var os = info.operatingSystem.split(" ");
					$modalContainer = $('#modal_container');
					$modalContainer.find("#operatingSystem").val(os[0]);
					$modalContainer.find("#osVer").val(os[1]);
					$modalContainer.find("#browser").val(info.browser);
					$modalContainer.find("#browserVersion").val(info.browserVersion);
					$modalContainer.find(".option").each(function() {
						$this = $(this);
						if ($this.attr("id") != "option_Home")
						{
							$this.hide();
						}
						$this.bind("change", function() {
							$("#modal_container").find("#accessDetail").val($this.val());
						});	
					});
					
					$modalContainer.find("#accessLocation").bind("change", function() {
						var $this = $(this);
						$("#more_feedback_details")
								.find(".option").hide().end()
								.find("#option_" + $this.val()).show();
					});
					
					$modalContainer.find("#pageTitle").val(document.title);
					$modalContainer.find("#pageUrl").val(document.location.href);
				}
				
				// Set Notes maximum size.
				$("#modal_container").find("#notes").bind("change", function() {
					var result = true,
							value = $(this).val();
					if (value.length > 140)
					{
						$(this).val(value.substring(0, 140));
						result = false;
					}
					return result;
				});
				
				$("#modal_container .modal_content input[type=text]:first").focus();
			});
		},
		show: function (dialog) {
			newListDD();
			
			$("#modal_container .input_submit").click(function(e) {
				e.preventDefault();
				$(this).closest("form").trigger("submit");
			});
			$('#modal_container').find("form").bind("submit", function(e) {
				var submitUrl = $('#modal_container').find('form').attr('action'),
					submitData = $('#modal_container').find('form').serialize();
				var loading = $('<div id="modal_loading">Loading, please wait...</div>').hide();
				
				// Special behaviour for the feedback form.
				if ($("#feedback_holder").length == 0 && $("#contactUs").length == 0)
				{
					e.preventDefault();	
					
					// validate form
					if (modal_form.validate()) {					
						$('#modal_container')
							.find('.modal_content').css('height', $('#modal_container .modal_content').height()).end() // change height from auto to fixed for animating
							.find('.close_button').hide().end()
							.find('form').fadeOut(200, function(){
								$('#modal_container')
									.find('form').remove().end()
									.find('.modal_content').animate({ height: '158px' }, function() {
										$(loading).appendTo('#modal_container .modal_content').fadeIn(400, function(){
											$.ajax({
												url: submitUrl,
												data: submitData,
												type: 'post',
												cache: false,
												dataType: 'html',
												success: modal_form.success,
												error: modal_form.error
											});
										});
									});
							});
					}
					else {
						modal_form.showError();
					}
				}
				else
				{
					// Feedback form behaviour (the response will close the modal).
					
					/*
					// Search Feedback Popup
					if ($("#feedback_holder").length > 0)
					{
						var feedbackHolder = $("#feedback_holder"),
								feedbackType = (feedbackHolder.find("[name=lookingFor]").val() == "yes") ? "Positive" : "Negative",
								mostUseful = feedbackHolder.find("#mostUseful").val(),
								issueText = feedbackHolder.find("#issueText").val();
						if (feedbackType == "Positive")
						{
							feedbackHolder.find("#feedbackContent").val(mostUseful);
						}
						else
						{
							feedbackHolder.find("#feedbackContent").val(issueText);
						}
						feedbackHolder.find("#feedbackType").val(feedbackType);
					}
					*/
					
					// Display the loading page.
					$('#modal_container')
							.find('.modal_content').css('height', $('#modal_container .modal_content').height()).end() // change height from auto to fixed for animating
							.find('.close_button').hide().end()
							.find('form').fadeOut(200, function(){
								$('#modal_container')
									.find('form').remove().end()
									.find('.modal_content').animate({ height: '158px' }, function() {
										$(loading).appendTo('#modal_container .modal_content').fadeIn(400);
									});
							});
				}
			});
		},
		close: function (dialog) {
			$('#modal_container').find('.close_button').fadeOut(200);
			dialog.data.fadeOut(200, function() {
				dialog.container.fadeOut(200, function() {
					dialog.overlay.fadeOut(200, function () {
						$.modal.close();
					});
				});
			});
		},
		success: function (data) {
			$('#modal_loading').fadeOut(400, function() {
				$('#modal_loading').remove();
				$(data).hide().appendTo('#modal_container .modal_content');
				$('#modal_container').find('.modal_content').animate({ height: $('.response').innerHeight() }, function(){
					$('#modal_container').find('.response').fadeIn(200, function(){
						var response = $(this);
						if (response.hasClass('success')) {
							setTimeout(function() { 
								$.modal.close();
								if (response.hasClass('reload_page') || $("body").hasClass("trap"))
								{
									window.location.reload(); 
								}
								if (response.hasClass('reload_resource'))
								{									 
									var uids = response.find("#uid").val().split(",");
									for (var i = 0; i < uids.length; i++)
									{
										var id = $("input[value='" + uids[i] + "']").attr("id");									
										var index = parseInt(id.replace("resource", "").replace("_uid", ""));
										refreshResource(uids[i], index);
									}
									refreshMySavedItems();
								}
								if (response.hasClass("reload_my_items"))
								{
									refreshMySavedItems();
								}
								if (response.hasClass("new_window"))
								{
									var loc = window.location.href,
											prefix = loc.substring(0, loc.indexOf("/tale/"));
									window.open(prefix + response.find("#url").val(), "_rss");
								}
							}, 500);
							
						} else if (response.hasClass('modal_help_form')) {
							// Save the user's preference of showing the modal.
							$("#cb_dont_show").live("click", function() {
									$.post("/tale/components/includes/setUserPreference.html", 
											{ optionName: "helpModal_saveResource", optionValue: !$(this).attr("checked") });
							});
							if ($("body").hasClass("trap"))
							{
								response.find(".close_button").live("click", function() { window.location.reload(); });
							}
							else if (response.hasClass('reload_page'))
							{
								window.location.reload(); 
							}
							else if (response.hasClass('reload_resource'))
							{
								var uids = response.find("#uid").val().split(",");
								for (var i = 0; i < uids.length; i++)
								{
									var id = $("input[value='" + uids[i] + "']").attr("id");									
									var index = parseInt(id.replace("resource", "").replace("_uid", ""));
									refreshResource(uids[i], index);
								}
								refreshMySavedItems();
							}
							else if (response.hasClass("redirect"))
							{
								var url = response.find("#url").val();
								window.location.href = url;
							}
						
							$('#modal_container').find('.close_button').fadeIn(200).click(function(e){
								e.preventDefault();
								$.modal.close();
							});
							modal_form.show();
						} else {
							$('#modal_container').find('.close_button').fadeIn(200).end().find('.close_link').click(function(e){
								e.preventDefault();
								$.modal.close();
							});
						}
					});
				});
			});
		},
		error: function(xhr) {
			$('#modal_loading').fadeOut(400, function(){
				$('#modal_loading').remove();
				$('<div class="response fail"><h2><span>AJAX Error</span></h2><p>'+xhr.status+' '+xhr.statusText+'</p></div>').hide().appendTo('#modal_container .modal_content');
				$('#modal_container').find('.modal_content').animate({ height: $('.response').height() }, function(){ $('#modal_container').find('.response, .close_button').fadeIn(400); });
			});
		},
		
		validateWithTags: function() {
			$("#tags, #tagName").each(function() {
				var $this = $(this),
						tags = $this.val().split(" ").join(",");
				$.get("/tale/components/includes/isCensored.html", { tags: tags }, function(response) {
					if ($.trim(response) != "success")
					{
						$this.addClass("error");
						alert(response);
						return false;
					}
					else
					{
						return modal_form.validate();
					}
				});
			});
		},
		
		validate: function () {
			modal_form.message = '';

			var str = [];

			$('#modal_container .required:visible').each(function(){
				var $this = $(this);
				$('.error').removeClass('error');

				if ($.trim($this.val()).length == 0) {
					str.push($this.attr('title') + " is required.");
					$this.addClass('error');
				}
			});
			
			$("#email").each(function() {
				var $this = $(this);
				if ($this.val().length && 
						!DET.tale.validation.validateEmails($this.val()))
				{
					str.push($this.attr("title") + " must contain valid email address(es).");
					$this.addClass("error");
				}
			});
			
			$("#listName").each(function() {
				var $this = $(this),
						$select = $("#listId"),
						options = $select.find("option");
						
				if ($this.val().length)
				{
					for (var i = 0; i < options.length; i++)
					{
						if ($this.val().toLowerCase() == $(options[i]).html().toLowerCase())
						{
							str.push("The list '" + $this.val() + "' already exists.");
							$this.addClass("error");
						}
					}
				}
			});
			modal_form.message = str.join('\n');
			return modal_form.message.length == 0;
		},
		showError: function () {
			alert(modal_form.message);
		}
	};

	/* Update Download/View counter for TRAP */
	$("a.view, a.download").click(function() {
		var $this = $(this),
				data = {
					action: $this.hasClass("view") ? "view" : "download",
					title: $("h2.resource_title").html(),
					uid: $("#uid").val()
				};
		$.get("/tale/components/includes/logAccess.html", data);
		return true;
	});
	
	$(".description").find("a").live("click", function(e) {
		e.preventDefault();
		$(this).prev(".trunc").hide().end().next(".full").show().end().hide();
	});
	
	// TRAP box height for students.
	$(".trap .box").each(function() {
		if ($(this).innerHeight() < 40)
		{
			$(this).css("height", 40);
		}
	});
	
	/*
	// My Saved Items link on TRAP - open in parent window.
	$(".trap a[rel=parent]").live("click", function(e) {
		var url = $(this).attr("href");
		e.preventDefault();
		window.opener.location = url;
	});
	*/
	
	// Initialise the feedback forms.
	$("#contactUs, #trapFeedback").each(function() {
		var container = $(this),
				info = new DET.tale.util.BrowserDetails(),
				os = info.operatingSystem.split(" ");
		new DET.tale.ui.AjaxLookup("workplace", "/tfdi/ajax/getLocations.do");
		
		container.find("#operatingSystem").val(os[0]);
		container.find("#osVer").val(os[1]);
		container.find("#browser").val(info.browser);
		container.find("#browserVersion").val(info.browserVersion);
		container.find(".option").each(function() {
			$this = $(this);
			$this.hide().parent().find(".option:first").show();
			$this.bind("change", function() {
				$("#modal_container").find("#accessDetail").val($this.val());
			});	
		});
		container.find("#accessLocation").bind("change", function() {
			var $this = $(this);
			$("#more_feedback_details")
					.find(".option").hide().end()
					.find("#option_" + $this.val()).show();
		});
		
		container.find(".input_submit").click(function(e) {
			var $form = container.find("form"), str = [];
			$form.find(".required:visible").each(function(){
				var $this = $(this);
				$('.error').removeClass('error');

				if ($.trim($this.val()).length == 0) {
					str.push($this.attr('title'));
					$this.addClass('error');
				}
			});
			$form.find("#email").each(function() {
				var $this = $(this);
				if (!DET.tale.validation.validateEmails($this.val()))
				{
					str.push($this.attr("title"));
					$this.addClass("error");
				}
			});
	
			if (str.length > 0)
			{
				e.preventDefault();
				alert('The following fields are required: ' + str.join(', '));
			}		
		});
	});
	
	// Displays the text in a modal lightbox (check for existence first).
	window.doLightBox = function(text)
	{
		var success = text.indexOf("error") == -1,
				data = (success) ? "<div class=\"response success\"><h2><span>Success</span></h2><div class=\"modal_help\"><p>" + $.trim(text) + "</p></div></div>" : 
				"<div class=\"response fail\"><h2><span>Oops</span></h2><div class=\"modal_help\"><p>" + $.trim(text) + "</p></div></div>";
		
		if ($("#modal_container").length > 0)
		{
			// Update the existing modal form.
			$('#modal_loading').fadeOut(400, function() {
				$('#modal_loading').remove();
				$(data).hide().appendTo('#modal_container .modal_content');
				$('#modal_container').find('.modal_content').animate({ height: $('.response').innerHeight() }, function(){
					$('#modal_container').find('.response').fadeIn(200, function(){
						var response = $(this);
						if (response.hasClass('success')) 
						{ 
							setTimeout(function() { $.modal.close(); }, 500);
						}
						else
						{
							$('#modal_container').find('.close_button').fadeIn(200).end().find('.close_link').click(function(e){
								e.preventDefault();
								$.modal.close();
							});
						}
					});
				});
			});
		}
		else
		{
			// Create a new modal form.
			$(data).modal({
				closeClass: 'modal_close',
				closeHTML: '<a href="#" title="Cancel and close" class="modal_close close_button">Cancel and close</a>',
				overlayId: 'modal_overlay',
				containerId: 'modal_container',
				onOpen: modal_form.open,
				onShow: modal_form.show,
				onClose: modal_form.close
			});
		}
		if (success)
		{
			setTimeout(function() { $.modal.close(); }, 2000);
		}
		$("#submitFrame").attr("src", "");
	};
	
	window.doReset = function()
	{
		if ($("#contactUs").length > 0)
		{
			$("[type=reset]").click();
		}
		else if ($("rapFeedback").length > 0)
		{
			$("#sidebar a:first").click();
		}
	};
	
	refreshMySavedItems();
});

// Refine search results expand/collapse
collapseRefineHeadings = function() 
{
	$('#refine_results.collapsible').find('h3').addClass('compactor').attr('tabindex',0).each(function()	{
			var trigger = $(this),
				target = trigger.next('.values');
			
			trigger.bind('click keyup', function(e){
				if (e.type == 'click' || e.which == 13 || e.which == 10) {
					if (target.is(':hidden')) {
						trigger.removeClass('collapsed');
						target.slideDown('fast');
					} else {
						trigger.addClass('collapsed');
						target.slideUp('fast');
					}
				}
			});
		});
};

/*! Copyright (c) 2008 Brandon Aaron (http://brandonaaron.net)
 * Dual licensed under the MIT (http://www.opensource.org/licenses/mit-license.php) 
 * and GPL (http://www.opensource.org/licenses/gpl-license.php) licenses.
 *
 * Version 2.1.2-pre
 */
$.fn.bgIframe = $.fn.bgiframe = function(s) {
	// This is only for IE6
	if ( $.browser.msie && $.browser.version < 7 ) {
		s = $.extend({
			top     : 'auto', // auto == .currentStyle.borderTopWidth
			left    : 'auto', // auto == .currentStyle.borderLeftWidth
			width   : 'auto', // auto == offsetWidth
			height  : 'auto', // auto == offsetHeight
			opacity : true,
			src     : 'javascript:false;'
		}, s || {});
		var prop = function(n){return n&&n.constructor==Number?n+'px':n;},
		    html = '<iframe class="bgiframe"frameborder="0"tabindex="-1"src="'+s.src+'"'+
		               'style="display:block;position:absolute;z-index:-1;'+
			               (s.opacity !== false?'filter:Alpha(Opacity=\'0\');':'')+
					       'top:'+(s.top=='auto'?'expression(((parseInt(this.parentNode.currentStyle.borderTopWidth)||0)*-1)+\'px\')':prop(s.top))+';'+
					       'left:'+(s.left=='auto'?'expression(((parseInt(this.parentNode.currentStyle.borderLeftWidth)||0)*-1)+\'px\')':prop(s.left))+';'+
					       'width:'+(s.width=='auto'?'expression(this.parentNode.offsetWidth+\'px\')':prop(s.width))+';'+
					       'height:'+(s.height=='auto'?'expression(this.parentNode.offsetHeight+\'px\')':prop(s.height))+';'+
					'"/>';
		return this.each(function() {
			if ( $('> iframe.bgiframe', this).length == 0 )
				this.insertBefore( document.createElement(html), this.firstChild );
		});
	}
	return this;
};
