/*
 * utils.js
 *
 * Version: $Revision: 1.7 $
 *
 * Date: $Date: 2006/09/19 09:12:17 $
 *
 * Copyright (c) 2004, Hewlett-Packard Company and Massachusetts
 * Institute of Technology.  All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are
 * met:
 *
 * - Redistributions of source code must retain the above copyright
 * notice, this list of conditions and the following disclaimer.
 *
 * - Redistributions in binary form must reproduce the above copyright
 * notice, this list of conditions and the following disclaimer in the
 * documentation and/or other materials provided with the distribution.
 *
 * - Neither the name of the Hewlett-Packard Company nor the name of the
 * Massachusetts Institute of Technology nor the names of their
 * contributors may be used to endorse or promote products derived from
 * this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
 * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
 * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
 * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
 * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
 * DAMAGE.
 */

/*
 * Utility Javascript methods for DSpace
 */

// Popup window - here so it can be referred to by several methods
var popupWindow;

// =========================================================
//  Methods for e-person popup window
// =========================================================

// Add to list of e-people on this page -- invoked by eperson popup window
function addEPerson(id, email, name)
{
	// Enovation: changing all references to forms[0] to forms[1] for ticket #3249
    var newplace = window.document.forms[1].eperson_id.options.length;

    if (newplace > 0 && window.document.forms[1].eperson_id.options[0].value == "")
    {
        newplace = 0;
    }

    // First we check to see if e-person is already there
    for (var i = 0; i < window.document.forms[1].eperson_id.options.length; i++)
    {
        if (window.document.forms[1].eperson_id.options[i].value == id)
        {
            newplace = -1;
        }
    }

    if (newplace > -1)
    {
        window.document.forms[1].eperson_id.options[newplace] = new Option(name + " (" + email + ")", id);
    }
}

// Add to list of groups on this page -- invoked by eperson popup window
function addGroup(id, name)
{
	// Enovation: changing all references to forms[0] to forms[1] for ticket #3249
    var newplace = window.document.forms[1].group_ids.options.length;

	if (newplace > 0 && window.document.forms[1].group_ids.options[0].value == "")
    {
        newplace = 0;
    }

    // First we check to see if group is already there
    for (var i = 0; i < window.document.forms[1].group_ids.options.length; i++)
    {
        // is it in the list already
        if (window.document.forms[1].group_ids.options[i].value == id)
        {
            newplace = -1;
        }

        // are we trying to add the new group to the new group on an Edit Group page (recursive)
        if (window.document.forms[1].group_id)
        {
            if (window.document.forms[1].group_id.value == id)
            {
                newplace = -1;
            }
        }
    }

    if (newplace > -1)
    {
        window.document.forms[1].group_ids.options[newplace] = new Option(name + " (" + id + ")", id);
    }
}

// This needs to be invoked in the 'onClick' javascript event for buttons
// on pages with a dspace:selecteperson element in them
function finishEPerson()
{
	// Enovation: changing all references to forms[0] to forms[1] for ticket #3249
    selectAll(window.document.forms[1].eperson_id);

	if (popupWindow != null)
	{
		popupWindow.close();
	}
}

// This needs to be invoked in the 'onClick' javascript event for buttons
// on pages with a dspace:selecteperson element in them
function finishGroups()
{
	// Enovation: changing all references to forms[0] to forms[1] for ticket #3249
    selectAll(window.document.forms[1].group_ids);

    if (popupWindow != null)
    {
		popupWindow.close();
    }
}

// =========================================================
//  Miscellaneous utility methods
// =========================================================

// Open a popup window (or bring to front if already open)
function popup_window(winURL, winName)
{
    var props = 'scrollBars=yes,resizable=yes,toolbar=no,menubar=no,location=no,directories=no,width=640,height=480';
    popupWindow = window.open(winURL, winName, props);
    popupWindow.focus();
}


// Select all options in a <SELECT> list
function selectAll(sourceList)
{
    for(var i = 0; i < sourceList.options.length; i++)
    {
        if ((sourceList.options[i] != null) && (sourceList.options[i].value != ""))
            sourceList.options[i].selected = true;
    }
    return true;
}

// Deletes the selected options from supplied <SELECT> list
function removeSelected(sourceList)
{
    var maxCnt = sourceList.options.length;
    for(var i = maxCnt - 1; i >= 0; i--)
    {
        if ((sourceList.options[i] != null) && (sourceList.options[i].selected == true))
        {
            sourceList.options[i] = null;
        }
    }
}






//******************************************************
// Functions used by controlled vocabulary add-on
// There might be overlaping with existing functions
//******************************************************

function expandCollapse(node, contextPath) {
	node = node.parentNode;
	var childNode  = (node.getElementsByTagName("ul"))[0];

	if(!childNode) return false;

	var image = node.getElementsByTagName("img")[0];

	if(childNode.style.display != "block") {
		childNode.style.display  = "block";
		image.src = contextPath + "/image/controlledvocabulary/m.gif";
		image.alt = "Collapse search term category";
	} else {
		childNode.style.display  = "none";
		image.src = contextPath + "/image/controlledvocabulary/p.gif";
		image.alt = "Expand search term category";
	}

	return false;
}


function getAnchorText(ahref) {
 	if(isMicrosoft()) return ahref.childNodes.item(0).nodeValue;
	else return ahref.text;
}

function getTextValue(node) {
 	if(node.nodeName == "A") {
 		return getAnchorText(node);
 	} else {
 		return "";
 	}

}


function getParentTextNode(node) {
	var parentNode = node.parentNode.parentNode.parentNode;
	var children = parentNode.childNodes;
	var textNode;
	for(var i=0; i< children.length; i++) {
		var child = children.item(i);
		if(child.className == "value") {
			return child;
		}
	}
	return null;
}

function ec(node, contextPath) {
	expandCollapse(node, contextPath);
	return false;
}


function i(node) {
	return sendBackToParentWindow(node);
}


function getChildrenByTagName(rootNode, tagName) {
	var children = rootNode.childNodes;
	var result = new Array(0);
	if(children == null) return result;
	for(var i=0; i<children.length; i++) {
		if(children[i].tagName == tagName) {
			var elementArray = new Array(1);
			elementArray[0] = children[i];
			result = result.concat(elementArray);
		}
	}
	return result;
}

function popUp(URL) {
	var page;
	page = window.open(URL, 'controlledvocabulary', 'toolbar=0,scrollbars=1,location=0,statusbar=0,menubar=0,resizable=1,width=650,height=450');
}


function isNetscape(v) {
		  return isBrowser("Netscape", v);
}

function isMicrosoft(v) {
		  return isBrowser("Microsoft", v);
}

function isMicrosoft() {
		  return isBrowser("Microsoft", 0);
}


function isBrowser(b,v) {
		  browserOk = false;
		  versionOk = false;

		  browserOk = (navigator.appName.indexOf(b) != -1);
		  if (v == 0) versionOk = true;
		  else  versionOk = (v <= parseInt(navigator.appVersion));
		  return browserOk && versionOk;
}


//JG functions to automate portions of the dc.neeo.contributor field 2009-07-07

function NEEOModsName() {
   
   // first remove any neeo_contributor fields already in place, eg reset
   deleteNeeo();  
   
   // if any authors have been input,
    var count_aut = countAuthors();
       
    if (count_aut > 0) {
        // do the authors
        neeoAuthor(count_aut);
        // then do the editors
        var count_edt = countEditors();
        editorLoop(count_aut, count_edt);
    }
    
    //otherwise just do the editors
    
    else {        
        var count_edt = countEditors();
        neeoEditor(count_edt);
    }
}

function countAuthors() {
    
    var matchingElements = [];
    var numberInput = document.edit_metadata.elements.length;
    var inputIndex;
    var pattern1 = /dc_contributor_author_last/;
    var pattern2 = /.+/;
    
    for (inputIndex = 0; inputIndex < numberInput; inputIndex++)
   {      
      var inputName = document.edit_metadata.elements[inputIndex].name;
      var inputValue = document.edit_metadata.elements[inputIndex].value;
      
      if (pattern1.test(inputName) == true && pattern2.test(inputValue) == true) {
        matchingElements.push(inputName);      
     }
   }
   
    var count_aut = matchingElements.length;
    
    //alert(count_aut);
    return count_aut;
}

function countEditors() {
    
    var matchingElements = [];
    var numberInput = document.edit_metadata.elements.length;
    var inputIndex;
    var pattern1 = /dc_contributor_editor_last/;
    var pattern2 = /.+/;
    
    for (inputIndex = 0; inputIndex < numberInput; inputIndex++)
   {      
      var inputName = document.edit_metadata.elements[inputIndex].name;
      var inputValue = document.edit_metadata.elements[inputIndex].value;
      
      if (pattern1.test(inputName) == true && pattern2.test(inputValue) == true) {
        matchingElements.push(inputName);      
     }
   }
   
    var count_edt = matchingElements.length;
    
    //alert(count_edt);
    return count_edt;
}

function neeoAuthor(count_aut) {
    
    with (document.edit_metadata) {
        dc_neeo_contributor_0.value = dc_contributor_author_last_0.value + "|" + dc_contributor_author_first_0.value + "|aut|";
    }
    
    var m = count_aut - 1;
    
    var i = 1;
    for (i = 1; i <= m; i++) {
        newNeeo(i, "aut");
    }
}

function neeoEditor(count_edt) {
    
    with (document.edit_metadata) {
        dc_neeo_contributor_0.value = dc_contributor_editor_last_0.value + "|" + dc_contributor_editor_first_0.value + "|edt|";
    }
    
    var m = count_edt - 1;
    
    var i = 1;
    for (i = 1; i <= m; i++) {
        newNeeo(i, "edt");
    }
}

function newNeeo(n, type) {
    
    if (type == "aut") {
        var role = "author";
    } else {
        var role = "editor";
    }
    
    var neeoValue = "dc_neeo_contributor_" + n;
    var lastName = "dc_contributor_" + role + "_last_" + n;
    var firstName = "dc_contributor_" + role + "_first_" + n;
    
    var newNodeInput = document.createElement('input');
    newNodeInput.setAttribute('type', 'text');
    newNodeInput.setAttribute('size', '50');
    newNodeInput.setAttribute('name', neeoValue);
    
    var current = document.getElementById('formNode');
    current.appendChild(newNodeInput);
    
    
    document.edit_metadata[neeoValue].value = document.edit_metadata[lastName].value + "|" + document.edit_metadata[firstName].value + "|" + type + "|";
}

function editorLoop(count_aut, count_edt) {
    //create editor nodes for each editor entered, if there are also authors entered
    
    var i = 1;
    var editor_position = 0;
    
    while (i <= count_edt) {
        
        var neeoValue = "dc_neeo_contributor_" + count_aut;
        var editorLast = "dc_contributor_editor_last_" + editor_position;
        var editorFirst = "dc_contributor_editor_first_" + editor_position;
        
        //build the new node
        var newNodeInput = document.createElement('input');
        newNodeInput.setAttribute('type', 'text');
        newNodeInput.setAttribute('size', '50');
        newNodeInput.setAttribute('name', neeoValue);
        
        //get the parent node (the form)-- this should be added to edit-metadata.jsp
        var current = document.getElementById('formNode');
        current.appendChild(newNodeInput);
        
        //insert the new neeo_contributor element
        document.edit_metadata[neeoValue].value = document.edit_metadata[editorLast].value + "|" + document.edit_metadata[editorFirst].value + "|edt|";
        
        count_aut++;
        editor_position++;
        i++;
    }
}

function deleteNeeo() {
    
    var matchingElements = [];
    var numberInput = document.edit_metadata.elements.length;
    var inputIndex;
    var pattern1 = /dc_neeo_contributor_[\d]/;
    var pattern2 = /dc_neeo_contributor_0/;

    //loop through all inputs, match neeo_contributors
    for (inputIndex = 0; inputIndex < numberInput; inputIndex++)   {
    
      var node = document.edit_metadata.elements[inputIndex];
      var inputName = node.name;
     
      if (pattern1.test(inputName) == true) {
        matchingElements.push(node);
     }
   }
   
   //loop through all neeo_contributors, delete all but the first one
   var matchingInput = matchingElements.length;   
   for (i = 0; i < matchingInput; i++) {
   
        var matchingNode = matchingElements[i];
        
        if (pattern2.test(matchingElements[i].name) == false) {
        matchingNode.parentNode.removeChild(matchingNode);
     }
  }     
}

//JG script to add a link in item page to item's statistics page 2009-08-26

function statsLink() {

    var handle = document.getElementsByTagName("code");                               
    var regex = new RegExp("10197\/.+");                               
    var itemHandle = regex.exec(handle[0].innerHTML);    

    document.writeln('<table border=\"0\" align=\"center\">');
    document.writeln('<tr>');
    document.writeln('<td>');
    document.writeln('<a href=\"http://irserver.ucd.ie/dspace/stats?level=item&type=access&page=downviews-series&object-id=' + itemHandle + ' \" target=\"new_window\"><img alt=\"View statistics for this item\" src=\"http://irserver.ucd.ie/dspace/image/graph.png\" width=\"24\" height=\"19\" border=\"0\"/></a>');
    document.writeln('</td>');
    document.writeln('<td>');                          
    document.writeln('<a href=\"http://irserver.ucd.ie/dspace/stats?level=item&type=access&page=downviews-series&object-id=' + itemHandle + ' \" target=\"new_window\">View statistics for this item</a>');                               
    document.writeln('</td>');
    document.writeln('</tr>');
    document.writeln('</table>');
}

