/*
 * utils.js
 *
 * Version: $Revision: 1799 $
 *
 * Date: $Date: 2007-04-17 13:15:58 +0100 (Tue, 17 Apr 2007) $
 *
 * 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)
{
    var newplace = window.document.epersongroup.eperson_id.options.length;

    if (newplace > 0 && window.document.epersongroup.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.epersongroup.eperson_id.options.length; i++)
    {
        if (window.document.epersongroup.eperson_id.options[i].value == id)
        {
            newplace = -1;
        }
    }

    if (newplace > -1)
    {
        window.document.epersongroup.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)
{
    var newplace = window.document.epersongroup.group_ids.options.length;

	if (newplace > 0 && window.document.epersongroup.group_ids.options[0].value == "")
    {
        newplace = 0;
    }

    // First we check to see if group is already there
    for (var i = 0; i < window.document.epersongroup.group_ids.options.length; i++)
    {
        // is it in the list already
        if (window.document.epersongroup.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.epersongroup.group_id)
        {
            if (window.document.epersongroup.group_id.value == id)
            {
                newplace = -1;
            }
        }
    }

    if (newplace > -1)
    {
        window.document.epersongroup.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()
{
    selectAll(window.document.epersongroup.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()
{
    selectAll(window.document.epersongroup.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
//******************************************************

var categoryLocale = "default";

function ec(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/m.gif";
	} else {
		childNode.style.display  = "none";
		image.src = contextPath + "/image/p.gif";
	}
	
	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 "";
 	}
 	
}

//##ULg-00002-04 use controlled vocabulary mecanism for category selection
function getParentTextNode(node) {
    var childClass = node.attributes["class"].value;
	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 == childClass) {
			return child;
		}
	}
	return null;
}

function i(node,target) {
	var resultPath = "";
	var firstNode = 1;
	var pathSeparator = " => ";

    target.nextSibling.value= node.parentNode.id;    
	while(node != null) {
		if(firstNode == 1) {
			resultPath = getTextValue(node);
			firstNode = 0;
		} else {
			resultPath = getTextValue(node) + pathSeparator + resultPath;
		}
		node = getParentTextNode(node);
	}
	target.value= resultPath;
	return false;
}

function i_dc(dc){
	var n=0;
	var dcn = dc+"_"+n;
	if (document.getElementsByName(dc)[0]){dcn=dc;}//not repeatable dc   
	while (document.getElementsByName(dcn)[0]){
	  var cod = document.getElementsByName(dcn)[0].value;
	  var li = document.getElementById(cod);
	  if (li){
        var links= li.getElementsByTagName('a');
		 for(var j=0; j< links.length; j++) {
		   if(links.item(j).attributes["class"].value == categoryLocale){
		     i(links.item(j),document.getElementsByName("ui_"+dcn)[0]);
		   }
		 } 
	  }n++; dcn=dc+"_"+n; 
	}
}

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;
}*/

function chkbox(o)
{
  var p=o['parentNode'].lastChild;
  var c=o['parentNode'].getElementsByTagName("input");
  if (o.checked==true)p.value=o.value;
  else p.value="";
  for (var i=0;i<c.length;i++){
     if (c[i].getAttribute("type")=="checkbox" && c[i].value!=p.value)c[i].checked=false;
  }
}
function radio(o)
{
	
}

var bd;
function getPageScroll(){
	var y;
	if (self.pageYOffset) {
		y = self.pageYOffset;
	} else if (document.documentElement && document.documentElement.scrollTop){
		y = document.documentElement.scrollTop;
	} else if (document.body) {
		y = document.body.scrollTop;
	}
	return new Array('',y) ;
}
function getPageSize(){
	var x,y,w,h,ph,pw;
	
	if (window.innerHeight && window.scrollMaxY) {	
		x = bd.scrollWidth;y = window.innerHeight + window.scrollMaxY;
	} else if (bd.scrollHeight > bd.offsetHeight){ 
		x = bd.scrollWidth;y = bd.scrollHeight;
	} else {x = bd.offsetWidth;y = bd.offsetHeight;}
	
	if (self.innerHeight) {
		w = self.innerWidth;h = self.innerHeight;
	} else if (document.documentElement && document.documentElement.clientHeight) {
		w=document.documentElement.clientWidth;h=document.documentElement.clientHeight;
	} else if (bd) {
		w=bd.clientWidth;h=bd.clientHeight;}
	
	if(y<h)ph=h; else ph=y;
	if(x<w)pw=w; else pw=x;
	return new Array(pw,ph,w,h);
}
function findPos(obj) {
  var curleft = obj.offsetLeft || 0;
  var curtop = obj.offsetTop || 0;
  while (obj = obj.offsetParent) {
    curleft += obj.offsetLeft
    curtop += obj.offsetTop
  }
return {x:curleft,y:curtop};
}
function showBox(typ,o,ti,ch){
  if(!bd)bd=document.getElementsByTagName("body")[0];
  var bx=document.getElementById(typ);
  var cont=document.getElementById(typ + "_container");
  var tit=document.getElementById(typ + "_title");
  var ps=getPageSize();
  var p=getPageScroll();
  var bxTop=0, bxLeft=0;
  cont.innerHTML=o.innerHTML;
  bx.style.display="block";
  bxLeft=((ps[0]-600)/2);	
  var htBx=bx.clientHeight;
  var lgBx=bx.clientWidth;
  if(typ == "box") {
    hideBox('tip');
    tit.innerHTML=ti;
	var ov=document.getElementById("overlay");
	ov.style.height = (ps[1]+"px");
	ov.style.display="block";
	bxTop = p[1]+((ps[3]-htBx)/2);
	s = document.getElementsByTagName("select");
	for (var i=0; i!=s.length; i++){
	  if (s[i].className != 'box'){
	    s[i].style.visibility="hidden";}
	}
  }
  else {
	bxTop = (findPos(ch).y) - htBx;
	// Si IE, création d'une iframe pour masquer les listes
	if(nav_ie) {
	  var f=document.getElementById("layer");
	  if(!f) {
	    f=document.createElement("iframe");
	    f.setAttribute("id","layer");
	    f=document.getElementById("pagein").insertBefore(f,document.getElementById("pagein").firstChild);
		f.style.position="absolute";
		f.style.left=bxLeft - findPos(f).x -2 + "px";
		f.style.width=lgBx + "px";
		f.style.filter="alpha(opacity=0)";
	  }
	  f.style.top=bxTop - 2 + "px";
	  f.style.height=htBx  + "px";
    }
	tit.innerHTML="<h1>" + ti + "</h1><img href='javascript:void(0);' onclick=\"hideBox('tip')\" src=\"/img/box/close.png\" alt=\"\" />";
	var ct = bxTop - p[1];
	if(ct < 0) {
	  do {
	   window.scrollBy(0,-1);
	   ct++;
	  }while(ct<0)
	}
  }
  bx.style.left = (bxLeft<0)?"0px":bxLeft+"px";
  bx.style.top = (bxTop<0)?"0px":bxTop+"px";
}
function hideBox(typ){
  if(nav_ie) {
    // On vérifie qu'on est sous IE car Firefox ne supporte pas removeNode
	document.getElementById("layer").removeNode(true);
  }
  document.getElementById(typ).style.display="none";
  document.getElementById(typ + '_container').innerHTML="";
  if(typ == 'box') {
	  document.getElementById("overlay").style.display="none";
	  var s=document.getElementsByTagName("select");
	  for (i=0; i!=s.length; i++) {
		s[i].style.visibility="visible";
	  }
  }
}
function chkForm(showbox){
   var lMesg="";   
   var l_mand=/mand$/;  //mandatory fields have class ending with "mand"
   for (var i=0;i<document.getElementsByTagName("label").length;i++){
      var lLab=document.getElementsByTagName("label")[i];
      var lLab_txt=lLab.firstChild.nodeValue;
      lLab_txt=lLab_txt.substring(0, lLab_txt.lastIndexOf("*"));
      var lClass=lLab.className;
      if (lClass && l_mand.test(lClass)){
         if (lLab.getAttribute("for") ||lLab.getAttribute("htmlFor")){
            var lId=lLab.getAttribute("for");
            if (navigator.appName=="Microsoft Internet Explorer"){lId=lLab.getAttribute("htmlFor");}
            var field=document.getElementById(lId);
			if(field.tagName=="INPUT" && (field.getAttribute("type")=="text" || field.getAttribute("type")=="hidden" || field.getAttribute("type")=="file")){
               if (field.value==""){lMesg=lMesg+"<li>"+lLab_txt+"</li>";x2("empty",field,true);
			   	field.onblur=function(){if(this.value!="") x2("empty",this)}
			   }
            } else if (field.tagName=="TEXTAREA" && field.value==""){
			   lMesg=lMesg+"<li>"+lLab_txt+"</li>";x2("empty",field,true); field.onblur=function(){ if(this.value!="") x2("empty",this)}
            } else if (field.tagName=="SELECT" && field.value==""){
			   lMesg=lMesg+"<li>"+lLab_txt+"</li>";x2("empty",field,true); field.onblur=function(){ if(this.value!="") x2("empty",this)} 
            } else if (field.tagName=="DIV"){
               if (field.getElementsByTagName("input")[0]){
                 var lChild = field.getElementsByTagName("input");
				 if (lChild[0].getAttribute("type")=="radio" || lChild[0].getAttribute("type")=="checkbox"){
                    var lSel=0; var type=lChild[0].getAttribute("type");
                    for (var j=0;j<lChild.length;j++){
                       if (lChild[j].getAttribute("type")==type && lChild[j].checked==true){lSel=1;break;}
                    } if (lSel==0){lMesg=lMesg+"<li>"+lLab_txt+"</li>"; 
						x2("empty",field,true); 
						for (var j=0;j<lChild.length;j++){ 
							if(lChild[j].getAttribute("type")=="radio" || lChild[j].getAttribute("type")=="checkbox") {
								lChild[j].onclick=function(){ x2("empty",this["parentNode"])}
							}
						}
					 }
				  }
               }
            } 
         }
      } 
   }
   if (lMesg != ""){
      lMesg="<div><br/><br/><img src=\"/img/com/warn.gif\" alt=\"\"><br />Certains champs importants ne sont pas remplis :<br /><br /><ul>"+lMesg+"</ul><br />";
      lMesg=lMesg+"<input type=\"submit\" value=\"Suivant >\" onclick=\"hideBox('box');\" />";
      lMesg=lMesg+"&nbsp;<input type=\"submit\" value=\"Remplir maintenant\" onclick=\"hideBox('box');\" /><br/><br/><br/></div>";
      var o=document.createElement('div');
      o.innerHTML=lMesg;
      if(showbox)showBox("box",o,"Attention");
      return false;
   } else return true;
}

function fopen(url){
	var popupwin = window.open(url,'dspacepopup','height=600,width=750,resizable,scrollbars');
	popupwin.focus();
	return false;
}

var current = 1;
function paginate(pg,action){
	x2("selected",document.getElementById("p"+current));
	if(pg)current=pg;
	if(action){
		if(action=="n")(current<3)?current++:current=3;
		else if(action=="p")(current>1)?current--:current=1;
	}
	for(i=1;i<4;i++){
		var el=document.getElementById("v"+i);
		if(i==current)el.style.display = "block";
		else el.style.display = "none";
	}
	x2("selected",document.getElementById("p"+current),true);
}
