// dash-support.js -- various JavaScript hacks used by DASH presentation.
//  Author: Larry Stone
//  $Revision $

// NOTE: by convention all global identifiers start with "dash" to
// minimize the chance of conflicts with other JS that gets loaded.

// return false on success so link isn't followed
// expected to be the onClick event handler of an A tag, e.g.
//  <a href="foo/bar.html" target="_blank" onclick="javascript:return dashPopup(this);"> ...
function dashPopup(linktag)
{
    if (!window.focus)
        return true;
    var h = Math.floor(window.outerHeight * 6 / 10);
    var w = Math.floor(window.outerWidth * 8 / 10);
    var win = window.open(linktag.href, "DASH Popup", "width="+w+",height="+h+",toolbar=no,location=no,resizable=yes,scrollbars=yes");
    win.focus();
    return false;
}

// logic to disable embargo date fields when chosen license disallows them
// assumes license=="LAA" is the only enabling condition..
function dashLicenseEnableEmbargo(formID)
{
    var form = document.getElementById(formID);

    // first, figure out chosen license if any:
    var license = null;
    var lr = document.getElementsByName("lic_license_type");
    for (var i = 0; i < lr.length; ++i) {
        if (lr[i].type == "radio" && lr[i].checked) {
            license = lr[i].value;
            break;
        }
    }

    // now apply disable rule to embargo inputs
    var disableEmb =  license != 'LAA';
    var embYear =  form.elements['lic_embargo_year'];
    var embMonth = form.elements['lic_embargo_month'];
    var embDay =   form.elements['lic_embargo_day'];

    embYear.disabled = disableEmb;
    embMonth.disabled = disableEmb;
    embDay.disabled = disableEmb;

    // DEBUG:
    //console.log("embargo disable = "+disableEmb);
}

//-------------------------- DOI lookup

// Attempt to get DOI automatically by querying CrossRef.  Uses the
// existing Choices interface for the AJAX bit, since that hides the
// CrossRef configuration and password on the server.
//
// Assumptions:
//  - form element 'dc_relation_isversionof' is the target to fill in
//  - choice authority field is bogus "query_doi"
//  - Author in form element 'dc_contributor_author_last' etc (_first, _1, etc)
//  - Title in form element 'dc_title'
//
// FUTURE IMPROVEMENTS:
//  1. This only allows for ONE result.  When there are multiple possible
//     matches it should present a list, either by drop-down or perhaps popup.
//     Probably want to show some details about each DOI with that list.
//  2. The crossref protocol has a more precise mode with more metadata
//     elements, though some of them are hard to get from our elements,
//     e.g. journal issue, page etc.  Could look into whether providing SOME
//     of those fields improves the matching.

function dashLookupDOI(form, contextPath, indicatorID)
{
    var title =  dashStringTrim(form.elements['dc_title'].value);
    // get either first of many names or current value:
    var last = form.elements['dc_contributor_author_last_1']
    if (last == null)
        last = form.elements['dc_contributor_author_last']
    var surname = dashStringTrim(last.value);

    // ID of span for reporting errors
    doiErrorID = "dash-doi-error-message";

    // sanity check: must have title and lastname
    if (title == "")
    {
        alert("You must fill in the Title to look up a DOI.");
        return;
    }
    if (surname == "")
    {
        alert("You must fill in at least the last name of the first author to look up a DOI.");
        return;
    }

    var indicator = indicatorID == null ? null : document.getElementById(indicatorID);
    if (indicator != null)
        indicator.style.display = "inline";

    // query text is: {surname}|{title}
    var query = surname+"|"+title;

    // find span for status respnose
    var statusSpan = document.getElementById(doiErrorID);
    if (statusSpan == null) {
        var sibs = form.elements['dc_relation_isversionof'].parentNode.getElementsByTagName("span");
        for (var i = 0; i < sibs.length; ++i) {
            if (sibs[i].className.match(" ?field-help ?") != null)
                statusSpan = sibs[i];
        }
    } else {
        statusSpan.innerHTML = "";
    }

    new Ajax.Request(contextPath+"/choices/query_doi",
      {
        method: "get",
        parameters: {query: query, format: 'default', start: 0, limit: 1},
        // this is handy since it gives details of errors in callback
        onException: function(req, e) {
          alert("Query for DOI failed with exception!  req.query="+req.parameters.query+", exception="+e);
          if (indicator != null)
              indicator.style.display = "none";
        },
        onFailure: function() {
          alert("Query for DOI failed in HTTP!");
          if (indicator != null)
              indicator.style.display = "none";
        },
        // Returned XML is <Choices><Choice authority="key" value="val">label</Choice>...
        onSuccess: function(transport) {
          var root = transport.responseXML.firstChild;
          var choices = root.getElementsByTagName('Choice');
          if (choices.length == 0)
          {
            if (statusSpan != null)
            {
                // simulate "insertAfter"...
                statusSpan.parentNode.insertBefore(Builder.node("span",
                                    {class: "error", id: doiErrorID }, "* No DOI was found."),
                                                   statusSpan.nextSibling);
            }
          }
          else
          {
            var result = choices.item(0).getAttributeNode('value').value;
            form.elements['dc_relation_isversionof'].value = result;
          }
          if (indicator != null)
              indicator.style.display = "none";
        }
      });
}

// replicate java String.trim()
function dashStringTrim(str)
{
    var start = 0;
    var end = str.length;
    for (; str.charAt(start) == ' '&& start < end; ++start) ;
    for (; end > start && str.charAt(end-1) == ' '; --end) ;
    return str.slice(start, end);
}
