/*
	Name:		UOttawaDspace.js
	Author:		Mike Cockburn
	Purpose: 	holds js customizations particular to the uO library DSpace implimentation
	Date:		19-mar-09 (start)	
*/

/*----------------------- begin functions added by Mike Cockburn - Mar 2009 --------------------- */

var bIsHomePage = false;  /* see also bDetectHomePage() */
/*
* This is called when each page loads. The reference is provided in the body tag defined in structural.xsl
*/
function bodyOnLoad()
{
	//alert("UOttawaDspace.js/BodyOnLoad()");

	/* empty DIV issue
	* these DIV are loaded with dummy text, which is now removed
	* .textContent - firefox
	* .innerText - IE6
	*
	* having problems with empty DIV tags on certain browsers,
	* try putting content into the div then removing it after loaded
	document.getElementById("page-tools").style.visibility = "visible";
	document.getElementById("page-tools").style.display = "inline";
	document.getElementById("page-tools").innerText = "";
	document.getElementById("page-tools").textContent = "";
	document.getElementById("dynamic").style.visibility = "visible";
	document.getElementById("dynamic").innerText = "";
	document.getElementById("dynamic").textContent = "";
	document.getElementById("banner-link").innerText = "";
	*/
	/* addPageToolsDiv(); */
	/* addDynamicDiv();  */

	//alert("UOttawaDspace.js/BodyOnLoad()/initFontResizeTool(before)");
	//initFontResizeTool(); // uO ../js/resize-tool.js
	//initFontResizeTool1(); // below for testing
	//createFontResizeTool(); // uO ../js/resize-tool.js
	//alert("UOttawaDspace.js/BodyOnLoad()/initFontResizeTool(after)");
	
	detectLanguage(); /* detect current language from url and save the result in a var */
	
	/* 
	* These functions relate to bilingualization of the document submission workflow
	* Skip these functions if we are not within the workflow
	*/
	if (document.getElementById("aspect_submission_StepTransformer_list_submit-progress")!=null)
	{
		disableLanguageSelection(); /* cannot change during submission */
		switch(strSavedCurrentLang){
			case "fr":
				translateNewSubmission_Details_FieldLabels_fr();
				translateNewSubmission_VerificationPage_FieldLabels_fr();
				//translateNewSubmissionFieldLabels_fr();
				translateNewSubmissionFieldHelp_fr();
				translateNewSubmissionButtons_fr();
				translateMonthNames_fr();
				renameTwoDescribeButtons_fr();
				break;
			case "en":
				renameTwoDescribeButtons_en();
				break;
			default:
				alert('UOttawaDspace.js/bodyOnLoad - strSavedCurrentLang incorrect: ' + strSavedCurrentLang);
				break;
		}
	}
	
	/*
	* A few special things are done only when we are on the homepage (english or french)
	*/
	bDetectHomePage();
	if (bIsHomePage) {
		forHomePageOnly();
	}
	
	/*
	* for the static pages added to the application, we parse the url, determine the static document required, 
	* 	request it ajax style, then replace the body of the page with the retrieved document.
	*/
	detectStaticAjaxRequest();
	
	moveCommunityElements();
}

/* 
* Detect if current language is english or french.
* Save result in javascript variable strSavedCurrentLang as "en" or "fr".
* Other language related code: changeLang()
*/
var strSavedCurrentLang="fr";
function detectLanguage()
{
	strSavedCurrentLang="fr";
	if (location.href.indexOf("/en/") > 0) strSavedCurrentLang = "en";
	//alert("UOttawaDspace.js/detectLanguage()/strSavedCurrentLang=" + strSavedCurrentLang);
}

/*
*
*/
function addPageToolsDiv(){
	var objNewDiv = document.createElement('div');
	objNewDiv.id = "page-tools";
	var objParentDiv = document.getElementById("ds-user-box");
	objParentDiv.appendChild(objNewDiv);
}
function addDynamicDiv(){
	var objNewDiv = document.createElement('div');
	objNewDiv.id = "dynamic";
	var objParentDiv = document.getElementById("ds-header");
	objParentDiv.appendChild(objNewDiv);
}

String.prototype.trim = function() {
	return this.replace(/^\s+|\s+$/g,"");
}

/*
* interchanges the position of two sibling elements with the parent element
*/
function swapElements(parentElement, item1, item2)
{
	parentElement.insertBefore(item1, item2);
}

/* This is just for the community page for 'thesis' where the text needs to be moved around */
function moveCommunityElements()
{
	var objTargetParent = document.getElementById("aspect_artifactbrowser_CommunityViewer_div_community-home");
	if (objTargetParent != null) {
		/* this one contains the two items of interest */
		var objSourceParent = getElementsByClassName("detail-view", objTargetParent)[0];
		/* add a dummy child, sometimes IE nests incorrectly with empty DIV */
		var newdiv = document.createElement('div');
		newdiv.innerHTML="Replacement child";
		objSourceParent.appendChild(newdiv);
		
		try {
			/* this one may not exist in some communities, so we have the try block around */
			var objDetailViewNews = getElementsByClassName("detail-view-news", objTargetParent)[0];
			var objIntroText = getElementsByClassName("intro-text", objTargetParent)[0];

			/* with IE this is a problem, it loads after the right side stuff */
			objTargetParent.appendChild(objDetailViewNews);

			/* move to start */
			objTargetParent.insertBefore(objIntroText,objTargetParent.firstChild); 
		} /* end try block */
		catch(err)
		{}                
                
                /* get rid of the old parent, no longer used */
                objSourceParent.parentNode.removeChild(objSourceParent);
	}
}

function insertAfter( referenceNode, newNode )
{
    referenceNode.parentNode.insertBefore( newNode, referenceNode.nextSibling );
}

/*
* finds all child elements of 'obj' which match the given class name
*/
function getElementsByClassName( strClassName, obj ) {
    var ar = arguments[2] || new Array();
    var re = new RegExp("\\b" + strClassName + "\\b", "g");

    if ( re.test(obj.className) ) {
        ar.push( obj );
    }
    for ( var i = 0; i < obj.childNodes.length; i++ )
        getElementsByClassName( strClassName, obj.childNodes[i], ar );
    
    return ar;
}
/*
* Disables a link on with the given ID.
* Link becomes gray, underline is no longer used, click does nothing
* Intended for use with <A HREF, not tested with others yet.
*/
function disableLink(strLinkID)
{
   try {
	//document.getElementById(strLinkID).style.color = "#cccccc";
	document.getElementById(strLinkID).style.color = "#ffffff";
	document.getElementById(strLinkID).style.textDecoration = "none";
	document.getElementById(strLinkID).removeAttribute("href");
	document.getElementById(strLinkID).style.background = "none"; /* hide the little arrows beside some links */
   }
   catch(err)
   {
   	//alert("UOttawaDspace.js/disableLink(" + strLinkID + ")");
   }
}
/*
* This is a real kludge, want to hide the search option on the homepage
* without changing the Java code on the server this seems to be best way 
* to find the heading and make it disappear.
* Also related to this is a spec in the UOttawaDspace.css
* form#aspect_artifactbrowser_FrontPageSearch_div_front-page-search
*/
function hideHomepageSearch()
{
        //alert("UOttawaDspace.js/hideHomepageSearch");
	var labels=[];
        labels=document.getElementsByTagName("h1");
        for(var i=0;i<labels.length;i++){
                if (labels[i].innerHTML == "Search uO Research" ) {
                	labels[i].style.display = "none";
                	//labels[i].innerHTML = "";
                }
        }
}

function disableLanguageSelection()
{
	disableLink("language-selection-button");
}

/*
* There are a few unique things done only on the homepage
* these are all done here.
*/
function forHomePageOnly()
{
	//alert("UOttawaDspace.js/forHomePageOnly()");
	/*
	* these should be off when we are on the homepage
	*/
	disableLink("banner-link");
	disableLink("home-link");
	
	/* change the style to get the alternate image */
	document.getElementById("lib-mainbanner").id = 'lib-mainbanner2';

	//alert(document.getElementById("lib-mainbanner2").id);
	
	/* hide the search box in the body of the homepage */
	//hideHomepageSearch();
	
	/*
	* swap around contents of the search area
	*/
	var searchForm = document.getElementById("aspect_artifactbrowser_FrontPageSearch_div_front-page-search");
	var listitems= searchForm.getElementsByTagName("p")
	swapElements(searchForm, listitems[1],listitems[0]);
	
	/*
	* make generated d-space content in middle of page narrower to accomodate the graphics on the right side
	*/
	document.getElementById("uO-Generated-Content").setAttribute('class','uO-Generated-Content-homepage');
}
/*
* Detects if this is the home page
* Uses the length base URL of the form https://www.ruor.uottawa.ca as a basis to compare with the length of the current url
* If the current URL is more that 5 characters (eg. /en/) longer then we are no longer on the homepage
* Sets the JavaScript var bIsHomePage true for home
*/
function bDetectHomePage()
{
	//alert("UOttawaDspace.js/bDetectHomePage()");
	var curUrl=(location.href);
	var iBaseUrlLen = location.protocol.length + location.host.length + 2;
	//alert(location.protocol + "//" + location.host);
	//alert(curUrl.length - iBaseUrlLen);
	if ((curUrl.length - iBaseUrlLen) < 5) {
		bIsHomePage = true;
	}
	//alert("bDetectHomePage: " + bIsHomePage + ", curUrl=" + curUrl + ", substr=" + curUrl.substr(-1));
}

/*----------------------- end functions added by Mike Cockburn - Mar 2009 --------------------- */


/* ------------------------ removed from structural.xsl --------------- */

//Disable pressing 'enter' key to submit a form (otherwise pressing 'enter' causes a submission to start over)
function disableEnterKey(e)
{
     var key;

     if(window.event)
          key = window.event.keyCode;     //Internet Explorer
     else
          key = e.which;     //Firefox and Netscape

     if(key == 13)  //if "Enter" pressed, then disable!
          return false;
     else
          return true;
}

/*
Language management, no longer used
*/
function manageSession(){
	var nameEQ="JSESSIONID=";
	var sessionID=0;

	var ca=document.cookie.split(';');
	for(var i=0; i<ca.length;i++){
		var c=ca[i];
		while(c.charAt(0)==' ') c=c.substring(1,c.length);
		if(c.indexOf(nameEQ==0)) sessionID=c.substring(nameEQ.length,c.length);
	}

	if(sessionID==0){
		nameEQ="/fr/JSESSIONID=";
		var ca=document.cookie.split(';');
		for(var i=0;i<ca.length;i++){
			var c=ca[i];
			while(c.charAt(0)==' ') c=c.substring(1,c.length);
			if(c.indexOf(nameEQ==0)) sessionID=c.substring(nameEQ.length,c.length);
		}
	}

	if(sessionID!=0){
		document.cookie="JSESSIONID="+sessionID+""+"; path=/";
		document.cookie="JSESSIONID="+sessionID+""+"; path=/en";
		document.cookie="JSESSIONID="+sessionID+""+"; path=/fr";
	}
}

/*
* Jumps to other language
* NOTE: a cookie stores JSESSIONID which is different for english and french
*/
function changeLang(lang){
	switch(lang){
		case "fr":
			//document.forms['repost']['locale-attribute'] = 'fr';
		        //document.repost.locale.value='fr';
                        //document.repost.submit();
			location.href=location.href.replace("/en/", "/fr/");
			break;
		case "en":
		        //document.repost.locale.value='en';
                        //document.repost.submit(); 
                        // repost must be the name of a form
			location.href=location.href.replace("/fr/", "/en/");
			break;
		default:
			alert("UOttawaDspace.js/changeLang - invalid language selector: " + lang);
			break;
	}
}

/*----------------------- begin functions added by Mike Cockburn - AJAX - Apr 2009 --------------------- */

/*
* This function needs to detect if the url is a request for one of the static pages
* It looks for the static/ in the current URL to decide.
* If so then the static page is fetched using ajax(XMLHttpRequest).
* The static page is then subsituted into the page at the div#main-content element
*/
function detectStaticAjaxRequest() {
	var curUrl=(location.href);
	var iPointer = curUrl.indexOf('static/');
	if (iPointer > 0 ) {
		var strRequested = curUrl.substring(iPointer+7,999);
		//alert(strRequested);
		//https://www.ruor.uottawa.ca/en/static/BenefitsOfUOResearch.htm
		strRequested = 'http://www.ruor.uottawa.ca/' + strSavedCurrentLang + '/themes/Classic/uO/help/' + strRequested
		loadXMLDoc(strRequested);
		// 20090416 loadXMLDoc('https://www.ruor.uottawa.ca/en/themes/Classic/uO/help/' + strRequested);
		//loadXMLDoc('https://www.ruor.uottawa.ca/en/themes/Classic/uO/help/About_UOResearch1.htm');
	}
}

var xmlhttp;
var strReqUrl;
function loadXMLDoc(url)
{
	//alert('UOttawaDspace.js/loadXMLDoc:' + url);
	xmlhttp=null;
	strReqUrl = url;
	if (window.XMLHttpRequest)
	  {// code for IE7, Firefox, Opera, etc.
	  xmlhttp=new XMLHttpRequest();
	  }
	else if (window.ActiveXObject)
	  {// code for IE6, IE5
	  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
	  }
	if (xmlhttp!=null)
	  {
	//alert('have - xmlhttp');
	  document.getElementById('main-content').innerHTML = ""; /* hide junk while we fetch content */
	  xmlhttp.onreadystatechange=state_Change;
	  xmlhttp.open("GET",url,true);
	  xmlhttp.send(null);
	  }
	else
	  {
	  alert("UOttawaDspace.js/loadXMLDoc - Your browser does not support XMLHTTP - cannot load page content.");
	  }
	//alert('UOttawaDspace.js/loadXMLDoc - writting from - xmlhttp');
}

function state_Change()
{
if (xmlhttp.readyState==4)
  {// 4 = "loaded"
  if (xmlhttp.status==200)
    {// 200 = "OK"
    //document.getElementById('A1').innerHTML=xmlhttp.status;
    //document.getElementById('A2').innerHTML=xmlhttp.statusText;
    //document.getElementById('A3').innerHTML=xmlhttp.responseText;
    
    var newdiv = document.createElement('div');
    newdiv.setAttribute('class','uOStatic');
    newdiv.innerHTML=xmlhttp.responseText;
    
    document.getElementById('main-content').innerHTML=""; /* remove old stuff */
    document.getElementById('main-content').appendChild(newdiv);
    //document.getElementById('main-content').innerHTML=xmlhttp.responseText;
    
    document.title=strReqUrl; /* clear out garbage title */
    }
  else
    {
    /* put message into body */
    document.getElementById('main-content').innerHTML="<b>ERROR</b> in UOttawaDspace.js/state_Change()<br/><br/><h2>Problem retrieving page content</h2><br/>" + strReqUrl + "<br/><br/>"+ xmlhttp.statusText;
    }
  }
}
/*----------------------- end functions added by Mike Cockburn - AJAX - Apr 2009 --------------------- */
function createFontResizeTool1(arrChoices) {
	
	/* exit if page tools element not found or if resize tool exists */
	if (!document.getElementById(idList.pageTools)) return false;
	
	/* exit if tool already exists */
	if (document.getElementById(idList.resizeTool)) return document.getElementById(idList.resizeTool);
	
	/* create basic elements */
	var objResizeTool = document.createElement('div');
	//objResizeTool.textContent = "mike";
	var objResizeToolLabel = document.createElement('label');
	var objResizeToolChoiceList = document.createElement('ul');
	objResizeTool.id = idList.resizeTool;
	objResizeToolLabel.id = idList.resizeToolLabel;
	/* assemble the parts */
	objResizeTool.appendChild(objResizeToolLabel);
	objResizeTool.appendChild(objResizeToolChoiceList);
	/* add the choices */
	for (var i=0; i < arrChoices.length; i++) {
		objResizeToolChoiceList.appendChild(createResizeChoice(arrChoices[i]));
	}
	
	/* insert resize tool in DOM */
	document.getElementById(idList.pageTools).appendChild(objResizeTool);
	
	return objResizeTool;
}

function initFontResizeTool1 () {
	var arrChoices = [idList.resizeOptionSmall, idList.resizeOptionMedium, idList.resizeOptionLarge];
	var strDefaultPreference = arrChoices[0];
	var arrResizePageRegions = [idList.mainContainer, idList.mainContent, idList.sectionDetails, idList.secondaryContent, idList.siteInfo, idList.lastUpdated, idList.footerContact];
	
	/* create the tool's html scaffold */
	var objResizeTool = createFontResizeTool1(arrChoices);
	
	/* exit if tool isn't present */
	if (!objResizeTool) return; // working up to here for sure
	
	/* load preference from cookie (if not set default) */
	var cookie = readCookie(idList.resizeTool); /* the cookie is named after the resize tool's id */
	var strPreference = cookie ? cookie : strDefaultPreference;
	switchFontSize(strPreference, arrChoices, arrResizePageRegions);

	/* hook up event handling */

	addEvent(objResizeTool,'mouseover',function() { cssjs('add',this,cssClasses.over); } );
	addEvent(objResizeTool,'mouseout',function() { cssjs('remove',this,cssClasses.over); } );
	
	for (var i=0; i < arrChoices.length; i++) {
		addEvent(document.getElementById(arrChoices[i]),'click',function() { 
			switchFontSize(this.id, arrChoices, arrResizePageRegions); 
		} );
		addEvent(document.getElementById(arrChoices[i]),'mouseover',function() { cssjs('add',this,cssClasses.over); } );
		addEvent(document.getElementById(arrChoices[i]),'mouseout',function() { cssjs('remove',this,cssClasses.over); } );
	}
}
