/**
 * This file contains the javascript method used for Tagging.
 * @author Sameer Maggon
 *
 * This file is dependent upon functions that are present in general.js
 * Currently functions that are used are 
 *  - Trim
 *
 *
 */

var globalXRBRQuery;
var bkgndColor;

function invokeUpdateTagsRow(index, encodedResourceURI, model, myTagsFacetName, myTagsFacetLabel, encodedAuthorURI, xrbrQuery, evt) {
	evt = (evt) ? evt : event;
	var charCode = (evt.charCode) ? evt.charCode :
		((evt.which) ? evt.which : evt.keyCode);
		
	if(charCode == 13 || charCode == 3) {
		updateTagsRow(index, encodedResourceURI, model, myTagsFacetName, myTagsFacetLabel, encodedAuthorURI, xrbrQuery);
	} else {
		return false;
	}

}

//TODO: This should go somewhere in AJAX javascript file
function getHTTPObject() { 
	var xmlhttp; 
	/*@cc_on 
	@if (@_jscript_version >= 5) 
		try { 
			xmlhttp = new ActiveXObject("Msxml2.XMLHTTP"); 
		} catch (e) { 
			try { 
				xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); 
			} catch (E) { 
				xmlhttp = false; 
			} 
		} 
	@else xmlhttp = false; 
	@end @*/  
	if (!xmlhttp && typeof XMLHttpRequest != 'undefined') { 
		try { 
			xmlhttp = new XMLHttpRequest(); 
		} catch (e) { 
			xmlhttp = false; 
		} 
	} 
	return xmlhttp; 
} 

/**
 * Given an index and an array of tag followed by taguri,
 * manipulate the DOM tree and insert / edit
 * appropriate facet
 */
function updateResultItemTagFacet(index, tagsAndUris, myTagsFacetName, myTagsFacetLabel) {

    var anchorElements = new Array();
    var renderedHtmlForTags = "";
    var count = 0;
    var prependString = "";
	queryString = window.location.search;
	if(queryString.length == 0) {
		prependString = "?sm=";
	} else if(queryString.length == 1 && queryString.charAt(0) == '?') {
		prependString = "sm=";
	}
    for(j=0;j<tagsAndUris.length;j+=2) {
            partialURL = prependString + "fr" + myTagsFacetName.length +  "%3B" + myTagsFacetName;
            temp = "0" + tagsAndUris[j+1];
            partialURL += temp.length + "%3B" + URLencode(temp) + tagsAndUris[j].length + "%3B" + tagsAndUris[j];
            actualURL = window.location + partialURL;
            var anchorElement = document.createElement("a");
            anchorElement.setAttribute("href", actualURL);
            var tagLabel = document.createTextNode(tagsAndUris[j]);
            anchorElement.appendChild(tagLabel);
            anchorElements[count] = anchorElement;
            count++;
            if(j == 0) {
            	renderedHtmlForTags += "<a href=\"" + actualURL + "\" >" + tagsAndUris[j] + "</a>" ;
            } else {
	            renderedHtmlForTags += ", " + "<a href=\"" + actualURL + "\" >" + tagsAndUris[j] + "</a>" ;
	        }
    }

    // Check if the TAGS element already exists
    var tagsElement = document.getElementById("tagRow_" + index);
    if(null == tagsElement && renderedHtmlForTags != "") {
            tagsElement = document.createElement("li");
            tagsElement.setAttribute("class", "resultsText");
            tagsElement.setAttribute("id", "tagRow_" + index);

            var boldHeaderElement = document.createElement("b");
            var boldHeaderElementText = document.createTextNode(myTagsFacetLabel);
            boldHeaderElement.appendChild(boldHeaderElementText);
            tagsElement.appendChild(boldHeaderElement);

            tagsElement.appendChild(document.createTextNode(": "));

            for(i=0;i<anchorElements.length;i++) {
            	if(i != 0) {
                    tagsElement.appendChild(document.createTextNode(", "));
                }
                tagsElement.appendChild(anchorElements[i]);
                
            }
            document.getElementById('resultDim_' + index).appendChild(tagsElement);
    } else {
    	if(renderedHtmlForTags != "") {
	    	tagsElement.innerHTML = "<b>" + myTagsFacetLabel + "</b>: " + renderedHtmlForTags;
	    } else {
	    	tagsElement.innerHTML = "";
	    }
    }
}
 


function handleHttpResponseForBulkTagging() {
	if (xmlHttp.readyState == 4) {	
	  // Display an informative message showing how many resources were untagged
	  var requestTypeTags = xmlHttp.responseXML.getElementsByTagName("requestType");
	  var requestType = requestTypeTags[0].firstChild.nodeValue;

	  if (requestType == "5") { // MULTI_ITEM_UNTAGGING
	    var updateCountTags = xmlHttp.responseXML.getElementsByTagName("updateCount");
	    var updateCount = updateCountTags[0].firstChild.nodeValue;
	    var updateResponseSizeTags = xmlHttp.responseXML.getElementsByTagName("updateResponseSize");
	    var updateResponseSize = updateResponseSizeTags[0].firstChild.nodeValue;
	    var requestTagTags = xmlHttp.responseXML.getElementsByTagName("requestTag");
	    var firstTag = requestTagTags[0].firstChild.nodeValue;
	    var restTagString = "";
	    for (i = 1; i < requestTagTags.length; i++) {
	      restTagString = ", " + requestTagTags[i].firstChild.nodeValue;
	    }
	    var tagString = "Tag " + firstTag;
	    if (restTagString != "") {
	      tagString = "Tags " + firstTag + restTagString;
	    }
	    if (updateCount == "0") {
	      alert(tagString + " cannot be found in the selected resources.");
	    } else {
	      alert(tagString + " removed from " + updateCount + " of " + updateResponseSize + " selected resources.");
	    }
	  }

		location.reload(true);
		return false;
/**
		var modelTags = xmlHttp.responseXML.getElementsByTagName("model");
	    var modelname = modelTags[0].firstChild.nodeValue;
		// alert("ModelName " + modelname);
	    var authoruriTags = xmlHttp.responseXML.getElementsByTagName("authoruri");
	    var encodedAuthorURI = authoruriTags[0].firstChild.nodeValue;
	
	    var myTagsFacetNames = xmlHttp.responseXML.getElementsByTagName("facetname");
	    var myTagsFacetName = myTagsFacetNames[0].firstChild.nodeValue;
//  	alert("myTagsFacetName " + myTagsFacetName);
	    var myTagsFacetLabels = xmlHttp.responseXML.getElementsByTagName("facetlabel");
	    var myTagsFacetLabel = myTagsFacetLabels[0].firstChild.nodeValue;
//    alert("myTagsFacetLabel " + myTagsFacetLabel);
	    var responseSizeTags = xmlHttp.responseXML.getElementsByTagName("responsesize");
	    var responseSize = responseSizeTags[0].firstChild.nodeValue;
		
		HideTagAllForm(responseSize, globalXRBRQuery, modelname, "", "", "", myTagsFacetName, myTagsFacetLabel, encodedAuthorURI);
*/
	}
    enableButton(document.checkboxForm.AddTag);
    enableButton(document.checkboxForm.RemoveTag);
}

function hasSpace(tagName) {
	for (i = 0; i < tagName.length; i++) {
		var currentChar = tagName.charAt(i);

		if(currentChar == ' ') {
			return true;
		}
	}
	return false;
}

function handleHttpResponse() {
  if (xmlHttp.readyState == 4) {
    var modelTags = xmlHttp.responseXML.getElementsByTagName("model");
    var modelname = modelTags[0].firstChild.nodeValue;
//    alert("ModelName " + modelname);
    var resourceURITags = xmlHttp.responseXML.getElementsByTagName("resource-uri");
    var resourceURI = resourceURITags[0].firstChild.nodeValue;
    var authoruriTags = xmlHttp.responseXML.getElementsByTagName("author-uri");
    var encodedAuthorURI = authoruriTags[0].firstChild.nodeValue;

//    alert("ResourceURI " + resourceURI);
    var indexTags = xmlHttp.responseXML.getElementsByTagName("index");
    var index = indexTags[0].firstChild.nodeValue;
//    alert("index " + index);
    var myTagsFacetNames = xmlHttp.responseXML.getElementsByTagName("facet-name");
    var myTagsFacetName = myTagsFacetNames[0].firstChild.nodeValue;
//    alert("myTagsFacetName " + myTagsFacetName);
    var myTagsFacetLabels = xmlHttp.responseXML.getElementsByTagName("facet-label");
    var myTagsFacetLabel = myTagsFacetLabels[0].firstChild.nodeValue;
//    alert("myTagsFacetLabel " + myTagsFacetLabel);


	var tagElements = xmlHttp.responseXML.getElementsByTagName("tag");
    var tagsAndUris = new Array();
    var currentTagsLabelList = "";
    var j = 0;
    // loop through <tag> elements, and create an arraylist of those
    for (var i = 0; i < tagElements.length; i++) {
//        alert(tagElements[i].firstChild.nodeValue);
        tagsAndUris[j] = tagElements[i].firstChild.nodeValue;
		var currentLabel = tagsAndUris[j];
		if (hasSpace(tagsAndUris[j])) {
	       	currentTagsLabelList += "\\\'" + tagsAndUris[j] + "\\\' ";
		}
		else
	       	currentTagsLabelList += tagsAndUris[j] + " ";
        
        j = j + 1;
	    var attrib = tagElements[i].attributes;
//        alert(attrib[0].nodeValue);
	    // Get the Tag URI
	    tagsAndUris[j] = attrib[0].nodeValue;
      	j = j + 1;
    }
    updateResultItemTagFacet(index, tagsAndUris, myTagsFacetName, myTagsFacetLabel);
    var encresURI = escape(resourceURI);
    HideTagForm(index, encresURI, modelname, currentTagsLabelList, myTagsFacetName, myTagsFacetLabel, encodedAuthorURI, globalXRBRQuery);
	Fat.fade_element("tagRow_" + index);
  }
}

function getSelectedResourceURIsAsXML() {
	var	field = document.checkboxForm.chk;
	var retStr = "";
    for (i = 0; i < field.length; i++) {
		if (field[i].checked == true) {
			retStr += "<resource-uri><![CDATA[" + field[i].value + "]]></resource-uri>";
		}
    } 
	if (retStr.length != 0) {
		retStr = "<resource-uris>" + retStr + "</resource-uris>";
	}
	return retStr;
}

function tagMultiItems(model, xrbrQuery, myTagsFacetName, myTagsFacetLabel, encodedAuthorURI) {
	var resourcesXML = getSelectedResourceURIsAsXML();;
	if (resourcesXML.length == 0) {
		alert("No selected results!");
		return;
	}
	var tagsValue = document.getElementById("bulkTagField").value; 
	tagsValue = Trim(tagsValue);

	if(tagsValue == null || tagsValue == "") {
	     	return false;
	}

	tagsValue = getValidatedTags(tagsValue);

	var strToXfer = "requestXML=<TagsRequest>";
	strToXfer += "<type>4</type>";
	strToXfer += "<response-size/>";
	strToXfer += "<soap-url>" + soapserverurl + "</soap-url>";	
	strToXfer += "<model>" + model + "</model>";
	strToXfer += "<xrbr-query><![CDATA[" + xrbrQuery + "]]></xrbr-query>";
	strToXfer += "<facet-name>" + myTagsFacetName + "</facet-name>";
	strToXfer += "<facet-label>" + myTagsFacetLabel + "</facet-label>";
	strToXfer += "<author-uri>" + encodedAuthorURI + "</author-uri>";
	strToXfer += encodeTagsAsXML(tagsValue);
	strToXfer += "<indices>";
	strToXfer += "<index/>";
	strToXfer += "</indices>";
	strToXfer += resourcesXML;
	strToXfer += "</TagsRequest>";
    
	xmlHttp.open("POST", url, true); 
	xmlHttp.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
	xmlHttp.onreadystatechange = handleHttpResponseForBulkTagging; 
	xmlHttp.send(strToXfer);
	return false;
}

function untagMultiItems(model, xrbrQuery, myTagsFacetName, myTagsFacetLabel, encodedAuthorURI) {
	var resourcesXML = getSelectedResourceURIsAsXML();;
	if (resourcesXML.length == 0) {
		alert("No selected results!");
		return;
	}
	var tagsValue = document.getElementById("bulkTagField").value; 
	tagsValue = Trim(tagsValue);

	if(tagsValue == null || tagsValue == "") {
	     	return false;
	}

	tagsValue = getValidatedTags(tagsValue);

	var strToXfer = "requestXML=<TagsRequest>";
	strToXfer += "<type>5</type>";
	strToXfer += "<response-size/>";
	strToXfer += "<soap-url>" + soapserverurl + "</soap-url>";	
	strToXfer += "<model>" + model + "</model>";
	strToXfer += "<xrbr-query><![CDATA[" + xrbrQuery + "]]></xrbr-query>";
	strToXfer += "<facet-name>" + myTagsFacetName + "</facet-name>";
	strToXfer += "<facet-label>" + myTagsFacetLabel + "</facet-label>";
	strToXfer += "<author-uri>" + encodedAuthorURI + "</author-uri>";
	strToXfer += encodeTagsAsXML(tagsValue);
	strToXfer += "<indices>";
	strToXfer += "<index/>";
	strToXfer += "</indices>";
	strToXfer += resourcesXML;
	strToXfer += "</TagsRequest>";

	xmlHttp.open("POST", url, true); 
	xmlHttp.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
	xmlHttp.onreadystatechange = handleHttpResponseForBulkTagging; 
	xmlHttp.send(strToXfer);
	return false;
}

function tagAllResultItems(responseSize, xrbrQuery, model, resourcesOnScreen, indexesOnScreen, currentTags, myTagsFacetName, myTagsFacetLabel, encodedAuthorURI) {
	var tagsValue = document.getElementById("bulkTagField").value; 
	tagsValue = Trim(tagsValue);

	if(tagsValue == null || tagsValue == "") {
	     	return false;
	}

	tagsValue = getValidatedTags(tagsValue);

	var strToXfer = "requestXML=<TagsRequest>";
    
	strToXfer += "<type>2</type>";
	strToXfer += "<response-size>" + responseSize + "</response-size>";
	strToXfer += "<soap-url>" + soapserverurl + "</soap-url>";	
	strToXfer += "<model>" + model + "</model>";
	strToXfer += "<xrbr-query><![CDATA[" + xrbrQuery + "]]></xrbr-query>";
	strToXfer += "<facet-name>" + myTagsFacetName + "</facet-name>";
	strToXfer += "<facet-label>" + myTagsFacetLabel + "</facet-label>";
	strToXfer += "<author-uri>" + encodedAuthorURI + "</author-uri>";
	strToXfer += encodeTagsAsXML(tagsValue);
	strToXfer += "<indices>";
	strToXfer += "<index/>";
	strToXfer += "</indices>";
	strToXfer += "</TagsRequest>";

	xmlHttp.open("POST", url, true); 
	xmlHttp.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
	xmlHttp.onreadystatechange = handleHttpResponseForBulkTagging; 
	xmlHttp.send(strToXfer);
	return false;
}

function untagAllResultItems(responseSize, xrbrQuery, model, resourcesOnScreen, indexesOnScreen, currentTags, myTagsFacetName, myTagsFacetLabel, encodedAuthorURI) {
	var tagsValue = document.getElementById("bulkTagField").value; 
	tagsValue = Trim(tagsValue);

	if(tagsValue == null || tagsValue == "") {
	     	return false;
	}

	tagsValue = getValidatedTags(tagsValue);

	var strToXfer = "requestXML=<TagsRequest>";
	strToXfer += "<type>3</type>";
	strToXfer += "<response-size>" + responseSize + "</response-size>";
	strToXfer += "<soap-url>" + soapserverurl + "</soap-url>";	
	strToXfer += "<model>" + model + "</model>";
	strToXfer += "<xrbr-query><![CDATA[" + xrbrQuery + "]]></xrbr-query>";
	strToXfer += "<facet-name>" + myTagsFacetName + "</facet-name>";
	strToXfer += "<facet-label>" + myTagsFacetLabel + "</facet-label>";
	strToXfer += "<author-uri>" + encodedAuthorURI + "</author-uri>";
	strToXfer += encodeTagsAsXML(tagsValue);
	strToXfer += "<indices>";
	strToXfer += "<index/>";
	strToXfer += "</indices>";
	strToXfer += "<resource-uris>";
	strToXfer += "<resource-uri />";
	strToXfer += "</resource-uris>";
	strToXfer += "</TagsRequest>";

	xmlHttp.open("POST", url, true); 
	xmlHttp.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
	xmlHttp.onreadystatechange = handleHttpResponseForBulkTagging; 
	xmlHttp.send(strToXfer);
	return false;
}

function encodeTagsAsXML(tagsStr) {
	var tagsList = tagsStr.split(",");
	var retStr = "<tags>";
	for (i=0; i < tagsList.length; i++) {
		retStr += "<tag>" + escape(Trim(tagsList[i])) + "</tag>";
	}
	retStr += "</tags>";
	return retStr;
}

/** This method is invoked when a user clicks on Tag It! button. */
function updateTagsRow(index, encodedResourceURI, model, myTagsFacetName, myTagsFacetLabel, encodedAuthorURI, xrbrQuery) {
	var tagsValue = document.getElementById("tagField_" + index).value; 
	tagsValue = Trim(tagsValue);

	// if the tagsValue is null OR empty, that implies two things.
	// 1. The user is playing with the click and hide link
	// 2. The user has just removed the last tag. 
  	// The current strategy would be to get a confirmation dialog to the user and let him know that
  	// this operation would remove any tags if present from the facet.
	if(tagsValue == null || tagsValue == "") {
		 fRet = confirm('You do not have any tags in the textbox. If there are any tags associated with the Facet, they would be removed.\n Are you sure you want to do that?');
	     if(!fRet)
	     	return false;
	}
	tagsValue = getValidatedTags(tagsValue);

	var strToXfer = "requestXML=<TagsRequest>";
	strToXfer += "<type>1</type>";
	strToXfer += "<model>" + model + "</model>";
	strToXfer += "<soap-url>" + soapserverurl + "</soap-url>";
	strToXfer += "<xrbr-query><![CDATA[" + xrbrQuery + "]]></xrbr-query>";
	strToXfer += "<indices>";
	strToXfer += "<index>" + index + "</index>";
	strToXfer += "</indices>";
	strToXfer += "<facet-name>" + myTagsFacetName + "</facet-name>";
	strToXfer += "<facet-label>" + myTagsFacetLabel + "</facet-label>";
	strToXfer += "<author-uri>" + encodedAuthorURI + "</author-uri>";
	strToXfer += "<resource-uris>";
	strToXfer += "<resource-uri><![CDATA[" + encodedResourceURI + "]]></resource-uri>";
	strToXfer += "</resource-uris>";
	strToXfer += encodeTagsAsXML(tagsValue);
	strToXfer += "</TagsRequest>";
	xmlHttp.open("POST", url, true); 
	xmlHttp.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
	xmlHttp.onreadystatechange = handleHttpResponse; 
	xmlHttp.send(strToXfer);
	return false;
}

/** This function expects a tagString that is already trimed.
 */
function getValidatedTags(tagsString) {
	var tagsArray = new Array();
	var arrayIndex = 0;
	var i;
    var tag = "";
	for(i=0;i<tagsString.length;i++) {
		var currentChar = tagsString.charAt(i);
		
		if(currentChar == '\'' || currentChar == '\"') {
			i++;
			currentChar = tagsString.charAt(i);

			//While the closing quotation marks are not detected or until end of string
			while(currentChar != '\'' && currentChar != '\"' && i<tagsString.length){
				
				//If a space is found
				if(currentChar == ' ' || currentChar == ',') {
					//Check and delete any additional spaces
					while(currentChar == ' ' || currentChar == ',') {
							i++;
							currentChar = tagsString.charAt(i);
						}
						i--;
						currentChar = tagsString.charAt(i);
								
				}
				//Add character inside quotation to tag
				tag += currentChar + "";
				i++;
				currentChar = tagsString.charAt(i);
			}
			//Add tag to array
			tagsArray[arrayIndex] = tag;
			arrayIndex = arrayIndex + 1;
			tag = "";
			i++;
			currentChar = tagsString.charAt(i);
		}

		if(currentChar == ' ' || currentChar == ',') {
			//do not add tag to array if space after closing of quotation
			if(tagsString.charAt(i-1) == '\'' || tagsString.charAt(i-1) == '\"'){
				// Check for multiple spaces and commas
				while(currentChar == ' ' || currentChar == ',') {
					i++;
					currentChar = tagsString.charAt(i);
				}
				if(currentChar != '\'' && currentChar != '\"'){
					i--;
				}
			}
			else {
				tagsArray[arrayIndex] = tag;
				arrayIndex = arrayIndex + 1;
				tag = "";
			
				// Check for multiple spaces and commas
				while(currentChar == ' ' || currentChar == ',') {
					i++;
					currentChar = tagsString.charAt(i);
				}
				i--;
				currentChar = tagsString.charAt(i);
			}
		} 
		else{
			if(currentChar != ' ' && currentChar != ',' && currentChar != '\'' && currentChar != '\"'){
			tag += currentChar + "";
			}
		}
		if(currentChar == '\'' || currentChar == '\"') {
			i--;
		}
	}
	if(tag != "") {
		tagsArray[arrayIndex] = tag;
	}
	
	var tagsString = "";
	for(i=0;i<tagsArray.length;i++) {
	    if(i == 0) {
			tagsString = tagsArray[i];
		} else {
			tagsString += "," + tagsArray[i];
		}
	}
	
	return tagsString;
}

function URLencode(sStr) {
    return escape(sStr).replace(/\+/g, '%2C').replace(/\"/g,'%22').replace(/\'/g, '%27').replace(/\//g, '%2F');
}

function HideTagAllForm(responseSize, xrbrQuery, model, resourcesOnScreen, indexesOnScreen, currentTags, myTagsFacetName, myTagsFacetLabel, encodedAuthorURI) {
	var tagFormContainerElement = document.getElementById("tagAllColumn");
	var html = "<a id=\"bulkTaggingAnchor\" style=\"text-decoration:none\" href=\"#\" onClick=\"showTagAllForm('" + responseSize + "','" + xrbrQuery + "','" + model + "','" + resourcesOnScreen + "','" + indexesOnScreen + "','','" + myTagsFacetName + "','" + myTagsFacetLabel + "','" + encodedAuthorURI + "'); return false;\" onMouseover=\"this.style.backgroundColor='#FAFAD2';\" onMouseout=\"this.style.backgroundColor='white';\">(click here to attach tag(s) to all " + responseSize + " items)</a>";
	tagFormContainerElement.innerHTML = html;
}

function HideTagForm(index, encodedResourceURI, model, currentTags, myTagsFacetName, myTagsFacetLabel, encodedAuthorURI, xrbrQuery) {
    var tagFormContainerElement = document.getElementById("tagColumn_" + index);
	var html = "<a id=\"taggingAnchor_" + index + "\" style=\"text-decoration:none\" href=\"#\" onClick=\"showTagForm('" + index + "','" + encodedResourceURI + "','" + model + "','" + currentTags + "','" + myTagsFacetName + "','" + myTagsFacetLabel + "','" + encodedAuthorURI + "','" + bkgndColor + "','" + xrbrQuery + "'); return false;\" onMouseover=\"this.style.backgroundColor='#FAFAD2';\" onMouseout=\"this.style.backgroundColor='"+bkgndColor+"';\">Tag it</a>";
	tagFormContainerElement.innerHTML = html;
}


function showTagAllForm(responseSize, xrbrQuery, model, resourcesOnScreen, indexesOnScreen, currentTags, myTagsFacetName, myTagsFacetLabel, encodedAuthorURI) {
	var tagFormContainerElement = document.getElementById("tagAllColumn");
	// We need to remove any structure inside and put a text box and a Tag All! button
	var tagToRemove = document.getElementById("bulkTaggingAnchor");
	tagFormContainerElement.removeChild(tagToRemove);
	globalXRBRQuery = xrbrQuery
	var html = "&nbsp; <input type=\"text\" class=\"lw_tags_input\" id=\"bulkTagField\" size=30 />";
	html += "&nbsp; <input type=\"button\" class=\"tagIt_Button C4\" value=\"Tag All!\" onClick=\"tagAllResultItems('" + responseSize + "','" + xrbrQuery + "','" + model + "','" + resourcesOnScreen + "','" + indexesOnScreen + "','" + currentTags + "','" + myTagsFacetName + "','" + myTagsFacetLabel + "','" + encodedAuthorURI + "');\" />";
	html += "&nbsp; <input type=\"button\" class=\"tagIt_Button C4\" value=\"Remove Tag(s)\" onClick=\"untagAllResultItems('" + responseSize + "','" + xrbrQuery + "','" + model + "','" + resourcesOnScreen + "','" + indexesOnScreen + "','" + currentTags + "','" + myTagsFacetName + "','" + myTagsFacetLabel + "','" + encodedAuthorURI + "');\" />";	
	html += "&nbsp; <input type=\"button\" class=\"tagIt_Button C4\" value=\"Cancel\" onClick=\"HideTagAllForm('" + responseSize + "','" + xrbrQuery + "','" + model + "','" + resourcesOnScreen + "','" + indexesOnScreen + "','" + currentTags + "','" + myTagsFacetName + "','" + myTagsFacetLabel + "','" + encodedAuthorURI + "');\"/>";

	tagFormContainerElement.innerHTML = html;
}

/**
 * This method is responsible for displaying the Form that allows the users to 
 * tag an item 
 */
function showTagForm(index, encodedResourceURI, model, currentTags, myTagsFacetName, myTagsFacetLabel, encodedAuthorURI, bkgrndColor, xrbrQuery) {
	var tagFormContainerElement = document.getElementById("tagColumn_" + index);
	// We need to remove any structure inside and put a text box and a Tag it! button
	var tagToRemove = document.getElementById("taggingAnchor_" + index);
	tagFormContainerElement.removeChild(tagToRemove);
	globalXRBRQuery = xrbrQuery;

//    var html = "&nbsp; <img src=\"images/icon_tag_it.gif\" alt=\"Tag\" /> ";


	//var html = "&nbsp; <input type=\"image\" src=\"images/icon_tag_it.gif\" alt=\"Cancel\" border=\"0\" onClick=\"HideTagForm('" + index + "','" + encodedResourceURI + "','" + model + "','" + currentTags + "','" + myTagsFacetName + "','" + myTagsFacetLabel + "','" + encodedAuthorURI + "','" + xrbrQuery + "');\"/>";
    bkgndColor = bkgrndColor;
    var html = "<span class=\"tagAddCell\">Add Tag</span>";
	html += "&nbsp; <input type=\"text\" class=\"tagInputText\" id=\"tagField_" + index + "\" onkeypress=\"invokeUpdateTagsRow('" + index + "','" + encodedResourceURI + "','" + model + "','" + myTagsFacetName + "','" + myTagsFacetLabel + "','" + encodedAuthorURI + "','" + xrbrQuery + "',event);\" size=30 value=\"" + currentTags + "\"/>";
	html += "&nbsp; <input type=\"button\" class=\"taggingSaveButton\" onClick=\"updateTagsRow('" + index + "','" + encodedResourceURI + "','" + model + "','" + myTagsFacetName + "','" + myTagsFacetLabel + "','" + encodedAuthorURI + "','" + xrbrQuery + "');\" />";
	html += "&nbsp; <input type=\"button\" class=\"taggingCancelButton\" onClick=\"HideTagForm('" + index + "','" + encodedResourceURI + "','" + model + "','" + currentTags + "','" + myTagsFacetName + "','" + myTagsFacetLabel + "','" + encodedAuthorURI + "','" + xrbrQuery + "');\"/>";
    tagFormContainerElement.innerHTML = html;
	var textBox = document.getElementById("tagField_" + index);
	textBox.focus();
}

/*
 * The following functions are used to toggle the Check Box for Tagging All results on Screen On/Off
*/
function checkAll(field) {
    for (i = 0; i < field.length; i++) {
        field[i].checked = true;
    } 
}
 
/*
* The following functions are used to toggle the Check Box for Tagging All results on Screen On/Off
*/  
function uncheckAll(field) {
    for (i = 0; i < field.length; i++) {
        field[i].checked = false; 
    }
}

/*
* The following functions are used to toggle the Check Box for Tagging All results on Screen On/Off
*/  
function toggleBulkCheckbox(field) {
    if (field[0].checked == true) {
        checkAll(field);
    } else {
        uncheckAll(field);
    }
	handleCheckbox();
}

function handleCheckbox() {
	var	field = document.checkboxForm.chk;
    var count = 0;
	//dont start from 0 since 0 is 'check all'
    for (i = 1; i < field.length; i++) {
		if (field[i].checked == true) {
			count++;
		} 
        
        if(field[i].checked == false) {
            field[0].checked = false;
        } 
    } 
	var dropdown = document.getElementById("taggingDropdown");
	if (count <= 0)	{
		dropdown.options[1].text = "There are not selected items";
		dropdown.options[0].selected = true;
	} else if (count == 1) {
		dropdown.options[1].text = "Selected one item only";
		dropdown.options[1].selected = true;
	} else {
		dropdown.options[1].text = "Selected " + count + " items only";
		dropdown.options[1].selected = true;
	}
}

function disableButton(obj)
{
	obj.disabled = true;
}

function enableButton(obj)
{
    obj.disable = false;
}