/**
*Converts text to html.
**/
function convertTextToHTML(s) {
	s = s.replace(/\n/g, "<br>").replace(/  /g, "&nbsp; ");
	return s;
}

/**
*Converts html to text.
**/
function convertHtmlToText(s) {
	s = s.replace(/<br>/g, "\n" ).replace(/&nbsp/g, " ");
	return s;
}

/**
*This function returns the object whose id matches the string parameter being passed.
**/
function getElement(elementId){
    if (document.getElementById)
    {
        return document.getElementById(elementId);
    }
    else if (document.all)
    {
        return document.all[elementId];
    }
    else if (document.layers)
    {
        return document.layers[elementId];
    }
}

/**
*This function returns "selected" if the dropdown value matches the selected value during the last session which is the second parameter xmlVal
**/
function isSelected(dropDownVal, xmlVal){
    if(dropDownVal == xmlVal){
        return "selected";
    }
    return "";
}

/**
*Returns the string value in the node. If there is an error it returns an empty string.
**/
function getString(node, num){
	try{                
		return node.childNodes[getIndex(num)].firstChild.nodeValue;
	}catch(e){
		return "";
	}
}

/**
*Returns the numeric value in the node. If there is an error it returns 0.
**/
function getNum(node, num){
	try{
		return parseInt(node.childNodes[getIndex(num)].firstChild.nodeValue);
	}catch(e){
		return 0;
	}
}

/**
*Returns the value for the node which stores the "Yes" "No" value.
**/
function getYesNo(node, num){
	try{
		return node.childNodes[getIndex(num)].firstChild.nodeValue;
	}catch(e){
		return "No";
	}
}


/**
*Returns the value for the node which stores the Text value.
**/
function getText(node){
        try{
            if(navigator.appName=="Microsoft Internet Explorer"){
                return node.text;
            }else{
                return node.textContent;
            }   
            
            // This ine works for Firefox and Netscape 
            if(node.textContent) { return node.textContent; }
            
            // This one is for IE
            if (node.text) { return node.text; }
        }catch(e){
             return "";
        }
}


/**
*Returns "checked" if the radioval is same as the value passed in the parameter toCheck
**/
function isChecked(radioVal, toCheck){
    if(radioVal == null && toCheck == "No")
        return "checked";
    if(radioVal == toCheck) {
        return "checked";
    }else {
        return "";
    }
}

/**
*This replaces the xml representation of special characters by html version
**/
function removeAmp(s) {
	s = s.replace(/&lt;/g, "<").replace(/&gt;/g, ">").replace(/&amp;/g, "&");
	return s;
}

/**
*This removes the initial line break of a string
**/
function removeInitialLineBreak(s) {
	s = s.replace(/\n/, "");
	return s;
}

/**
*Returns a HttpRequest object.
**/
function getHttpRequest(){
	var objXmlHttp = null;
	objXmlHttp = createXMLHTTPRequest( );
	if (objXmlHttp == null)
	{
		alert('Cannot create XMLHTTP instance');
		return false;
	}
	else{
	    return objXmlHttp;
	}
}

/**
 *The function returns the index of an xml element based on the browser we are using
 **/
function getIndex(index){

	if(window.XMLHttpRequest){
                	if(navigator.appName=="Microsoft Internet Explorer"){
                	                return index;
                	}else{
                		index = 2*index+1;
                		return index;
                	}	
	}
	else{
		return index;
	}
}

/**
 *The function returns column id based on the column number.
 *@param colVal the column number.
 **/
function getCol(colVal){
	if(colVal == "2"){
	    return SECONDCOLUMN
	} else if(colVal == "3"){
	    return THIRDCOLUMN
	} else{
		return FIRSTCOLUMN
	}	
}


/**
*Converting html to cdata for xml
**/
function normalizeContent(webnoteContent){
    webnoteContent = webnoteContent.replace(/&/g,"&amp;").replace(/\'/g,"&apos;").replace(/\"/g,"&quot;").replace(/</g, "&lt;" ).replace(/>/g, "&gt;" );
    return webnoteContent;
}

/**
*Function to replace space with plus for the query of pennTags
**/
function replaceSpaceWithPlus(searchString){
     searchString = searchString.replace(/ /g,"+");
    return searchString;
}

/********************Function to trim String**************************/
function trimString(sInString) {
  sInString = sInString.replace( /^\s+/g, "" );// strip leading
  return sInString.replace( /\s+$/g, "" );// strip trailing
}

/**
 * The divid and the num of the div in which the waiting image has to be shown.
 *
 **/
function dispImgWait(type, numcount){
	getElement('annotationtext'+type+numcount).innerHTML ="<img class='throbber' src='"+source+"images/firefox-red.gif' />";
}

/**
 *This function computes which column should the new element be added to.
 *
 **/
function getDiv(){        
	var divtoadd;
	divtoadd = FIRSTCOLUMN;
	total_cnt++;
	return divtoadd;
}



function removeWindow(id)
{
    if(confirm("Do you really want to remove this tool?")){ 
        var newElem = getElement(id);
        var parent = newElem.parentNode;
        parent.removeChild(newElem);
	startDrag();
    }
}


/********************Function to change title*************************/
function changeTitle(callnum, num)
{
	/*The switch case is to change the value of two variables based on which
		element is calling the function.*/
	switch (callnum){
		case PENNTAGS:
			elemtype=PENNTAGSTEXT;
			titletext="PennTags";
			break;
		case WEBNOTE:
			elemtype=WEBNOTETEXT;
			titletext="Webnote";
			break;
		case RSSFEEDS:
			elemtype=RSSFEEDSTEXT;
			titletext="RSS Feeds";
			break;
		case IMGTOOL:
			elemtype=IMGTOOLTEXT;
			titletext="Image/Highlight Tool";
			break;
		case LIBDETAILS:
			elemtype =LIBDETAILSTEXT;
			titletext="Library Details";
			break;
		case PCERES:
			elemtype =PCERESTEXT;
			titletext="Pce Resource";
			break;
		case NAVTOOL:
			elemtype =NAVTOOLTEXT;
			titletext="Navigation Tool";
			break;
		case SEARCH:
			elemtype =SEARCHTEXT;
			titletext="Search Tool";
			break;
		case STANDALONEHEADER:
			elemtype =STANDALONEHEADERTEXT;
			titletext="Stand Alone Header";
			break;
		}
		
	if(trimString(getElement(elemtype+'_text_'+num).value)==""){
		getElement(elemtype+'_text_'+num).value=titletext;

	}

	if (elemtype == PENNTAGSTEXT || elemtype == RSSFEEDSTEXT){
		if (document.getElementsByName(elemtype+"_subheader"+num)[0].checked){
			getElement(elemtype+"_title_"+num+"_outer").className="subheadlinear";
		}else{
			getElement(elemtype+"_title_"+num+"_outer").className="colunitheader";
		}
	}

	getElement(elemtype+'_title_'+num).innerHTML=getElement(elemtype+'_text_'+num).value;		
	toggleLayer(elemtype+'_edit_title_',num);
	getElement(elemtype+'_edit_'+num).style.visibility ='hidden';

}

/***********Function for showing and hiding the edit panel************/
function toggleLayer(elem, num)
{    
    var style2 = getElement(elem+num).style;
    style2.display = style2.display? "":"block";	
}

function trim(stringVal) { 
    return stringVal.replace(/^\s+|\s+$/g, ''); 
 }
 
 function getEditablePage(){
    window.location=window.location+'?action=edit';
}

function removeChild(column){
   getElement(column).innerHTML = '';
}
 
function toggleBodyClass(){
     var temp = $('mainBody').className;
     $('mainBody').className=previousBodyClass;
     previousBodyClass= temp;
} 
 
/**
*Function to show and hide edit panel for all tools.
**/
function pt_edit_widget(elemtype, num, booledit, varvisi)
{	
	if(isdraghapp==0)
	{
		var e=getElement(elemtype+'_edit_'+num);
		if(booledit!='false')
			var ediv=getElement(elemtype+'_edit_title_'+num);
		
		if(booledit!='false' && ediv.style.display == 'block') {
			//h.innerHTML='edit';
			e.style.visibility = 'visible';
		} 
		else{
				e.style.visibility = varvisi;
		}
	}	
}

/**
*Renders the div containing the edit, delete and refresh button. 
**/
function renderEditDeleteDiv(type, count, typeconstant, feedType){
    var editDelete = '';
    var iden_feed = type + "_feed_" + count;
    iden_edit = type +"_edit_" + count
    iden_edit_titel = type+"_edit_title_";

    // div with id Exx
    editDelete = editDelete + '<div id="E' + total_cnt + '" class="editicons" onclick="openshutedit(' + total_cnt + ')" style="visibility:hidden">';
 
    //editDelete = editDelete + '<div id="'+iden_edit+'" class="editicons" style="visibility:hidden">';
    editDelete = editDelete + '<div id="'+iden_edit+'">';

    if(type!="artfinder" && type!=WEBNOTETEXT && type!= STANDALONEHEADERTEXT) {
    
        // This if is ensuring that RSSFeed button appears only for tools other than standalone header and webnotes.
        // if(type != WEBNOTETEXT && type != STANDALONEHEADERTEXT){
        if(type == RSSFEEDSTEXT || type == PENNTAGSTEXT || type == SEARCHTEXT) { 
        
            if(ISEDITABLE) {    
                editDelete = editDelete + '<a id="'+ iden_feed + '" href="" target="_blank" onclick="createRSS('+count+',\''+type+'\',\'' +  feedType + '\');"><img src="images/common/feedx.gif" alt="Get RSS" /></a>';
        
             //   editDelete = editDelete + '<a href="" onclick="processRefresh('+count+','+typeconstant+'); return false;"><img src="images/common/refresh12x9.gif" alt="refresh" /></a>';
            }else {
                editDelete = editDelete + '<a id="'+ iden_feed + '" href="" target="_blank" onclick="createRSS('+count+',\''+type+'\',\'' +  feedType + '\');"><img src="images/common/feed-icon12x12.gif" alt="Get RSS" /></a>';
            }
        }
    }

    if(ISEDITABLE) { 
        editDelete = editDelete + '<a href="" onclick=\'toggleLayer("'+iden_edit_titel+'",'+count+');return false;\'><img src="images/common/editx.gif" alt="edit" /></a>' + 
                                 '<a href="" onclick="removeWindow(\''+type+'_'+count+'\'); return false;"> <img src="images/common/deletex.gif" alt="delete" /> </a>';
                                // '<a href="" onclick="removeWindow(this.parentNode.parentNode.parentNode.parentNode); return false;"> <img src="images/common/deletex.gif" alt="delete" /> </a>';

    }
    editDelete = editDelete + '</div>';

    editDelete = editDelete + '</div>';  //div with id Exx

    return editDelete;
}

/**
*Renders the div having the arrow to collapse the widget.
**/
function renderOpenShut(titleStyle){
	var openShut = '';
//	openShut = openShut + '<div class="openshutarrow">'+ 
//                            '<img src="images/common/arrowopentags.gif" onclick="expandcollapse('+total_cnt+')" id="Z'+total_cnt+'" alt="toggle" /></div>';
        openShut = openShut + '<div id="Z'+total_cnt+'" class=\''+titleStyle+'\' onclick="openshutside('+total_cnt+')">';
	return openShut;
}

/**
*Renders the header for the widget which has the title, collapse arrow and div containing buttons for refresh, delete and edit.
**/
function optionDiv(type, count, dontknow, title, typeconstant, collapse, linear, subheader, feedType){

    var thisDiv = '';
    var titleStyle='';
    var headerStyle='';
    var renderOpenShutString = "";

    if (type == STANDALONEHEADERTEXT){
        titleStyle = "standaloneheadertitle";
        headerStyle = "standaloneheader";      
    }else {
        titleStyle = "recordDescription";         
        if (subheader == "Yes"){
            if (linear == "Yes"){
                headerStyle = "subheadlinear";
            }else{
                headerStyle = "subheadblock";
            }
        }else{
            headerStyle = "colunitheader";
        }
        renderOpenShutString = renderOpenShut(titleStyle);
    }

	thisDiv = thisDiv +'<div id=\''+ iden_title +'_outer\' class=\''+headerStyle+'\' onmouseover=\'pt_edit_widget("'+type+'",'+count+',"'+dontknow+'","visible")\' onMouseOut=\'pt_edit_widget("'+type+'",'+count+',"'+dontknow+'","hidden")\'>'+
			renderEditDeleteDiv(type, count, typeconstant, feedType)+
			renderOpenShutString +
			'<div id=\''+ iden_title +'\'>'+title+'</div>'; 

         if (renderOpenShutString != '') { thisDiv = thisDiv + '</div>'; }
         thisDiv = thisDiv + '</div>';

	return thisDiv;
}

/**
*Renders the radio button row of the edit div of a tool
**/
function renderRadioButton(type, count, value, title, radioType){
var radioId = type+"_"+radioType+count;
return	'<div class="row">'+
		'<div class="labelptradio"><label>'+title+'</label></div>'+
		'<div class="ptradio">'+
                		' <input  name="'+radioId+'" type="radio" class="noborder"  value="Yes" '+isChecked(value, "Yes")+' onblur="updateDOM(this)" />&#160;Yes &#160;&#160;'+
                		'<input name="'+radioId+'" type="radio" class="noborder" value="No" '+isChecked(value, "No")+' onblur="updateDOM(this)" />&#160;No'+
                	'</div>'+
	'</div>';
}


/**
*Renders the number of items row of the edit div of a tool
**/
function renderNoOfItems(type, count, itemCount){
var noOfItemsId = type+'_count_'+count;
return '<div class="row">'+
		'<div class="labeltoolinput"><label>No. of items: </label></div>'+
		'<div class="field"><input id="'+noOfItemsId+'" type="text" class="noOfItemsfield" value="'+itemCount+'" onblur="updateDOM(this)" /></div>'+
	'</div>'
}


/**
*Renders the title row in the edit div
**/
function renderTitleRow(type, count , title){
 var titleId = type+'_text_'+count;
 return 	' <div class="row">'+
		'<div class="labeltoolinput"><label>Title: </label></div>'+
		'<div class="field"><input id="'+titleId+'" value="'+title+'" class="longfield" type="text" onblur="updateDOM(this)" /></div>'+		
	'</div>'
}


/**
*Renders the query row in the edit div, which is used as the url input for penntags, rss, image tool.
**/
function renderQuery(type, count, text){
var idQuery = type +"_query"+ count;
return	'<div style="display:none">'+
		'<input type="text" id="'+idQuery+'" value="'+text+'" onblur="updateDOM(this)" />'+
	'</div>'
}


/**
*Renders Rss Type (in a hidden field)
**/
function renderFeedType(type, count, text){
var idFeedType = type +"_feedType"+ count;
return	'<div style="display:none">'+
		'<input type="hidden" id="'+idFeedType+'" value="'+text+'"  />'+
	'</div>'
}


function renderAnnotationDiv(type, count){
return	'<div id="annotationtext'+type+count+'"  >'+
			'<img src="http://www.library.upenn.edu/images/spacer.gif" width="1" height="1" alt="*" >'+
	'</div>'
}

/**
*This function is called when the refresh button is hit. Which in turn calls the specific function to repopulate the widget.
**/
function processRefresh(count, typeconstant){

    switch (typeconstant){
        case RSSFEEDS:
            getrssFeeds(count);
            break;
        case PENNTAGS:
            getpennTags(count);
            break;
        case IMGTOOL:
            getimgTool(count);
            break;
        case WEBNOTE:
            break;
        case LIBDETAILS:
            getLibDetails(count);
            break;
        case ARTFINDER:
            break;
        case ERESOURCE:
            getEResource(count);
            break;
        case PCERES:
            getpceRes(count);
            break;
        case NAVTOOL:
            getnavTool(count);
            break;
        case SEARCH:
            getSearch(count);
    }

}


/**
* This function changes the display style for the standAloneHeader.
**/
function changeDisplayStyle(type, count){
    var displayStyle = getElement(type+'_query'+count).value;
    var titlediv = getElement(type+'_title_'+count);
    if (displayStyle == 'pagesubtitle'){
        titlediv.className = 'pagetitle';
    }else{
        titlediv.className = 'loneheader';
    }
    
}

/**
*This function is called when the refresh button is hit. Which in turn calls the specific function to repopulate the widget.
**/
function createRSS(count, type, feedType){

    var iden_feed = type + "_feed_" + count;    
    var url = '';
 
    switch(type){
        case SEARCHTEXT:
            var searchtype = getElement(type+'_query'+count).value ;
            if (searchtype == 'empty'){
                alert('Please select a search tool.');
            }
            url = "/cocoon/librarytools/searchtool.rss?searchtool=" + searchtype;
            break;       

        case RSSFEEDSTEXT:   
            if(trim(getElement(type+'_query'+count).value) == ''){
                if (feedType == "penntags"){
                    alert('Please enter a PennTags URL.');
                }else{
                    alert('Please enter an RSS link.');
                }
                return false;
            }

            if (feedType == "penntags"){
                url = 'http://tags.library.upenn.edu/mp/tags/lookup/rss'+ (getElement(type+'_query'+count).value).substring(pennTagsURL.length);
            }else{   
                url = getElement(type+'_query'+count).value;
            }   
        break;
    }
    var elem = getElement(iden_feed)
    elem.setAttribute("href", url);
}




function openshutedit(id) { 
    var contents = document.getElementById("Y"+id); 
    var control = document.getElementById("Z"+id); 
    var editline = document.getElementById("E"+id);

    if(contents != null){
        if (contents.style.display == "none") {    
            contents.style.display = "block";  
        }
        else{
            contents.style.display = "block";
        } 	
    }
    if(control != null){
        if (control.className == "headerclosedarrow") {
            control.className = "recordDescription";
        }	
    }
}

function openshutside(id) { 
	var contents = document.getElementById("Y"+id); 
	var control = document.getElementById("Z"+id); 
	var editline = document.getElementById("E"+id);
/*
	if (contents.style.display == "none") {    
	contents.style.display = "block";  
	} 
	else if (contents.style.display == "block") {    
	contents.style.display = "none"; 
	}
	else {    
	contents.style.display = "block";
	}
*/
	if (control.className == "recordDescription") {
	control.className = "headerclosedarrow";
        contents.style.display = "none";
	}
	else if (control.className == "headerclosedarrow") {
	control.className = "recordDescription";
        contents.style.display = "block";
	}	
}

function updateDOM(inputField) {
    if (typeof inputField == "string") {
        inputField = document.getElementById(inputField);
    }

    if (inputField.type == "select-one") {
        for (var i=0; i<inputField.options.length; i++) {
            if (i == inputField.selectedIndex) {
                inputField.options[inputField.selectedIndex].setAttribute("selected","selected");
            }
        }
    } else if (inputField.type == "select-multiple") {
        for (var i=0; i<inputField.options.length; i++) {
            if (inputField.options[i].selected) {
                inputField.options[i].setAttribute("selected","selected");
            }
        }
    } else if (inputField.type == "text") {
        inputField.setAttribute("value",inputField.value);
    } else if (inputField.type == "textarea") {
        inputField.setAttribute("value",inputField.value);
    } else if (inputField.type == "checkbox") {
        if (inputField.checked) {
            inputField.setAttribute("checked","checked");
        } else {
            inputField.removeAttribute("checked");
        }
    } else if (inputField.type == "radio") {
	var radioNames = document.getElementsByName(inputField.name);
	for(var i=0; i < radioNames.length; i++) {
		if (radioNames[i].checked) {
			radioNames[i].setAttribute("checked","checked");
		} else {
			radioNames[i].removeAttribute("checked");
		}
	}
    }
}
