function _isCoursePage() {
	return (typeof(courseId) != "undefined") &&
		courseId != null;
}

function _isEditor() {
	return $("librarianEditor") != null;
}

/* ML: Break out editor actions into a separate js file to
   optionally include in default layout if editor role. */

function onEditLibrarian() {
	replaceWithEditor('librarianDisplay', 'librarianEditor');
}

function onCancelLibrarian() {
	replaceWithView('librarianEditor', 'librarianDisplay');
}

function onEditCourseComments() {
	replaceWithEditor('courseCommentsDisplay', 'courseCommentsEditor');
}

function onCancelCourseComments() {
	replaceWithView('courseCommentsEditor', 'courseCommentsDisplay');
}

function onAddDatabase(section) {
	replaceWithEditor('databasesDisplay'+section, 'databasesEditor'+section);
	var editorSection = $('databasesEditor'+section);
	$(editorSection)
		.down("#"+(_isCoursePage()?"Course":"Department")+"EditorAction"+section)
		.value="add";
	$(editorSection).down("select").show();
	$(editorSection).down(".databaseName").hide();
	$(editorSection).down("select").options[0].selected = true;
	$(editorSection).down("textarea").value = "";
}

function onEditDatabase(database_id, section) {
	replaceWithEditor('databasesDisplay'+section, 'databasesEditor'+section);
	var editorSection = $('databasesEditor'+section);
	$(editorSection)
		.down("#"+(_isCoursePage()?"Course":"Department")+"EditorAction"+section)
		.value="edit";
	if ($(editorSection).down("select")) {
		$(editorSection).down("select").hide();
	}
	$(editorSection).down(".editRefDbId").value = database_id;  	
	$(editorSection).down(".databaseName").innerHTML =
		$("db_"+database_id).down(".databaseLink").innerHTML; 
	$(editorSection).down(".databaseName").show();
	$(editorSection).down("textarea").value = $("db_"+database_id).down(".databaseRawDescription").innerHTML;
}

function onEditBackgroundLink() {
	replaceWithEditor('databasesDisplay1', 'backgroundLinkEditor');
}

function onCancelBackgroundLink() {
	replaceWithView('backgroundLinkEditor', 'databasesDisplay1');
}

function onEditBookTools() {
	replaceWithEditor('databasesDisplay2', 'bookToolsEditor');
}

function onCancelBookTools() {
	replaceWithView('bookToolsEditor', 'databasesDisplay2');
}

function onEditArticleTools() {
	replaceWithEditor('databasesDisplay3', 'articleToolsEditor');
}

function onCancelArticleTools() {
	replaceWithView('articleToolsEditor', 'databasesDisplay3');
}

function onCancelDatabase(section) {
	replaceWithView('databasesEditor'+section, 'databasesDisplay'+section);
}

function onAddLink() {
	replaceWithEditor('linksDisplay', 'linksEditor');
	$('linksEditor').down("#CourseEditorAction").value="add";
	$('linksEditor').select('textarea', 'input[type="text"]').
		each(function(input) { input.value="" });
}

function onEditLink(link_id) {
	replaceWithEditor('linksDisplay', 'linksEditor');
	$('linksEditor').down("#CourseEditorAction").value="edit";
	$('linksEditor').down("#CourseLinkId").value = link_id; 
	$('linksEditor').down("#LinkTitle").value =	$("link_"+link_id).down("a").innerHTML; 
	$('linksEditor').down("#LinkUrl").value =	$("link_"+link_id).down("a").href; 
	$('linksEditor').down("#LinkDescription").value =	
		$("link_"+link_id).down(".linkDescription").innerHTML; 
}

function onCancelLink() {
	replaceWithView('linksEditor', 'linksDisplay');
}

//var resetValues = [];

function replaceWithEditor(display, editor) {
	$(display).blindUp({duration: 0.25});
	$(editor).slideDown({duration: 0.25});
	$$('.editorLink').each(function (editorLink) {
		editorLink.addClassName('disabledEditorLink');
	});
	$$('.section').each(function (section) {
		if (!($(editor).descendantOf(section))) {
			section.addClassName('disabledSection');
		}
	});

	
	function grabFocus() {
		$firstInput = $(editor).down('input[type="text"]');
		if ($firstInput == null) {
			$firstInput = $(editor).down('textarea');
		}
		$firstInput.focus();
		/* 
		if (resetValues[editor] == null) {
			resetValues[editor] = $(editor).down('textarea').getValue();
		}
		else {
			$(editor).down('textarea').innerHTML = resetValues[editor];
		}
		*/
	}

	if ($(editor).down('textarea') || $(editor).down('input[type="text"]')) {
		setTimeout(grabFocus, 300);
	}

	jumpToSlowly(editor);	
}

function replaceWithView(editor, display) {
	$(editor).blindUp({duration: 0.25});
	//$(display).slideDown({duration: 0.25});
	$(display).blindDown({duration: 0.25});

	$$('.editorLink').each(function (editorLink) {
		editorLink.removeClassName('disabledEditorLink');
	});
	$$('.section').each(function (section) {
		section.removeClassName('disabledSection');
	});

}

// sortable reference databases
// code adapted from:
// http://www.jhl.it/Courses/LUGPC4.html
// © Copyright John Leach 2007-2008. Content licensed according to the Artistic License 2.0.
// and
// http://zenofshen.com/posts/ajax-sortable-lists-tutorial
// zen of shen © Paul Shen 2008
// Contents under Creative Commons License
var sortableLists = {

	updated: function (list) {
		if (list.id == "databasesSection31" || list.id == "databasesSection32") {
			var orderString =
				Sortable.serialize("databasesSection31") + "&" +
				Sortable.serialize("databasesSection32");
		}
		else {
			var orderString =	Sortable.serialize(list.id);
		}	
		
		new Ajax.Updater("ajaxResponse",
				"/library/coursepages/"+
					(_isCoursePage()?"coursesEditor":"departments")+
					(list.id=="linksList" ? "/sortLinks/" : "/sortDatabases/") + 
					//courseId,
					unitId, 
			{
				method: "post",
				parameters: { data: orderString }
			});
	},
	
	createSortables: function(event) {
		if (! _isEditor()) {
			return;
		}

	  var groups = new Array();
	  groups[0] = ["databasesSection11"];
	  groups[1] = ["databasesSection21"];
	  groups[2] = ["databasesSection31", "databasesSection32"];
	  groups[3] = ["databasesSection41"];
	  if (_isCoursePage()) {
	  	groups[4] = ["linksList"];
	  }

		Element.extend(groups).each(function (group, groupId) {
			Element.extend(group);
			$(group).each(function (id) {
				Sortable.create(id, {
					dropOnEmpty: true,
					containment: group,
					constraint: false,
					onUpdate: sortableLists.updated
				});
			});
		});
	}
};

// IE sometimes generates dom:loaded too early
setTimeout(sortableLists.createSortables, 1000);
setTimeout(loadElectronicReserves, 200);
setTimeout(loadTraditionalReserves, 250);
//document.observe("dom:loaded", sortableLists.createSortables);
//document.observe("dom:loaded", loadElectronicReserves);
//document.observe("dom:loaded", loadTraditionalReserves);


function loadElectronicReserves() {
	loadElectronicReservesToDiv('electronicReservesDisplay', false);
}
function loadElectronicReservesToDiv(targetDiv, force) {
	if (!force && _isEditor() || !_isCoursePage()) return;
	if ($('electronicReservesDisplay') == null) return;
	var url = '/library/coursepages/courses/loadElectronicReserves/' + courseId;
	new Ajax.Updater($(targetDiv), url, {
		onSuccess: function(transport) { // before targetDiv is set with the result
			$(targetDiv).hide();
		},	
		onComplete: function(transport) {
			displayCleanErrorMessageIfNecessary(targetDiv, 
				'Sorry, could not retrieve Electronic Reserves right now.  Please refresh the page or try <a href="http://eres.uwosh.edu/eres/courseindex.aspx?error=&page=instr">this page</a> instead.');
			hideOrShow(targetDiv);
		}
	});
}

function loadTraditionalReserves() {
	loadTraditionalReservesToDiv('traditionalReservesDisplay', false);
//	$('traditionalReservesDisplay').update('<a href="http://oshlib.wisconsin.edu/vwebv/enterCourseReserve.do">Please click here for access to Traditional Reserves.</a> We are currently upgrading the library catalog.  Once this is complete, the reserve items for this class will again be linked directly from this page.');
}
function loadTraditionalReservesToDiv(targetDiv, force) {
	if (!force && _isEditor() || !_isCoursePage()) return;
	if ($('traditionalReservesDisplay') == null) return;
	var url = '/library/coursepages/courses/loadTraditionalReserves/' + courseId;
	new Ajax.Updater($(targetDiv), url, {
		onSuccess: function(transport) { // before targetDiv is set with the result
			$(targetDiv).hide();
		},	
		onComplete: function(transport) {
			displayCleanErrorMessageIfNecessary(targetDiv, 
				'Sorry, could not retrieve Traditional Reserves right now.  Please refresh the page or try <a href="http://polkweb.uwosh.edu/cgi-bin/Pwebrecon.cgi?DB=local&PAGE=rbSearch">this page</a> instead.');
			hideOrShow(targetDiv);
		}
	});
}

function displayCleanErrorMessageIfNecessary(targetDiv, errorMessage) {
	// if an error message was returned, display something friendly
	if ($(targetDiv).down('.cake-debug') != null ||
			$(targetDiv).down('font[size=1]') != null) {
		$(targetDiv).childElements().each(function (errorElement) {
			$(errorElement).hide();
		});
		$(targetDiv).insert(errorMessage);
	}
}

// hide if no reserves, otherwise blind down
function hideOrShow(targetDiv) {
	var result = $(targetDiv).innerHTML.strip().stripTags();
	if (result == "None") {
		$(targetDiv).show();
		window.setTimeout(function() {
			$(targetDiv).up().blindUp({duration: 0.5});
		 }, 1000);
	}
	else {
		$(targetDiv).blindDown({duration: 1.0});
	}
}

function displayImportWizard1() {
	// to avoid IE rendering problem
	$('sessionPanel').hide();

	$('importWizard2').hide();

	$('content').setOpacity(0.3);
	$('importWizard1').show();
	
	$('importPreview').textContent = "Generating Preview...";
	
	var url = '/library/coursepages/coursesEditor/loadImportOptions/';
	new Ajax.Updater('importOptions', url, {
		parameters: {primaryCourseId: courseId },
		method: 'get',
		onComplete: function(transport){
		}
	});
}

function displayImportWizard2(targetCourseId) {
	$('importWizard1').hide();
	$('importWizard2').show();
	jumpTo('siteHeader');
	$('importWizard2').down('#CourseTargetCourseId').value = targetCourseId;
	var url = '/library/coursepages/coursesEditor/previewImport/';
	new Ajax.Updater('importPreview', url, {
		parameters: {primaryCourseId: courseId, targetCourseId: targetCourseId },
		method: 'get',
		onComplete: function(transport){
			loadElectronicReservesToDiv($('importWizard2').down('#electronicReservesDisplay'), true);
			loadTraditionalReservesToDiv($('importWizard2').down('#traditionalReservesDisplay'), true);
		}
	});

}

function cancelImportWizard() {
	$('importWizard1').hide();
	$('importWizard2').hide();
	$('content').setOpacity(1);
}

/*
function confirmCopyright() {
	accepted = confirm(
		"Copyright Notice\n\n" +
		"Please be advised that to use electronic material, you must agree to the " +
		"following by clicking the 'OK' button below:\n\n" +
		"The copyright law of the United States (Title 17, United States Code) governs " +
		"the making of photocopies or other reproductions of copyrighted materials. " +
		"Under certain conditions specified in the law, libraries and archives are " +
		"authorized to furnish a photocopy or other reproduction. One of these specified " +
		"conditions is that the photocopy or reproduction is not to be used for any " +
		"purpose other than private study, scholarship, or research. If a user makes a " +
		"request for, or later uses, a photocopy or reproduction for purposes in excess " +
		"of fair use that user may be liable for copyright infringement.");
	return accepted;
}
*/

function jumpToSlowly(id) {
	if (id) {
		new Effect.ScrollTo($(id).up(), {offset: -15});
	}
}

function jumpTo(id) {
	if (id) {
		$(id).up().scrollTo();
	}
}

function onToolFormSubmit(toolId) {
	var form = $(toolId).down('form');
	if (toolId == 'badgerCatTool') {
		convertFormToLink(form);
		return false;
	}
}

// for web proxy
var proxyPrefix = 'http://www.remote.uwosh.edu/login?url='; 
function convertFormToLink(form) {
	var url = proxyPrefix + form.action + '?';
	var inputs = $(form).getElementsBySelector('input');
	$(inputs).each(function (input) {
		url += '&' + $(input).name + '=' + $(input).getValue();
	});
	
	window.location.href = url;
}

function onToolInputFocused(input) {
	$(input).style.color = '#000000';
	$(input).value = '';
}


document.observe("dom:loaded", addCheckboxListeners);
function addCheckboxListeners() {
	$$('#bookToolsEditor input[type=checkbox]').each(function (checkbox) {
		checkbox.observe("click", onBooksSearchToolsCheckboxChange);
	});
} 

function onBooksSearchToolsCheckboxChange() {
	var checkboxes = $$('#bookToolsEditor input[type=checkbox]');
	var saveButton = $('bookToolsEditor').down('input[type=submit]');
	$(saveButton).disable();
	$(checkboxes).each(function (checkbox) {
		if (checkbox.checked) {
			saveButton.enable();
		}
	});
}

function onDepartmentBrowseChange(select) {
	var departmentId = $(select).getValue();
	if (departmentId == '-') return;
	$('departmentCourses').innerHTML = "Loading ...";
	var url = '/library/coursepages/home/browseDepartment/' + departmentId;
	new Ajax.Updater('departmentCourses', url, {
		method: 'get'
	});
}

function switchHomeTab(tab, tabName) {
	var tabPanels = $$('div.tabPanel');
	tabPanels.each(function(tabPanel) {
		if (tabPanel.id == tabName+"Panel") {
			tabPanel.show();
		}
		else {
			tabPanel.hide();
		}
	}); 

	if (tab != null) {
		tab.blur();
	}	
	var targetTab = $(tab).up();
	$$('#tabBar span.tab').each(function(tab) {
		if (tab == targetTab) {
			tab.addClassName('activeTab');
		}
		else {
			tab.removeClassName('activeTab');
		}
	});
}

function _cpDebug(message) {
	message = "<p>"+message+"</p>";
	$('cpDebug').insert(message, "bottom");
}

function openD2L() {
	window.open("https://uwosh.courses.wisconsin.edu/","_blank","width=850,height=700,status=1,toolbar=1,location=1,menubar=1,resizable=1,scrollbars=1");
	return false;
}
