//\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
// Purpose:  Creates the XML for the media file list POST request.
// Last Revision Date:  12/10/2008
// Parameters:
//		sections:  The collection of retrieval sections to process
//\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
function GetMediaFileListInstructions(sections)
{
	try
	{
		// Retrieve the authentication cookie value.  If it doesn't exist, authC === null.
		var authC = $.cookie("SEPA_AUTH_3");
				
		var xml = 
		[
			'<mediaFileListRequest>',
			'<auth>', 
			// Build the the authentication area.
			((null === authC) ? '' : authC),
			'</auth>',
			'<focusArea>',
			// Retrieve the focus area.
			GetDataFilterFocusAreaValue(),
			'</focusArea>',
			'<dataFilters>',
			// Retrieve the data filters definitions.
			GetDataFiltersDefinitions(),
			'</dataFilters><sections>'			
		];

		// Retrieve the section definitions.
		$.each(sections, function(i, rs)
		{
			xml.push(rs.GetSectionDefintion());
		});		

		// Push the final XML elements into the array.		
		xml.push("</sections></mediaFileListRequest>");				
		
		// The join method join two or more array objects element together with a specified separator.
		// The join method returns a String object that contains each element converted to a string and concatenated together.
		return xml.join("");
	}
	catch (e)
	{
		//alert(e);
		
		return ("<mediaFileListRequest/>");
	}	
}

//\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
// Purpose:  Retrieves the XML content that forms the section content using
// an AJAX request to an RSS service.
// Last Revision Date:  12/10/2008
// Parameters:
//		sections:  The collection of retrieval sections to process
//\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
function GetFeedList(sections)
{
	try
	{		
		// Notify each retrieval section (rs) that an update is about to occur.
		$.each(sections, function(i, rs)
		{
			// cr = cachedResponse
			var cr = rs.GetResponseCache();
			
			if (cr == null)
			{			
				_feedProxy.invokeXML("furl=" + rs.GetFeedURL(),
			    EMPTY_POST_DATA,
			    function(responseXML)
			    {				
					// Notify the section that the response was received.
					if (rs.OnResponseReceived)
					{
						rs.OnResponseReceived(responseXML);
					}
			    },
			    function(errorMessage)
			    {
			        alert(errorMessage);
			    },
				IS_FEED_METHOD);
			}
			else
			{
				// Notify the section that the response was received.
				if (rs.OnResponseReceived)
				{
					rs.OnResponseReceived(cr);
				}
			}								
		});
	}
	catch (e)
	{
		alert("There was an error in the 'GetFeedList' function:\n\n" + e);	
	}	
}

//\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
// Purpose:  Retrieves the XML content that forms the section content using
// an AJAX request to a web service.
// Last Revision Date:  12/10/2008
// Parameters:
//		sections:  The collection of retrieval sections to process
//\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
function GetMediaFileList(sections)
{
	try
	{
		//alert(GetMediaFileListInstructions(sections));
		
		//alert(GetDataFiltersDefinitions());
		
		/*
		if (sections[0].GetSectionDefintion().indexOf("presentation") > -1) 
		{		
			$("#debug").html('<textarea style="width:100%;height:100px;">' + GetMediaFileListInstructions(sections) + '</textarea>');
		}
		*/
				
		// Retrieve the data.
		_DFServiceProxy.invokeXML("GetMediaFileList3",
		("mediaFileListRequestXML=" + GetMediaFileListInstructions(sections)),
	    function(responseXML)
	    {
			if (responseXML != null)
			{
				// Iterate over each retrieval section (rs):
				$.each(sections, function(i, rs)
				{			
					// Notify the section that the response was received.
					if (rs.OnResponseReceived)
					{
						rs.OnResponseReceived(responseXML);
					}
				});								
			}				
	    },
	    function(errorMessage)
	    {
	        alert(errorMessage);
	    },
		IS_WEB_METHOD);
	}
	catch (e)
	{
		alert("There was an error in the 'GetMediaFileList' function:\n\n" + e);	
	}	
}

//\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
// Purpose:  Retrieves the XML content that forms the section content using
// an AJAX request to a web service.
// Last Revision Date:  12/10/2008
// Parameters:
//		sections:  The collection of retrieval sections to process
//\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
function GetContentForSections(sections)
{
	try
	{
		//var feedSections = [];
		//var sepaSections = [];
		
		// Notify each retrieval section (rs) that an update is about to occur.
		$.each(sections, function(i, rs)
		{
			if (rs.OnBeforeUpdate) 
			{
				rs.OnBeforeUpdate();
			}	
			
			// Separate the feeds into the individual arrays.
			if (rs.GetMediaFileType() == "feed")
			{
				GetFeedList([rs]);				
				//feedSections[feedSections.length] = rs;
			}	
			else
			{
				GetMediaFileList([rs]);				
				//sepaSections[sepaSections.length] = rs;
			}
		});
		
		//GetMediaFileList(sepaSections);	
		
		//GetFeedList(feedSections);			
	}
	catch (e)
	{
		alert("There was an error in the 'GetContentForSections' function:\n\n" + e);	
	}
}


var UI_PARAMS_BEFORE = {opacity:1.0};
var UI_PARAMS_AFTER = {opacity:0.0};
var UI_DURATION = 1000;

var EMPTY_POST_DATA = "";
var IS_WEB_METHOD = true;
var IS_FEED_METHOD = false;
var RETRIEVE_NO_PERMALINKS = 0;
var RETRIEVE_ONLY_PERMALINKS = 1;
var RETRIEVE_ALL = 2;

function GetPropValue(props, propName)
{
	return ($(props).find("prop[n='" + propName + "']").attr("v"));
}

function HyperlinkBuilder(index, node, tjid, rt)
{
	try
	{
		if (rt) 
		{
			var props = $(node).find("props");
			
			var pURL = props.find("prop[n='url']").attr("v");
			var pPath = props.find("prop[n='path']").attr("v");
		
			$(tjid).append(rt, 
			{				
				href:((pURL.length > 0) ? pURL : pPath),
				nodeID:GetPropValue(props, "id"),
				type:GetPropValue(props, "type"),
				title:GetPropValue(props, "alt"),
				text:GetPropValue(props, "title"),
				cdate:GetPropValue(props, "creationDateShort"),
				pdate:GetPropValue(props, "pubStartDate"),
				fileAbstract:GetPropValue(props, "abstract")
			});			
		}
	}
	catch (e)
	{
		//alert("There was an error during the execution of the 'HyperlinkBuilder' function:\n\n" + e);		
	}
}

function SEPANewsItemBuilder(index, node, targetJID, resultTemplate)
{
	try
	{
		if (resultTemplate) 
		{
			var props = node.find("props");
			
			$(targetJID).append(resultTemplate, 
			{
				nodeID:GetPropValue(props, "id"),
				headline:GetPropValue(props, "title"),
				excerpt:GetPropValue(props, "excerpt")	
			});
			
			$(targetJID + " a[class!='thickbox']").attr("target", "_blank");				
		
			tb_init(targetJID + " a.thickbox");
			
		}
	}
	catch (e)
	{
		alert("There was an error during the execution of the 'SEPANewsItemBuilder' function:\n\n" + e);		
	}
}

function SectionResponseParser(section)
{
	try
	{
	
		if (section) 
		{
			var xml = section.GetResponseCache();
			
			if (xml)
			{
				// Empty the target container of any existing elements.
				$(section.GetSectionSelectorJID()).empty();
		
				// Retrieve the collection of source root elements.
				var nodes = $(xml).find(section.GetSourceElementName());
							
				// Proceed only if the source root elements exist.	
				if (nodes != null)
				{	
					// Calculate the desired retrieve/display count.
					var countDisplay = section.GetRetrieveCount();
					
					if (countDisplay > nodes.length)
					{
						countDisplay = nodes.length;
					}
				
					var rt = section.GetResultDisplayTemplate();
	
					if (rt != null) 
					{											
						// Update the results container.
						$(section.GetResultsDisplaySelectorJID()).html(rt, 
						{
							displayCount: countDisplay,
							totalCount: section.GetTotalCount(),
							type: section.GetElementName(),
							pluralSuffix: (((countDisplay > 1) || (countDisplay == 0)) ? "s" : "")
						});
					}
									
					var JID = section.GetSectionSelectorJID();
					var it = section.GetIterationTemplate();
															
					$(nodes).each(function(index)
		        	{		
						// Only process the nodes until the desired display count is achieved.
						if ((index + 1) > countDisplay) 
						{
							return false;
						}
																
						// Call the iteration function for each node.
						section.NodeIterator(index, $(this), JID, it);
			        });
									
					if (($(section.GetSliderControlJID()).length > 0))  
					{		
						// Update the slider value.
						if (section.GetTotalCount() > 0)
						{
							// Adjust the slider position to reflect the relative number of retrieved records.					
							//$(section.GetSliderControlJID()).slider("moveTo", Math.ceil((countDisplay / section.GetTotalCount()) * 100), 0, true);
							$(section.GetSliderControlJID()).slider("value", Math.ceil((countDisplay / section.GetTotalCount()) * 100));
						}
						else 
						{
							// Otherwise, since no records were retrieved, move the slider position to zero.
							//$(section.GetSliderControlJID()).slider("moveTo", 0, 0, true);
							$(section.GetSliderControlJID()).slider("value", 0);
						}
					}							
				}	
			}
			
			// Notify the section that the update is complete.
			if (section.OnAfterUpdate) 
			{
				section.OnAfterUpdate();
			}	
		}
	}	
	catch (e)
	{
		alert("There was an error in the 'SectionResponseParser' function:\n\n" + e);		
	}
	
}

function RetrievalSection(mediaFileType,
elementName,
sourceElementName,
elementFilter,
sectionSelectorJID,
resultsDisplaySelectorJID,
resultDisplayTemplate,
progressControlJID, 
sliderControlJID, 
permanentContentLevel,
minRetrieveCount,
iterationFunction,
iterationTemplate,
feedURL
)
{
	// The media file type identifier:
	var _mediaFileType = mediaFileType;
	
	this.GetMediaFileType = function(){return _mediaFileType};
	this.SetMediaFileType = function(mediaFileType){_mediaFileType = mediaFileType};
	
	var _sourceElementName = sourceElementName;
	
	this.GetSourceElementName = function(){return _sourceElementName};
	this.SetSourceElementName = function(sourceElementName){_sourceElementName = sourceElementName};
	
	// The element name used for result display text:
	var _elementName = elementName;
	
	this.GetElementName = function(){return _elementName};
	this.SetElementName = function(elementName){_elementName = elementName};
	
	var _feedURL = feedURL;
	
	this.GetFeedURL = function(){return _feedURL};
	this.SetFeedURL = function(feedURL){_feedURL = feedURL};
	
	// The section selector JID:
	var _sectionSelectorJID = sectionSelectorJID;
	
	this.GetSectionSelectorJID = function(){return _sectionSelectorJID};
	this.SetSectionSelectorJID = function(sectionSelectorJID){_sectionSelectorJID = sectionSelectorJID};
	
	// The results display selector JID:
	var _resultsDisplaySelectorJID = resultsDisplaySelectorJID;
	
	this.GetResultsDisplaySelectorJID = function(){return _resultsDisplaySelectorJID};
	this.SetResultsDisplaySelectorJID = function(resultsDisplaySelectorJID){_resultsDisplaySelectorJID = resultsDisplaySelectorJID};
	
	// Instance response cache:
	var _responseCache = null;
	
	this.GetResponseCache = function(){return _responseCache};
	this.SetResponseCache = function(responseCache){_responseCache = responseCache};	
	
	var _elementFilter = elementFilter;
	
	this.GetElementFilter = function(){return _elementFilter};
	this.SetElementFilter = function(elementFilter){_elementFilter = elementFilter};	
	
	// The template to specify the results display message:
	var _resultDisplayTemplate = resultDisplayTemplate;
	
	this.GetResultDisplayTemplate = function(){return _resultDisplayTemplate};
	this.SetResultDisplayTemplate = function(resultDisplayTemplate){_resultDisplayTemplate = resultDisplayTemplate};
	
	// Progress Control JID:
	var _progressControlJID = progressControlJID;
	
	this.GetProgressControlJID = function(){return _progressControlJID};
	this.SetProgressControlJID = function(progressControlJID){_progressControlJID = progressControlJID};
	
	// Slider Control JID:
	var _sliderControlJID = sliderControlJID;
	
	this.GetSliderControlJID = function(){return _sliderControlJID};
	this.SetSliderControlJID = function(sliderControlJID){_sliderControlJID = sliderControlJID};
	
	// Minimum file count to retrieve:	
	var _minRetrieveCount = minRetrieveCount;
	
	this.GetMinRetrieveCount = function(){return _minRetrieveCount};
	this.SetMinRetrieveCount = function(minRetrieveCount){_minRetrieveCount = minRetrieveCount};
		
	// The total number of files for the section:
	var _totalCount = 0;
	
	this.GetTotalCount = function(){return _totalCount};
	this.SetTotalCount = function(totalCount){_totalCount = totalCount};	
	
	this.GetRetrieveFactor = function()
	{
		if ($(_sliderControlJID).length > 0)
		{
			return $(_sliderControlJID).slider("value");
		}
		else
		{
			return 100;
		}
	};
	
	// The number of files to retrieve:
	var _retrieveCount = 0;
	
	this.GetRetrieveCount = function()
	{
		var rf = this.GetRetrieveFactor();

		// If retrieveFactor is > 0, treat the retrieveFactor as a percentage.
		// The function return value will be the smallest integer >= the
		// total count multiplied by the percentage of elements to retrieve.
		if ((rf > 0) && (rf > _minRetrieveCount))
		{
			_retrieveCount = (Math.ceil(this.GetTotalCount() * (rf / 100)));
		}
		// Otherwise, return the minimum count.
		else
		{
			_retrieveCount = this.GetMinRetrieveCount();
		}
		
		return _retrieveCount;
	};
	this.SetRetrieveCount = function(retrieveCount){_retrieveCount = retrieveCount};		
	
	// The permanent content level:  0 = No Permanent Content, 1 = Only Permanent Content, 2 = Include All
	var _permanentContentLevel = permanentContentLevel;
	
	this.GetPermanentContentLevel = function(){return _permanentContentLevel};
	this.SetPermanentContentLevel = function(permanentContentLevel){_permanentContentLevel = permanentContentLevel};	
	
	// Function to execute before updates:
	this.OnBeforeUpdate = function()
	{
		if (_progressControlJID)
		{
			$(_progressControlJID).show();
			$(_progressControlJID).animate(UI_PARAMS_BEFORE, UI_DURATION);
		}
	};
	
	// Function to execute when the XML response is received.
	this.OnResponseReceived = function(xml)
	{
		_totalCount = 0;
		
		if (_mediaFileType != "feed")
		{
			// Update the section response cache.
			this.SetResponseCache($(xml).find(this.GetElementFilter()));
			//"section[mediaFileType='" + this.GetMediaFileType() + "'][permanentContentLevel='" + this.GetPermanentContentLevel() + "'] mediaFiles[mediaFileType='" + this.GetMediaFileType() + "']"

			$.each(_responseCache, function(index, node)
			{
				try
				{
					// Update the total retrieved file count for the section.
					_totalCount += parseInt($(node).attr("totalFileCount"));
				}
				catch (e)
				{
					_totalCount = 0;
				}				
			});
		}
		else
		{
			// Update the section response cache.
			this.SetResponseCache(xml);

			_totalCount = ((xml) ? $(xml).find("item").length : 0);		
		}
			
		// Call the parsing function.
		this.SectionParser();
	};
	
	var _customAfterUpdateFunc = null;
	
	this.GetCustomAfterUpdate = function(){return _customAfterUpdateFunc};
	this.SetCustomAfterUpdate = function(customAfterUpdateFunc){_customAfterUpdateFunc = customAfterUpdateFunc};
	
	// Function to execute after updates:
	this.OnAfterUpdate = function()
	{
		if (_progressControlJID)
		{
			$(_progressControlJID).animate(UI_PARAMS_AFTER, UI_DURATION, function(){$(this).hide();});
		}
		
		// Retrieve the current filter text.
		var ft = GetKeywordFilterText();

		if (ft.length > 0) 
		{
			// Highlight the link text and abstract text for the rows.
			$(_sectionSelectorJID + " a").highlight(ft);
		}
		
		if (_customAfterUpdateFunc)
		{
			_customAfterUpdateFunc();
		}
	};
	
	// Retrieves the section's definition.
	this.GetSectionDefintion = function()
	{			
		var sd = ["<section mediaFileType='"];
		sd.push(this.GetMediaFileType());
		sd.push("' sortDirection='desc' pageNumber='1' fileCountPerPage='");
		sd.push(this.GetRetrieveCount());
		sd.push("' includePermanentContent='");
		sd.push(this.GetPermanentContentLevel());
		sd.push("'/>");
		
		return sd.join('');
	};	
	
	// The function to call for each individual file parsed from the result XML.
	this.NodeIterator = iterationFunction;
	
	// The template to apply when the iteration function is called.
	var _iterationTemplate = iterationTemplate;
	
	this.GetIterationTemplate = function(){return _iterationTemplate};
	this.SetIterationTemplate = function(iterationTemplate){_iterationTemplate = iterationTemplate};
	
	// The function to execute to parse the section content.
	this.SectionParser = function()
	{
		SectionResponseParser(this);
	};
}