// from http://www.tek-tips.com/faqs.cfm?fid=4862
function addOnLoadHandler(myHandler) {
  if ( typeof window.addEventListener != "undefined" )
      window.addEventListener( "load", myHandler, false );
  else if ( typeof window.attachEvent != "undefined" )
      window.attachEvent( "onload", myHandler );
  else {
      if ( window.onload != null ) {
          var oldOnload = window.onload;
          window.onload = function ( e ) {
              oldOnload( e );
              myHandler();
          };
      }
      else
          window.onload = myHandler;
  }
}

/**
 * A function that should be in the DOM, but is not.  Create an element in script and insert it after an existing element.
 * @param {Object} parent - parent of the node you want to insert and the reference node you want to insert it after
 * @param {Object} node - the element you want to insert
 * @param {Object} referenceNode - the existing element you want to insert your newly created node after.
 */
function insertAfter(parent, node, referenceNode) {
	parent.insertBefore(node, referenceNode.nextSibling);
}

function showHide(id){
  if (document.getElementById){
    var obj = document.getElementById(id);
    if (obj.style.display == "none"){
      obj.style.display = "";
    } else {
      obj.style.display = "none";
    }
  }
}

function showHide_reply(id, titleID, postText){
  if (document.getElementById){
    var obj = document.getElementById(id);
		var title = document.getElementById(titleID);	
    if (obj.style.display == "none"){
      obj.style.display = "block";		
			if(title.value == ''){
				title.value = postText;
			}
    } else {
      obj.style.display = "none";
    }
  }
}

function displayById(id) {
  if (document.getElementById){
    var obj = document.getElementById(id);
    if (obj == null) return;
    obj.style.display = "";
  }
}

function hideById(id) {
  if (document.getElementById){
    var obj = document.getElementById(id);
    if (obj == null) return;
    obj.style.display = "none";
  }
}

function showHideBC(imageID){
	if(imageID == 'bcExpand'){
		document.getElementById('bcCollapse').style.display = "";
		document.getElementById('bcExpand').style.display = "none";
		document.getElementById('bcAdditional').style.display = "";
	}else{
		document.getElementById('bcCollapse').style.display = "none";
		document.getElementById('bcExpand').style.display = "";
		document.getElementById('bcAdditional').style.display = "none";
	}
}

function showDiv(pass) {
  var divs = document.getElementsByTagName('div');
  //alert("divs = " + divs.length);
  for (i=0; i<divs.length; i++) {
    //if (divs[i].id.match(pass)) {
    if (divs[i].id.indexOf(pass, 0) != -1) {
      if (document.getElementById) {
	if (divs[i].style.display == "none"){
	  divs[i].style.display = "";
	} else {
	  divs[i].style.display = "none";
	}
      }
    }
  }
}

function showSpan(pass) {
  var spans = document.getElementsByTagName('span');
  //alert("spans = " + spans.length);
  for (i=0; i<spans.length; i++) {
    if (spans[i].id.indexOf(pass, 0) != -1) {
      if (document.getElementById) {
	if (spans[i].style.display == "none"){
	  spans[i].style.display = "";
	} else {
	  spans[i].style.display = "none";
	}
      }
    }
  }
}

function displayRenditions(button, rowClass){
	var clickedButton = document.getElementById(button);
	var showButton = document.getElementById('btn_showRenditions');
	var hideButton = document.getElementById('btn_hideRenditions');
	var rows = document.getElementsByTagName('tr');
	var visibility = null;
	
	//find all rendition rows and show or hide...
	for (i=0; i<rows.length; i++){
		if(rows[i].className == 'ht_rendition_row'){
			//hide or show depending on what button got clicked...	
			if(clickedButton == showButton){
				rows[i].style.display = "";
				showButton.style.display = "none";
				hideButton.style.display = "";
			}else if(clickedButton == hideButton){
				rows[i].style.display = "none";
				showButton.style.display = "";
				hideButton.style.display = "none";
			}
		}
	}
}

function showSearchOptions(optionregion){
  expandarrow = document.getElementById('searchOptionsShow');
  collapsearrow = document.getElementById('searchOptionsHide');
  hiddenoptiondiv = document.getElementById(optionregion);
  if(hiddenoptiondiv.style.display == "none"){
    hiddenoptiondiv.style.display = "";
    expandarrow.style.display = "none";
    collapsearrow.style.display = "";
  } else {
    hiddenoptiondiv.style.display = "none"
      expandarrow.style.display = "";
    collapsearrow.style.display = "none";
  }
}

function showOptions(optionregion, show, hide){
  expandarrow = document.getElementById(show);
  collapsearrow = document.getElementById(hide);
  hiddenoptiondiv = document.getElementById(optionregion);
  if(hiddenoptiondiv.style.display == "none"){
    hiddenoptiondiv.style.display = "";
    expandarrow.style.display = "none";
    collapsearrow.style.display = "";
  } else {
    hiddenoptiondiv.style.display = "none"
      expandarrow.style.display = "";
    collapsearrow.style.display = "none";
  }
}

function openUrlTextWindow(url) {
  if (typeof(popupWin) != "object"){
    popupWin = window.open(url, "urlWindow", "toolbar=yes,location=yes,directories=yes,status=yes,menubar=yes,scrollbars=yes,resizable=yes");
  } else {
    if (!popupWin.closed){
      popupWin.location.href = url;
    } else {
      popupWin = window.open(url, "urlWindow", "toolbar=yes,location=yes,directories=yes,status=yes,menubar=yes,scrollbars=yes,resizable=yes");
    }
  }
  popupWin.focus();
}


function openHelpTextWindow(url) {
  var attributes = "toolbar=no,location=no,directories=no,status=yes,menubar=no,scrollbars=yes,copyhistory=no,resizable=yes,width=350,height=250";
  var win = window.open(url, "dshelpwindow", attributes);
  win.onClose = window.focus();
  win.focus();
}

// Idea from http://domscripting.com/presentations/xtech2006/ by Jeremy Keith // Fix to IE bug with getAttribute described at http://www.glennjones.net/Post/809/getAttributehrefbug.htm
// Opera 9 and greater appear not to have this problem.
// IE reportedly offers a workaround 2-arg version of getAttribute, where the second arg of 2 means to // do what the DOM Level 2 spec says to do, and what Opera and Firefox do already.
function doLabelHelpLinks() {
  if (document.getElementsByTagName) {
    var links = document.getElementsByTagName("a");
    for (var i=0; i < links.length; i++) {
      if (links[i].className.match("labelHelpLink") || links[i].className.match("xforms-minimal-help-link")) {
        links[i].onclick = function() {
          var url = null;
          try {
            url = this.getAttribute("href", 2);
          } catch (e) {
            url = this.getAttribute("href");
          } 
          openHelpTextWindow(url);
          return false;
        };
      }
    }
  }
} 

//Global variable since addOnLoadHandler also defined and used in js_functions.js
//Check this flag to see if addOnLoadHandler already loaded
if(typeof(addonloadhandler_global_flag) == "undefined") { 
	addonloadhandler_global_flag = 1;
	addOnLoadHandler(doLabelHelpLinks);
}

function clearSelect(item) {
	var n;
	var i;
	n = item.length;
	for (i=0; i < n ; i++) {
		item.options[i].selected = false;
	}
}

function setSelect(item, optionValue) {
	var n;
	var i;
	n = item.length;
	for (i=0; i < n ; i++) {
		if (item.options[i].value == optionValue) item.options[i].selected = true;
	}
}


function SearchFormSetSelect(item) {
	if (item.form.object_type_enable[1].checked == false) {
		item.form.object_type_enable[1].checked = true;
		item.form.object_type_enable[1].click();	
		item.checked = true;
	}
}

function SearchFormSelectAll(item,sel) {
	var n;
	var i;
	n = item.form.object_type.length;
	for (i=0; i < n ; i++) {
		if (item.form.object_type[i].type=='checkbox') {                            
			if (sel == true) {
				item.form.object_type[i].checked = true;
			}

			if (sel == false) {
				item.form.object_type[i].checked = false;
			}
		}
	}
}

function SearchFormSetSelectMime(item) {
	if (item.form.document_type_enable[1].checked == false) {
		item.form.document_type_enable[1].checked = true;
		item.form.document_type_enable[1].click();	
		item.checked = true;
	}
}

function SearchFormSelectAllMime(item,sel) {
	var n;
	var i;
	n = item.form.document_type.length;
	for (i=0; i < n ; i++) {
		if (item.form.document_type[i].type=='checkbox') {                            
			if (sel == true) {
				item.form.document_type[i].checked = true;
			}

			if (sel == false) {
				item.form.document_type[i].checked = false;
			}
		}
	}
}

/**
 * This javascript function shows or hides additional search scope features depending on what 
 * was selected in the "search within" textbox.  The 'item' parameter is the select option value selected.
 * @param {Object} item
 */
function SearchFormSetScope(item) {
	var federated = (document.getElementById('fed_scope'))? true : false; //does a federation exist?
	var col_scope = document.getElementById('col_scope'); // items displayed if searching inside a collection
	var site_scope = document.getElementById('site_scope'); // items displayed if an archive server is present
	var fed_scope = document.getElementById('fed_scope'); // items displayed if the server is in a federation
	
	if(item.value == 'Collection' || item.value == 'Collection+') {
	  if(document.getElementById){
			col_scope.style.display = "";
			if(federated == true){fed_scope.style.display = "none";}
			site_scope.style.display = "";			
	  }
	}
	else if(item.value == 'Space'){
	  if(document.getElementById){
			col_scope.style.display = "none";
			if(federated == true){fed_scope.style.display = "none";}
			site_scope.style.display = "";
	  }
	}
	else if(item.value == 'Site'){
	  if(document.getElementById){
			col_scope.style.display = "none";
			if(federated == true){fed_scope.style.display = "none";}
			site_scope.style.display = "";			
	  }
	}
	else if(item.value == 'AllFederated' || item.value == 'SelectFederated'){
	  if(document.getElementById){
	    col_scope.style.display = "none";
			if(federated == true){fed_scope.style.display = "";}
			site_scope.style.display = "none";
	  }
	  
		var sel = (item.value == 'AllFederated')? true : false;
	  var n;
	  var i;
	  n = item.form.fed_name.length;
	  for (i=0; i < n ; i++){
			if(item.form.fed_name[i].type=='checkbox'){                            
				if(sel == true) {
					item.form.fed_name[i].checked = true;
				}	
				if(sel == false){
					item.form.fed_name[i].checked = false;
				}
			}
	  }
	}
	else {
	  if(document.getElementById){
	    col_scope.style.display = "none";
			if(federated == true){fed_scope.style.display = "none";}
	  }
	}
}

function SearchFormSetFedNameSelect(item) {
	if (item.form.scope.value != 'SelectFederated') {
		item.form.scope.value = 'SelectFederated';
		item.form.scope.change();	
	}
}

/* The showDescription function is for the search results page to hide and show the query details */
function showDescription(optionregion){
        expandarrow = document.getElementById('descriptionShow');
        collapsearrow = document.getElementById('descriptionHide');
        hiddenoptiondiv = document.getElementById(optionregion);
        if(hiddenoptiondiv.style.display == "none"){
        	hiddenoptiondiv.style.display = "";
        	expandarrow.style.display = "none";
        	collapsearrow.style.display = "";
        } else {
        	hiddenoptiondiv.style.display = "none"
        	expandarrow.style.display = "";
        	collapsearrow.style.display = "none";
        }
}

// Show an animation when retrieving meter informtion on quota pages...
function retrieveMeters(){
	// initialize variables
	var ani_img = document.getElementById("meter_ani");
	var static_img = document.getElementById("meter_static");
	var buttoncontainer = document.getElementById("quotaLookupButton");
	var docCountMeterBarLength = null;
	var docSizeMeterBarLength = null;
	
	// display loading animation; hide button.
	ani_img.style.display = "inline";
	static_img.style.display = "none";
	buttoncontainer.style.display = "none";
}

// Load the meter bars that are generated based on quota usage data
function loadMeterBars(docCount, docQuota, docSize, docSizeQuota){
	var docCountBar = document.getElementById("docCount_value");
	var docSizeBar = document.getElementById("contentSize_value")
	var docCountSize = (docCount / docQuota) * 100;
	//var docMBSize = Math.ceil((docSize/1000000)) / docSizeQuota;
	var docMBSize = (docSize / docSizeQuota) * 100;
	docCountMeterBarLength = docCountSize + "%";
	docSizeMeterBarLength = docMBSize + "%";  //round up the the nearest whole percent
	//alert("Doc Count Width = " + docCountSize);
	//alert("Doc Size Width = " + docMBSize);
	
	// Only perform meter bar resizing if the quota values are NOT "unlimited" or "not set".
	// a -2 or -1 value these means the quota is set to "unlimited" or "not set"
	if(docQuota >= 0){
		//determine the color of the bar based on the percentage of the quota used...
		//for the docCountSize
		if(docCountSize < 49){
			docCountBar.className = 'bar_ok';
			docCountBar.style.width = docCountMeterBarLength;
		}else if(docCountSize < 85 && docCountSize > 49){
			docCountBar.className = 'bar_warning';
			docCountBar.style.width = docCountMeterBarLength;
		}else if(docCountSize <= 100 && docCountSize > 85){
			docCountBar.className = 'bar_caution';
			docCountBar.style.width = docCountMeterBarLength;
		}else if(docCountSize > 100){
			docCountBar.className = 'bar_caution'
			docCountBar.style.width = '100%';
			document.getElementById('docCount_values').className = document.getElementById('docCount_values').className + ' q_warning';
		}
	}
	
	// Only perform meter bar resizing if the quota value is NOT "unlimited" or "not set".
	// a -2 or -1 value these means the quota is set to "unlimited" or "not set"
	if(docSizeQuota >= 0){
		//determine the color of the bar based on the percentage of the quota used...
		//for the docMBSize
		if(docMBSize < 49){
			docSizeBar.className = 'bar_ok';
			docSizeBar.style.width = docSizeMeterBarLength;
		}else if(docMBSize < 85 && docMBSize > 49){
			docSizeBar.className = 'bar_warning';
			docSizeBar.style.width = docSizeMeterBarLength;
		}else if(docMBSize <= 100 && docMBSize > 85){
			docSizeBar.className = 'bar_caution';
		}else if(docMBSize > 100){
			docSizeBar.className = 'bar_caution';
			document.getElementById('contentSize_values').className = document.getElementById('contentSize_values').className + ' q_warning';
			
		}
	}
}
// on the user meters page, reload the meters (after they've already been loaded
function reloadMeters(){
	//intialize variables
	var buttoncontainer = document.getElementById("quotaLookupButton");
	var meter1 = document.getElementById("docCount_value_cont");
	var meter2 = document.getElementById("contentSize_value_cont");
	var meterregion = document.getElementById("meterregion");
	var ani_img = document.getElementById("meter_ani");
	
	buttoncontainer.style.display = "none";
	meter1.style.display = "none";
	meter2.style.display = "none";
	meterregion.className = "";
	ani_img.style.display = "inline";
}


/**
 * Script for detecting illegal space characters (non-alphanumeric) when entering a space name on the space creation page. 
 */
function validateSpaceName(){
	var spaceNameField = document.getElementById('spaceName');
	spaceNameField.onkeyup = function(){
		var valueToCheck = document.getElementById('spaceName').value;
		var spaceNameField = document.getElementById('spaceName');
		var theParent = document.getElementById('spaceName').parentNode;
		var errorTextfromHiddenField = document.getElementById('spaceName_error').value; //pull the error string from a hidden field in the space creation form...
		var errorMessage = document.getElementById('formerror_spaceName');
		var pattern = /[^a-zA-Z0-9_-]/i; // regular expression pattern for detecting ANY non-alphanumeric characters...
		result = pattern.test(valueToCheck); // testing the pattern...
		if(result == true){
			if(!errorMessage){ // only display a new error message if one isn't already there...
				var errordisplay = document.createElement("div");
				var errorText = document.createTextNode(errorTextfromHiddenField);
				errordisplay.setAttribute("class", "formerror");
				errordisplay.setAttribute("id", "formerror_spaceName");			
				errordisplay.appendChild(errorText);
				insertAfter(theParent, errordisplay, spaceNameField);		
			}
		}else{ 
			if(errorMessage){  //if no non alphanumeric characters exist, get rid of any error message if one is present...
				theParent.removeChild(errorMessage);
			}
		} 
	};
}

/**
 * Script for disabling the "Go" button if the search box is empty for DocuShare 6.3.
 */
function disableShowAllBtnOnload(){
	//activate the event listener for the "go" button.
	document.getElementById("string_value1").onkeyup = checkLocSearchTextBox;
	//on page load, look to see if the search box is empty, if it is, hide the "go" button.
	if (document.getElementById("string_value1").value == ""){
		document.getElementById("filterbtn").disabled = true;
	}else{
		document.getElementById("filterbtn").disabled = false;
	}
}

function checkLocSearchTextBox(){
	var txtbox = document.getElementById("string_value1");
	var btn = document.getElementById("filterbtn");
	if(txtbox.value == "" || txtbox.value == "*"){
		btn.disabled = true;
	}else{
		btn.disabled = false;
	}
}


//adding a whitespace trim method to the built-in String object.
String.prototype.trim = function () {
    return this.replace(/^\s*/, "").replace(/\s*$/, "");
}

