//-----------------------------------------------------------------------------
// File:  search.js
//
// Purpose:  This file contains the javascript code that is specicific to
//           the advanced and basic search.
//
// Depenedencies:  menu.js, common.js
//----------------------------------------------------------------------------

//-----------------------------------------------------------------------------
// Global variables
//-----------------------------------------------------------------------------

// regexp for empty field expression test.
var emptyString = /^\s*$/;

// holds the errors we'll display
var errors = [];


//-----------------------------------------------------------------------------
// Gets the first occurance of a checkbox which corresponds to the collectionId
//-----------------------------------------------------------------------------
function getCheckBoxFromCollectionId(collectionId)
{
    // Find the checkbox with the default collecion id
    var inputs = document.getElementsByTagName("input");
    for (var i = 0; i < inputs.length; i++)
    {
        if (inputs[i].type == "checkbox")
        {
            var checkBoxValue = inputs[i].value;
            if (collectionId == checkBoxValue       ||
                collectionId == extractId(checkBoxValue) )
            {
                return inputs[i];
            }
        }
    }

    return null;
}

//-----------------------------------------------------------------------------
// validate the simple search form
//-----------------------------------------------------------------------------
function validateSimpleForm(form, field, buttonName)
{
    enableButton(document.getElementById(buttonName), false);

    if (emptyString.test(document.getElementById(field).value))
    {
        window.alert(searchFieldEmpty);
        enableButton(document.getElementById(buttonName), true);
        return false;
    }

    return true;
}

//-----------------------------------------------------------------------------
// set focus on the control named by ctrlName
//-----------------------------------------------------------------------------
function setFocus(ctrlName)
{
    document.getElementById(ctrlName).focus();
}

//-----------------------------------------------------------------------------
// set focus on the first search field.
//-----------------------------------------------------------------------------
function focusOnSearch()
{
    // Find the first input element in the form and set focus to it
    var formElements = document.search.elements;
    for (var i = 0; i < formElements.length; ++i)
    {
        if (formElements[i].type == "text")
        {
            formElements[i].focus();
            break;
        }
    }
}

//-----------------------------------------------------------------------------
// Sets all the check boxes to the passed in value
//-----------------------------------------------------------------------------

function setAllCheckBoxes(formName, fieldNamePrefix, checkValue)
{
    var theForm = document.forms[formName];
    if (theForm === null) 
    {
        return;
    }
    
    // set the check value for all check boxes
    for (var i = 0; i < theForm.elements.length; ++i)
    {
        setElementChecked(theForm.elements[i], checkValue, fieldNamePrefix);
    }
}

//-----------------------------------------------------------------------------
// Sets the check of an element if it has the appropriate string in its field 
// name.
//-----------------------------------------------------------------------------
function setElementChecked(anElement, aCheckedValue, aFieldNamePrefix) 
{
    if (anElement.name.indexOf(aFieldNamePrefix) != -1 && anElement.type == "checkbox") 
    {
        anElement.checked = aCheckedValue;
    }
}

//-----------------------------------------------------------------------------
// add an error the the array of errors to display.
//-----------------------------------------------------------------------------
function addError(errorArray, errorMessage)
{
    errorArray[errorArray.length] = errorMessage;
}

//-----------------------------------------------------------------------------
// ensure that at least one of the required fields is filled out.
//-----------------------------------------------------------------------------
function atLeastOne(errors, searchForm, isAlert)
{
    var isNoSearchTerms = true;
    var formElements = document.search.elements;
    for (var i = 0; i < formElements.length; ++i)
    {
    		
        if (formElements[i].type == "text")
        {
    		if (isAlert && (formElements[i].name == 'alertName' || formElements[i].name == 'description' ||
    			formElements[i].name == 'emailAddress')) {
    			continue;
    		}
            isNoSearchTerms &= emptyString.test(formElements[i].value);
            if (isNoSearchTerms == false) { break; }
        }
    }

    if (isNoSearchTerms)
    {
        addError(errors, searchEmptyMessage);
    }
}

//-----------------------------------------------------------------------------
// just check the years
//-----------------------------------------------------------------------------
function endDateBeforeBeginDate(errorArray, /*beginMonth,*/ beginYear, /*endMonth,*/ endYear) {
    // we need to at least have the years filled in to validate
    if (emptyString.test(beginYear) &&
        emptyString.test(endYear)) {
        return;
    }

    // if either month is empty, just use the years
    //if (emptyString.test(beginMonth) ||
      //  emptyString.test(endMonth)) {
        if (endYear < beginYear) {
            addError(errors, beginDateAfterEndDate);
            return;

        }
}

//-----------------------------------------------------------------------------
// Performs validation on the form data before it is submitted
//-----------------------------------------------------------------------------
function validateForm(form, isAlert) 
{
    enableButton(document.getElementById("searchButton"), false);

    var ret = true;

    atLeastOne(errors, form, isAlert);

    // the end date can't be before the begin date
    if (typeof(form.fromYear) != "undefined")
    {
        endDateBeforeBeginDate(errors, parseInt(form.fromYear.value,10), parseInt(form.toYear.value,10));
    }

    if (areAnyChecked() === false) 
    {
      if(document.getElementById('eow') != null) {
        if(document.getElementById('eow').value == '') {
          addError(errors, noCategoriesSelected);
        }
      } else {
        addError(errors, noCategoriesSelected);
      }
    }

    if (errors.length > 0) 
    {
        var errorString = "";
        for (i = 0; i < errors.length; ++i) 
        {
            errorString += errors[i];
            errorString += '\n';
        }
    
        errors = [];
        window.alert(errorString);

        enableButton(document.getElementById("searchButton"), true);
        
        ret = false;
    }

    if(ret == false) {
        /*var author = document.getElementById('author').value;
        if(author.indexOf(" ")) {
            var bits = author.split(" ");
            document.getElementById('author').value = bits[1];
            document.getElementById('firstName').value = bits[0];
        }*/
    } else {
        combineAuthorFields();
    }
    return ret;
}

//-----------------------------------------------------------------------------
// Initializes the array of checkboxes 
//-----------------------------------------------------------------------------
function setupCategoryTree()
{
    var cb;
    if (typeof(C) == "undefined")
    {
        if (typeof(g_defaultCollection) != "undefined" && g_defaultCollection != "NONE") {
            C = [];

            if (g_defaultCollection == "ALL")
            {
                C[0] = "all";
            } else {
                cb = getCheckBoxFromCollectionId(g_defaultCollection);
                if (cb !== null)
                {
                    C[0] = cb.value;
                }
            }
        }
    }
    else if (C.length === 0)
    {
        for (var i = 0; i < g_collectionIds.length; ++i)
        {
            cb = getCheckBoxFromCollectionId(g_collectionIds[i]);
            if (cb !== null)
            {
                C[C.length] = cb.value;
            }
        }
    }

    if (typeof(C) != "undefined")
    {
        setupTree(C);
    }

    if (g_categories.length === 1)
    {
        expandAll(g_categories);
    }
}

//-----------------------------------------------------------------------------
// Handler for the onload event from the body element
//-----------------------------------------------------------------------------
function onLoad()
{
    setupCategoryTree(); 
    focusOnSearch();
    
    //Look for the flag set on search.jsp and expand if its true.
   	if (typeof(g_expandCollectionTree) != "undefined"){
   		if(g_expandCollectionTree === true ) {
   			toggleAll(g_categories);
   		}	
   	}
   	
    //Store initial values of search form to be used onreset. 
    //assumes non-changing form

    var form = document.search;
    if (form === null) { return true; }
    for (var i = 0; i < form.elements.length; i++) {
        var element = form.elements[i];
        if (element.type == "text")
        {
            initSearchFormVals[i] = element.value;

        }
        else if (element.tagName.toLowerCase() == "select")
        {
            initSearchFormVals[i] = element.selectedIndex;
        }
    }

}

//-----------------------------------------------------------------------------
// Note not used now!  Called when E-prints on Websites subject is chosen from drop down
// Creates checkbox to send source in only if Select... is not chosen
// Item is the this for the select or drop down
// If Select... is chosen it clears the div that may or may not have contained
// a checkbox for the E-prints on Websites
//-----------------------------------------------------------------------------
function createEprintsOnWebsitesCollectionCheckbox(item) {
    if(item != null) {
        if(item.value == '') {
            if(document.getElementById('eowSelection') != null) {
                document.getElementById('eowSelection').innerHTML = '';
            }
        } else {
            var link = document.createElement('input');
            link.setAttribute('type', 'checkbox');
            link.setAttribute('name', 'selectedCollections');
            link.setAttribute('value', item.value);
            link.setAttribute('checked', true);
            if(document.getElementById('eowSelection') != null) {
                document.getElementById('eowSelection').innerHTML = '';
                document.getElementById('eowSelection').appendChild(link);
            }
        }
    }
}

//-----------------------------------------------------------------------------
// toggleSelectedCollection - either creates a checkbox with the special collections
// value or removes it depending on if users has checked Eprints on Websites Checkbox
// param item is the checkox element for searching Eprints on Websites
//-----------------------------------------------------------------------------
function toggleSelectedCollection(item) {
    if(item != null) {
        if(item.checked == true) {
//            alert("checked is true");
             // IE detection... crazy code to make things work in ie
             var isIE=false;
             if(navigator.userAgent.toLowerCase().indexOf("msie") != -1) { isIE = true; }
             if(isIE) {
                 var link = document.createElement('<INPUT type="checkbox" name=\'selectedCollections\' checked />');
                 document.getElementById('eowid').value = "73"
//                 document.getElementById('selectedEOWCollection').value = "73";
                 var tValue = document.getElementById('eowid').value;
//                 alert("tValue:" + tValue);
//                  var i;
//                  for(i=selectedEOWCollection.options.length-1;i>=0;i--){
//                    var option =  selectedEOWCollection.options[i];
//                      if(option.value=='73'){
//                          option.selected=true;
//                          break;
//                      }
//
//                  }
                 link.value=tValue;
//                 link.setAttribute('value', document.getElementById('eowid').value);
             } else {
                 var link = document.createElement('input');
                 link.setAttribute('type', 'checkbox');
                 link.setAttribute('name', 'selectedCollections');
                 link.setAttribute('checked', true);
                 var tValue = document.getElementById('eowid').value;
//                 alert("value:" + tValue);
                 link.setAttribute('value', document.getElementById('eowid').value);
             }



             if(document.getElementById('selectedEOWCollection') != null) {
                document.getElementById('selectedEOWCollection').innerHTML = '';
                document.getElementById('selectedEOWCollection').appendChild(link);
             }

        } else {
//            alert("checked is false");
            document.getElementById('selectedEOWCollection').innerHTML = '';
            document.getElementById('all').checked = '';
        }
    }
}

//-----------------------------------------------------------------------------
// setSelectedCollection - sets the dynamically created selectedCollections
// eprints on websites checkbox to what is chosen in the drop down
// param item is the drop down menu
//-----------------------------------------------------------------------------
function setSelectedCollection(item) {
    var theDiv = document.getElementById('selectedEOWCollection');
    if(theDiv != null) {
        if(theDiv.firstChild != null) {
//            alert("settingEOW"+item);
            theDiv.firstChild.value = item.value;
        }
    }
}

//-----------------------------------------------------------------------------
// selectEprintsOnWebsites - determines if the eprints on websites should be set
// to something other than All Categories; Used in editAlert
// param g_collectionIds are the selected collection ids
//-----------------------------------------------------------------------------
function selectEprintsOnWebsites(g_collectionIds) {
    if(document.getElementById('eow') != null) {
        for(i = 0; i < g_collectionIds.length; i++) {
            if(g_collectionIds[i] > 54 && g_collectionIds[i] < 74) {
                document.getElementById('eow').value =  g_collectionIds[i];
                document.getElementById('searchEOW').checked = true;
                break;
            }
        }
    }
}

//-----------------------------------------------------------------------------
// combineAuthorFields - appends firstName to author field
//-----------------------------------------------------------------------------
function combineAuthorFields() {
    if(document.getElementById('firstName') != null && document.getElementById('firstName') != '') {
      var newVal = document.getElementById('firstName').value + " " + document.getElementById('lastName').value;
      document.getElementById('author').value = newVal;
      //alert(document.getElementById('author').value);
    }
}