var soapRequest;
var params;
var resultdivMulti;
var SavedCategories;

function display_dynamiccontentmulti(ssQueryText,ssSortField, ssSortOrder, ssResultCount, ssTitle, ssCategoryField, ssStartCollapsed,ssGroupByLevel,ssHasHeader)
{
	
	var containerIdMulti = "PC_DYNAMICCONTENTMULTI";
	
	document.write('<div id="' + containerIdMulti + '"></div>');
	 
	
	document.write();
	
	params = {
	
			queryTextMulti: ssQueryText,
			sortFieldMulti : ssSortField,
			sortOrderMulti : ssSortOrder,
			resultCountMulti : ssResultCount,
			titleMulti : ssTitle,
			categoryField : ssCategoryField,
			startCollapsed : ssStartCollapsed,
			groupByLevel : ssGroupByLevel
	};
	
	resultdivMulti = document.getElementById(containerIdMulti);
	
	window.PARAMS = params;
	window.RESULTDIVMULTI = resultdivMulti;
	
	if(resultdivMulti)
	{
		//runSearch(params, resultdivMulti);
		refreshCatPanes(params, resultdivMulti);
	}
}


	//runs AJAX request to count the total number of results per category 
	//runs a second AJAX request to get all the results
	//then categorizes and presents results in panes
	function refreshCatPanes(params, resultdivMulti)
	{
		//start by running a search to get TotalRows back so that we know how many results to categorize
		var requestUrl = httpCgiPath +
	        "?IdcService=GET_SEARCH_RESULTS" +
			"&QueryText=" + params.queryTextMulti +
			"&SearchQueryFormat=UNIVERSAL" +
			"&ftx=" +
			"&AdvSearch=True" +
			"&ResultCount=1" +
			"&IsSoap=1";
		runSoapRequest(requestUrl, setTotalRowsAndRunCatSearch);
	
	}



// run a search against the content server with SOAP, and
// display the results on the same page. No browser refresh
// will be required
function runSoapRequest(requestUrl, displayFunction)
{
	// run the XMLHTTP request, and draw the response with
	// the function 'displayFunction'
	loadXMLDoc(requestUrl, displayFunction);

	// stop the form from posting
	return false;
}



//sets the TOTAL_ROWS global variable to be used for calculating the number of categories
//then calls the category search
function setTotalRowsAndRunCatSearch()
{
	// if the XML document isn't ready, do nothing
	if (!checkXMLDoc())
		return;

	// get the first idc:document object, which contains all the
	// name-value pairs for the response
	var docNodes = getIdcElementsByTagName(soapRequest.responseXML,"document");
	//if (docNodes != null)
	//{
		var localData = docNodes[0];

		// obtain the number of total results
		var totalRows = getSoapValue(localData, "TotalRows");
		//var totalRows = TOTAL_ROWS;
	//}

	//var that = DynamicContentMulti.that;
	runCatSearch(params, resultdivMulti);
}

//categorized search
function runCatSearch (params, resultsDiv)
	{
		// tell the user that the search is running
		resultsDiv.innerHTML = "running search...";

		// this is a basic Search URL, with IsSoap appended
		// so we get an XML response
		var requestUrl = httpCgiPath +
			"?IdcService=GET_SEARCH_RESULTS" +
			"&QueryText=" + params.queryTextMulti +
			"&SearchQueryFormat=UNIVERSAL" +
			"&ftx=" +
			"&AdvSearch=True" +
			//NOTE: 200 is for testing purposes, uncomment this.totalRow  for accurate results
			"&ResultCount=200"+ //this.totalRows +
			"&SortField=" + params.sortFieldMulti +
			"&SortOrder=" + params.sortOrderMulti +
			"&IsSoap=1";
		
			
		runSoapRequest(requestUrl, drawCatSearchResultsMulti);
	
	}


// extract the search results from the XML response, and
	// draw them to the page in categorized collapsible panels
	function drawCatSearchResultsMulti ()
	{
		var categories;
		//var that = DynamicContentMulti.that;
		
		// if the XML document isn't ready, do nothing
		if (!checkXMLDoc())
			return;

		// get the first idc:document object, which contains all the
		// name-value pairs for the response
		var docNodes = getIdcElementsByTagName(soapRequest.responseXML, "document");
		var localData = docNodes[0];

		// obtain the number of total results
		//var totalRows = RequestUtils.getSoapValue(localData, "TotalRows");
		
		// obtain the SearchResults result set from the response
		var searchResultsMulti = getSoapResultSet(soapRequest.responseXML, "SearchResults");

		var htmlString = '';
		
		if(searchResultsMulti == null)
		{
			htmlString += "";
		}
		else //extract and categorize results then build html to draw them
		{
			categories = fillCatHash(searchResultsMulti);
			
			//save categories to avoid unnecessary AJAX calls later
			//DynamicContentMulti.categories = categories;
			SavedCategories = categories;
			
			htmlString += makeCatResultsHtml(categories);
		}
		htmlString += '';

		// insert the string into the specific DIV
		//var resultsDiv = document.getElementById("SS_NY_FR_RELATEDLINKSDYNA");
		resultdivMulti.innerHTML = htmlString;
		
		//TODO: commented out the filter:
		//var filterDiv = document.getElementById("filterSearch");
		//filterDiv.style.display = "block";
		
		//register SpryMulti collapsible panels for each docFormat category
		if(categories && categories.length)
		{
			var panels = new Array();
			
			for(var i=0; i<categories.length;)
			{
				var panelIDMulti = "CollapsiblePanel" + (++i);
				window[panelIDMulti] = new SpryMulti.Widget.CollapsiblePanel(panelIDMulti);
				if(!params.startCollapsed)
				{
					window[panelIDMulti].open();
				}
			}
		}
	}

	//takes search results and builds a hash table with group by field as key and arrays of grouped results as value
function fillCatHash(searchResultsMulti)
	{
		var categories = new Array();
		categories.length=0;
		
	
		//build doc format categories
		for (var i = 0; i < searchResultsMulti.childNodes.length; i++)
		{
			// only iterate over explicit XML node objects
			var itemMulti = searchResultsMulti.childNodes[i];
			if (itemMulti.nodeType == null || itemMulti.nodeType != 1)
				continue;

			// extract the title and comments from the current row
			var titleMulti = getSoapValue(itemMulti, "dDocTitle");
			var commentsMulti = getSoapValue(itemMulti, "xDocDesc");
			var categoryField = getSoapValue(itemMulti, params.categoryField);
			var catFieldName = params.categoryField;
			var groupByLevel = params.groupByLevel;
			var size = getSoapValue(itemMulti, "VaultFileSize");
			var dCreateDate = getSoapValue(itemMulti, "dCreateDate");
			var urlMulti = getSoapValue(itemMulti, "URL");
			var dIDMulti = getSoapValue(itemMulti, "dID");
			var dDocNameMulti = getSoapValue(itemMulti, "dDocName");
			var extensionMulti = getSoapValue(itemMulti, "dExtension");
			var dDocAuthor = getSoapValue(itemMulti, "dDocAuthor");
			var dInDate = getSoapValue(itemMulti, "dInDate");
			var dDocType = getSoapValue(itemMulti, "dDocType");
						
			//an item may belong to more than one category so split
			var categoryFieldSplit = new Array();
			if(categoryField){		
				categoryFieldSplit = categoryField.split(",");
			}else{
				categoryFieldSplit[0] = "Undefined";	
			}
			for(var j=0; j<categoryFieldSplit.length; j++)
			{
				
				var category = categoryFieldSplit[j];
				if (catFieldName == "dInDate" || catFieldName == "xContentDate")
				{
					category = getMonthAndYear(category);
					
				}
				//create a doc object and add it to the organized results categories
				var doc = new Object();
				doc.titleMulti = titleMulti;
				doc.commentsMulti = commentsMulti;
				doc.category = category;
				doc.size = size;
				doc.dCreateDate = dCreateDate;
				doc.urlMulti = urlMulti;
				doc.dIDMulti = dIDMulti;
				doc.dDocNameMulti = dDocNameMulti;
				doc.extensionMulti = extensionMulti;
				doc.dDocAuthor = dDocAuthor;
				//doc.xDescription = xDescription;
				//doc.xLastUpdated = xLastUpdated;
				doc.dInDate = dInDate;
				//doc.xContentCreator = xContentCreator.substring(0,30);
				//doc.xFeedbackEnabled= xFeedbackEnabled;
				//doc.xViewableVersion = xViewableVersion;
				doc.dDocType = dDocType;
				//doc.xExternalLink = xExternalLink;
				//create a new category if no such category exists
				if(!categories[category]){
					categories[category] = new Object();
					categories[category].itemsMulti = new Array();
					categories[category].name = category;
					//categories.length++;
				} 
				//add doc object to the category
				var itemsMultiLength = categories[category].itemsMulti.length;
				categories[category].itemsMulti[itemsMultiLength] = doc;
			}
		}	
		return categories;
	}

	//generates html for the categorized result panels
	function makeCatResultsHtml (categories)
	{
		var hString = "";
		hString = '<div class="block head">Related Links</div>';
		var htmlString = "";
		//create categorized html panes
		var categoryCount = 0;
		var numResultsToDisplayMulti;//number of results to display in a pane
		var showMoreLinkMulti;//boolean determines whether to show the 'Show All ...' link at the end of a pane
		var addblock = '<div class="block spacer"><!--save--></div>';
		
		//loop through the categories and make html for each category pane
		for(var cat in categories)
		{
			if(cat == "remove" || cat == "RemoveAt" || cat == ""){
				continue;
			}
			var category = categories[cat];
			var itemsMulti = category.itemsMulti;

			
			//CATEGORIES WITH NUMBER OF ITEMS...
			//htmlString += '<div class="block item">' + (cat==""?"Undefined":cat) + ' (' + itemsMulti.length + ') </div><div>';\
			if(!(cat == "Campaign Materials" || cat == "Tradeshows" || cat == "Events")){
			htmlString += '<div class="block item">' + (cat==""?"Undefined":cat) + '</div><div class="clear"><!--save--></div>';}
			//htmlString += '<div class="CollapsiblePanelContent" style="height:auto;overflow:visible;>';
			htmlString += '<div class="nonCollapsiblePanel">';

			//find out how many results to show in a pane an if a 'Show All ...' link is required
			if(itemsMulti.length > params.resultCountMulti){
				numResultsToDisplayMulti = params.resultCountMulti;
				showMoreLinkMulti = true;
			}else{
				numResultsToDisplayMulti = itemsMulti.length;
				showMoreLinkMulti = false;
			}

			//loop through results and show
			for(var i=0; i<numResultsToDisplayMulti; i++)
			{
				if((itemsMulti[i].extensionMulti == "xml" || itemsMulti[i].extensionMulti == "html") && itemsMulti[i].category == "Success Stories"){
					htmlString += '<div class="block link"><a href="/mv_internet/SuccessStories/' + itemsMulti[i].dDocNameMulti + '">- '+ itemsMulti[i].titleMulti +'</a></div><div class="clear"><!--save--></div>';
				} else{
				  if(itemsMulti[i].category == "Events" || itemsMulti[i].category == "Tradeshows" || itemsMulti[i].category == "Campaign Materials"){
					htmlString += '<!--Events or Tradeshows exist. Show Header-->';
					addblock = '';
				}else{
					htmlString += '<div class="block link"><a href="?IdcService=GET_FILE&dID=';
					htmlString += itemsMulti[i].dIDMulti + '&dDocName=' + itemsMulti[i].dDocNameMulti + '">- '+ itemsMulti[i].titleMulti +'</a></div><div class="clear"><!--save--></div>';
					}
				}

			}

			if(showMoreLinkMulti){
				htmlString += '<a class="block link" style="text-align:right;cursor:pointer;" onclick="refreshPaneResultsMulti(this.parentNode, SavedCategories[\'' + cat + '\'].itemsMulti)">More ...</a>';
			}
			
			htmlString += '</div>';
			//htmlString += '</div>';
		}

		if(categoryCount==0)
		{
			htmlString += "";
		}
		
		if(htmlString == ""){
			return htmlString;}
		else{
			htmlString += addblock;
			hString += htmlString;
			return hString;}
	}

	//returns image icon file name based on item file extension
	//EDIT this to add more extension icons; make sure to have corresponding icon files in the fragment's assets directory
	function getImageFilename(extensionMulti){
		switch(extensionMulti.toLowerCase())
		{
			case "doc": return "icon-doc.gif";
			case "exe": return "icon-exe.gif";
			case "gif": return "icon-image.gif";
			case "bmp": return "icon-image.gif";
			case "jpg": return "icon-image.gif";
			case "jp2": return "icon-image.gif";
			case "jpeg": return "icon-image.gif";
			case "png": return "icon-image.gif";
			case "pcx": return "icon-image.gif";
			case "svg": return "icon-image.gif";
			case "ai": return "icon-image.gif";
			case "pdf": return "icon-pdf.gif";
			case "ppt": return "icon-ppt.gif";
			case "swf": return "icon-swf.gif";
			case "vsd": return "icon-vsd.gif";
			case "xls": return "icon-xls.gif";
			case "zip": return "icon-zip.gif";
			default: 	return "icon-misc.gif";
		}
		return "icon-misc.gif";
	}



//Take month and year as date value
function getMonthAndYear(category)
{
	var slashIndex = category.indexOf("/");
	if(slashIndex > 0)
	{
		var rel_month= category.substring(0,slashIndex);

		switch(rel_month)
		{
			case "1": 
				rel_month = "Jan"; 
				break;
			case "01": 
				rel_month = "Jan"; 
				break;
			case "2": 
				rel_month = "Feb"; 
				break;
			case "02": 
				rel_month = "Feb";
				break;
			case "3": 
				rel_month = "Mar";
				break;
			case "03": 
				rel_month = "Mar";
				break;
			case "4": 
				rel_month = "Apr";
				break;
			case "04": 
				rel_month = "Apr";
				break;
			case "5": rel_month = "May";break;
			case "05": rel_month = "May";break;
			case "6": rel_month = "Jun";break;
			case "06": rel_month = "Jun";break;
			case "7": rel_month = "Jul";break;
			case "07": rel_month = "Jul";break;
			case "8": rel_month = "Aug";break;
			case "08": rel_month = "Aug";break;
			case "9": rel_month = "Sept";break;
			case "09": rel_month = "Sept";break;
			case "10": rel_month = "Oct";break;
			case "11": rel_month = "Nov";break;
			case "12": rel_month = "Dec";break;
			default: rel_month = ""; 
		}
		
		var rel_day_year = category.substring(slashIndex+1, category.length);
		slashIndex = rel_day_year.indexOf("/");
		var spaceIndex = rel_day_year.indexOf(" ");
		if (slashIndex > 0){
			rel_year = "20" + rel_day_year.substring(slashIndex+1, spaceIndex);
		}
		category = rel_month + " " + rel_year;
	}
	return category;
}
						


function refreshPaneResultsMulti(container, itemsMulti)
{
	var htmlString = "";
	//loop through results and show
	for(var i=0; i<itemsMulti.length; i++)
	{
		htmlString += makeResultHtmlMulti(itemsMulti[i]);
	}
	//container.style.height = "385px";
	container.style.overflow = "auto";
	container.innerHTML = htmlString;
}



function makeResultHtmlMulti(itemMulti)
{
	//var that = DynamicContentMulti.that;
	var htmlString = "";
	//htmlString += '<table width="100%" cellspacing="0" cellpadding="6" border="0">';
	//htmlString += '<tbody>';
	//htmlString += '<tr valign="top">';
	//htmlString += '<td>';
	
		if((itemMulti.extensionMulti == "xml" || itemMulti.extensionMulti == "html") && itemMulti.category == "Success Stories"){
			htmlString += '<div class="block link"><a href="/mv_internet/SuccessStories/' + itemMulti.dDocNameMulti + '">- '+ itemMulti.titleMulti +'</a></div><div class="clear"><!--save--></div>';
		} else{
		  	if(itemMulti.category == "Events" || itemMulti.category == "Tradeshows" || itemMulti.category == "Campaign Materials"){
				htmlString += '<!--Events or Tradeshows exist. Show Header-->';
			}else{
				htmlString += '<div class="block link"><a href="?IdcService=GET_FILE&dID=';
				htmlString += itemMulti.dIDMulti + '&dDocName=' + itemMulti.dDocNameMulti + '">- '+ itemMulti.titleMulti +'</a></div><div class="clear"><!--save--></div>';
			}
		}
		
	
	
	
	//htmlString += '</span>';
	//htmlString += '</td>';
	//htmlString += '</tr>';
	//htmlString += '</tbody>';
	//htmlString += '</table>';
	
	return htmlString;
}

	

function navigate(locMulti)
{
	window.location = locMulti;
}


	



// ------------------------------------------------------------------
//  Utility functions for running a SOAP request
// ------------------------------------------------------------------

// This function creates a XMLHttpRequest object specific to the
// browser, runs the web service, and processes the result.
function loadXMLDoc(urlMulti, handleResponseFunction)
{
	soapRequest = false;

	// try to create a native XMLHttpRequest object, works in
	// Mozilla 1.0, Safari 1.2, Netscape 7, and Opera 7.60
	if(window.XMLHttpRequest)
	{
		try
		{
			soapRequest = new XMLHttpRequest();
		}
		catch(e)
		{
			soapRequest = false;
		}
	}
	// otherwise create an ActiveX object for Internet Explorer
	else if(window.ActiveXObject)
	{
		try
		{
			soapRequest = new ActiveXObject("Msxml2.XMLHTTP");
		}
		catch(e)
		{
			try
			{
				  soapRequest = new ActiveXObject("Microsoft.XMLHTTP");
			}
			catch(e)
			{
				  soapRequest = false;
			}
		}
	}

	// if the object could be created, send a request
	if(soapRequest)
	{
		// set the function to process state changes in the request
		// so that the response will be drawn to the page only
		// when its complete
		soapRequest.onreadystatechange = handleResponseFunction;

		// open the URL, and send an empty string to finish
		// the request
		try
		{
			soapRequest.open("GET", urlMulti, true);
			if (soapRequest.readyState == 0)
			{
				throw 'Failed to open the connection';
			}
			soapRequest.send("");
		}
		catch (e)
		{
			alert(e + "\nUnable to open the XMLHTTP request.\n" +
				"The server may be down, you may not have permission,\n" +
				"or else you attempted to connect to a server other\n" +
				"than the one hosting this page.");
		}
	}
}

// check to make sure the XMl document is fully loaded, and no
// HTTP errors occurred.
function checkXMLDoc()
{
	var isReady = false;
	// only do something is the request state is "loaded"
	if (soapRequest.readyState == 4)
	{
		// check the HTTP status for a successful connection
		if (soapRequest.status == 200)
		{
			isReady = true;
			
		}
		else
		{
			// could be access denied, or a server error
			alert("There was a problem retrieving the XML data:\n" +
				soapRequest.statusText);
		}
	}
	return isReady;
}

// ------------------------------------------------------------------
//  Utility functions for extracting text from the SOAP response
// ------------------------------------------------------------------

// pull out a node from the XML doc by its name. This is needed
// because of the different ways each browser handles XML namespaces
function getIdcElementsByTagName(xmlDoc, nodeName)
{
	if (xmlDoc.getElementsByTagNameNS)
	{
		// for w3c compliant XML objects
		return xmlDoc.getElementsByTagNameNS(
			"http://www.stellent.com/IdcService/",
			nodeName);
	}
	else
	{
		// for IE
		return xmlDoc.getElementsByTagName("idc:" + nodeName);
	}
}

// a helper function to extract a ResultSet from a SOAP response
function getSoapResultSet(xmlDoc, rsetName)
{
	var allResultSets = getIdcElementsByTagName(xmlDoc, "resultset");

	var rset = null;
	for (var i=0; i<allResultSets.length; i++)
	{
		if (allResultSets[i].getAttribute("name") == rsetName)
		{
			rset = allResultSets[i];
			break;
		}
	}
	return rset;
}

// a helper function to extract an attritbute or a value from
// an idc:field XML node
function getSoapValue(xmlNode, name)
{
	// first, try pulling the value from the attributes
	var value = xmlNode.getAttribute(name);
	if (value == null)
	{
		// otherwise, loop over all the children looking for a
		// node with the 'name' attribute set to the pased value
		// for 'name'
		for (var i=0; i<xmlNode.childNodes.length; i++)
		{
			var subNode = xmlNode.childNodes[i];

			// skip nodes that are not full xml elementss
			if (subNode.nodeType == null || subNode.nodeType != 1)
			{
				continue;
			}

			if (subNode.getAttribute("name") == name)
			{
				if (subNode.text)
					value = subNode.text;  // IE
				else
					value = subNode.textContent; // Safari/Mozilla
			}

		}
	}
	return value;
}