
function switchClasses ( element, classToRemove, classToAdd)
{
  if(element){
    element.removeClassName(classToRemove);
    element.addClassName(classToAdd);
  }
}

function togglePopupDiv( inputElement, div1ID, div2ID )
{
  var div1 = $(div1ID);
  var div2 = $(div2ID);
  
  if ((!div1) || (!div2)){
    return;
  }
  if(div1.hasClassName ('visible')){
    switchClasses(div1, 'visible', 'hidden');
    switchClasses(div2, 'hidden', 'visible');

    inputElement.src='common/images/scroll_down_active.gif';
  }else if (div1.hasClassName('hidden')) {

    switchClasses(div1,  'hidden', 'visible');
    switchClasses(div2,  'visible', 'hidden');

    inputElement.src='common/images/scroll_up_active.gif';
  }
  return false;
}


  
//--------------------------------------------------------------------------------
//--------------------------------------------------------------------------------
//--------------------------------------------------------------------------------


function getCheckedProjects()
{
    return $$('input[type="checkbox"].projectCheckbox').select( function(n){ return n.checked;});
}

function getCheckedLibraries()
{
    return $$('input[type="checkbox"].libraryCheckbox').select( function(n){ return n.checked;});
}

function addProjectRestrictions(args)
{
    saveProjectCookie();
    if (projectIDs.length == 0){
	deleteAttr(args, 'projects');
	return;
    } 
    
    // Accumulate a string of project ids, ie:  90,81,78
    args['projects'] = projectIDs.join(",");
}

function saveProjectCookie()
{
    if (projectIDs.length == 0){
	setCookie('searchProjIDs','',-10);
	return;
    } 
    // Accumulate a string of project ids, ie:  90,81,78
    setCookie('searchProjIDs',projectIDs.join(","), 30);
}

var projectIDs = []

function onCloseProjectDialog()
{
    var checkedBoxes = getCheckedProjects();
    if ( checkedBoxes == null){
	return;
    }
    projectIDs = checkedBoxes.pluck('value');
    saveProjectCookie();
    updateProjectTitles();
}

function setupProjectCheckBoxes( )
{
    var projectIDHash = $H();
    projectIDs.each(function(item){ projectIDHash[item] = 1 ;});
    $$('input[type="checkbox"].projectCheckbox').each( function (item) {
	if (item.value in  projectIDHash ){
	    item.checked = true;
	} else {
	    item.checked = false;
	}});
}

var libraryIDs = []
function setupLibraryCheckBoxes()
{
    var libraryIDHash = $H();
    libraryIDs.each(function(item){ libraryIDHash[item] = 1 ;});
    $$('input[type="checkbox"].libraryCheckbox').each( function (item) {
	if (item.value in  libraryIDHash ){
	    item.checked = true;
	} else {
	    item.checked = false;
	}});

}


function onCloseLibraryDialog()
{
    var checkedBoxes = getCheckedLibraries();
    if ( checkedBoxes == null){
	return;
    }

    libraryIDs = checkedBoxes.pluck('value');
    
    if (libraryIDs.length == 0){
	libraryIDs[0] = 1;
    }
    saveLibraryCookie();
    updateLibraryTitles();
}

function saveLibraryCookie(){
    if (libraryIDs.length == 0){
	setCookie('searchLibraryIDs','',-10);
	return;
    }
    // Accumulate a string of project ids, ie:  90,81,78
    setCookie('searchLibraryIDs',   libraryIDs.join(","), 30);
}

function addLibraryRestrictions(args)
{
    saveLibraryCookie();

    if (libraryIDs.length == 0){
	deleteAttr(args, 'libraries');
	return;
    }
    // Accumulate a string of project ids, ie:  90,81,78
    args['libraries'] = libraryIDs.join(",");
}


function updateProjectTitles(  )
{
    var titles = '' ;

    $A(projectIDs).each ( function (item){
	if ( item in projectIDName ){
	    titles = titles + projectIDName[item]+ '<br>';
	}
    });

    if (titles.length > 0){
	$('projectList').innerHTML = titles ;
    }else{
	$('projectList').innerHTML = "No restrictions";
    }
}

function updateLibraryTitles( )
{
    var libraryList = $('libraryList');

    if (!libraryList){
	return;
    }
    
    var titles = '';
    $A(libraryIDs).each ( function (item){
	if ( item in libraryIDName ){
	    titles = titles + libraryIDName[item]+ '<br>';
	    
	} 
    });
    
    if (titles.length > 0){
	libraryList.innerHTML = titles ;
    }else{
	libraryList.innerHTML = "Public";
    }
}


function buildAdvSearchURL( baseURL, withAction )
{
  var txtNames = {'txtAny':'', 'txtExact':'','txtAll':'','txtNone':'','txtAuthor':'','txtPublisher':''};
  var field = null;
  var atLeastOneArg = false;

  // Values in fields
  for( fieldName in txtNames){
    field = $("ctl00_ContentPlaceHolder1_" + fieldName);
    if (field){
      txtNames[fieldName] =  field.value;
    }
  }

  var args = getArgs();

  deleteAttr(args,'like');
  deleteAttr(args,'query');
  deleteAttr(args,'formQuery');
  deleteAttr(args, 'basic');

  for ( fieldName in txtNames ){
    if (txtNames[fieldName] != ""){
      args[fieldName] = txtNames[fieldName];
      atLeastOneArg = true;
    }else{
      deleteAttr(args, fieldName);
    }
  }

  updateRequireAbstracts(args);
  addProjectRestrictions(args);
  addLibraryRestrictions(args);
    
    updateSortMethod(args);

  if (withAction) {
    
    var element = document.getElementById('reaction');
    
    args["reaction"]= element.value;
  } else {
    args["reaction"] = "";
  }


  var ansids = getAnsids();
  if ( ansids.length > 0){
    args['ansids'] = ansids;
  } else{
    deleteAttr(args, 'ansids');
  }

  if ( atLeastOneArg ){
    args['page'] = 1;
  }else{
    deleteAttr(args, 'page');
  }

  var newURLArgs = buildURLArgs(args);
  
  return baseURL + newURLArgs;  
}


var ChooseProjectsDlg = null;
var Dialogs = { 'ChooseProjects':null,
    'SavedTerms' : null,
    'ChooseLibraries': null};



function showProjectsDialog(){
    try{
	ShowDialogDiv(  'Choose Projects', 'projectContainer', 'innerProject', 'ChooseProjects', onCloseProjectDialog,    setupProjectCheckBoxes,
			'Close this dialog to save changes' );

    }catch(e){
	//console.log(e);
    }
}  

function showLibrariesDialog(){
    try{
	ShowDialogDiv(  'Choose Libraries', 'libraryContainer', 'innerLibrary', 'ChooseLibraries', onCloseLibraryDialog,    setupLibraryCheckBoxes,
			'Close this dialog to save changes' );

    }catch(e){
	//console.log(e);
    }
}  


function showSavedTermsDialog(){
    try{
	ShowDialogDiv( 'Saved Terms', 'savedTermsContainer', 'innerTermsList', 'SavedTerms', null, null,null );
    }catch(e){
	//console.log(e);
    }
}


function ShowDialogDiv(title, parentID, divID, dlgName, onDeleteFunction, onShowFunction, statusBarText ){

    if ( Dialogs[dlgName]  != null) { 
	Dialog.alert("Close the window '" + title + "' before opening it again!", {width:200, height:130}); 
    }  else { 

	Dialogs[dlgName]  = new Window({maximizable: false, 
					resizable: false, 
					minimizable:false,
					hideEffect:Element.hide, 
					showEffect:Element.show, 
					minWidth: 10,  
					destroyOnClose: true});

	Dialogs[dlgName].setContent(divID, true, true);
	if (statusBarText ){
            Dialogs[dlgName].setStatusBar(statusBarText);
	}

	Dialogs[dlgName].show(); 
	if(onShowFunction){
	    onShowFunction();
	}

	// Set up a windows observer, 
	myObserver = { onDestroy: function(eventName, win)  { 
            if (win == Dialogs[dlgName] ) { 
		if(onDeleteFunction != null){
		    onDeleteFunction();
		}
		//$( parentID ).appendChild($(divID)); 
		Dialogs[dlgName] = null; 
		Windows.removeObserver(this); 
	    }
	}
		     };

	Windows.addObserver(myObserver); 
    }
}

function  readAndUseCookieValue( urlArgName, 
				 cookieName, 
				 globalarrayVar,
				 cleanupFunction,
				 validIDHash) {

    var args = getArgs();    
    var arrayValues = null;
    var savedValue = null;

    if (urlArgName in args){
	savedValue = args[urlArgName];
    } else {
	// restore the values from the cookie when there's
	// no url args at all.
	var objCount = 0;
	for(_obj in args) objCount++;
	if (objCount == 0){
	    savedValue = getCookie(cookieName);
	}
    }

    if (savedValue == null){
	return;
    }
    if (savedValue.length > 0){
	arrayValues = savedValue.split(',');
    }
	
    if (arrayValues != null && 
	arrayValues != '' 
	&& arrayValues.length > 0){
	var index = 0;
	$A(arrayValues).each( function(val){
	    if (val in validIDHash){
		globalarrayVar[index++] = parseInt(val);
	    }});
	cleanupFunction();
    }
}

function  setSelectSortOnChange(){
    var sortSelect = $(selectSortID);
    if (!sortSelect){
	return;
    }
    Event.observe(sortSelect, 'change', function() { doAdvSearch(); });
}

// reset the radio button, on page load
function setupPage() {
    var advButton = $('advSearchRadio');
    var simpleButton = $('simpleSearchRadio');

    if (advButton ) {
        advButton['checked'] =true;
    }

    readAndUseCookieValue('projects',
			  'searchProjIDs',
			  projectIDs,
			  updateProjectTitles,
			 projectIDName);

    readAndUseCookieValue('libraries',
			  'searchLibraryIDs',
			  libraryIDs,
			  updateLibraryTitles,
			 libraryIDName);

    UpdateSortSelection();
    UpdateAbstractCheckbox();
    setSelectSortOnChange();
    //window.loadFirebugConsole();
}

Event.observe(window, 'load', function() { setupPage(); });
