//\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
// 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.
		var i = 0;
		var sectionCount = sections.length;

		while (i < sectionCount)
		{			
			xml[xml.length] = (sections[i].GetSectionDefintion());
			
			i++;
		}		

		// Push the final XML elements into the array.		
		xml[xml.length] = ("</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)
	{		
		return ("<mediaFileListRequest/>");
	}	
}

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;
var MIN_RETRIEVE_COUNT = 5000;

//\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
// Purpose:  Retrieves the "v" attribute value for a
// specified <prop> element with an "n" attribute value
// specified by "propName".
// Last Revision Date:  05/20/2010
// Parameters:
//		props:  The property XML
//		propName:  The property name attribute value to match
//\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
function GetPropValue(props, propName)
{
	return (props.children("prop[n='" + propName + "']:eq(0)").attr("v"));
}


//\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
// Purpose:  Builds a <tr> element for a node.
// Last Revision Date:  05/20/2010
// Parameters:
//		node:  The XML element containing the properties
//		isUserAuthenticated:  A value indicating whether or not the user is authenticated
//\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
function TableRowBuilder(node, isUserAuthenticated)
{
	var props = $(node).find("props");
			
	var pURL = GetPropValue(props, 'url');
	var canAccess = GetPropValue(props, 'canAccess');
	var linkClass = GetPropValue(props, 'accessClass');
	var title = GetPropValue(props, 'title');

	var linkTitle = '';
	
	if ((linkClass == 'm') && (isUserAuthenticated == false))	
	{
		linkTitle = ('This is a members-only resource.  Members can click to log in and access.');
	}
	else	
	{
		linkTitle = ('View the &quot;' + title + '&quot; file.');
	}

	var item = ['<tr class="row"><td class="cell0 cell"><div class="link ', 
	GetPropValue(props, "type"), 
	'"><a class="ca',
	canAccess,
	' ',
	linkClass,
	'" href="',
	((pURL.length > 0) ? pURL : GetPropValue(props, 'path')),
	'" rel="',
	GetPropValue(props, "id"),
	'" title="',
	linkTitle,
	'" target="_blank">',
	title,
	'</a></div></td><td class="cell1 cell"><div class="abstract">',
	GetPropValue(props, 'abstract'),
	'&nbsp;</div></td><td class="cell2 cell"><div class="cdate" title="',
	GetPropValue(props, "creationDateTextSortable"),
	'">',
	GetPropValue(props, "creationDateShort"),
	'</div></td></tr>'];	
	
	return item.join('');
}

//\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
// Purpose:  Builds a library <div> element for a node.
// Last Revision Date:  05/20/2010
// Parameters:
//		node:  The XML element containing the properties
//		isUserAuthenticated:  A value indicating whether or not the user is authenticated
//\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
function LibraryItemBuilder(node, isUserAuthenticated)
{
	var props = $(node).find("props");
			
	var pURL = GetPropValue(props, 'url');
	var canAccess = GetPropValue(props, 'canAccess');
	var linkClass = GetPropValue(props, 'accessClass');
	var title = GetPropValue(props, 'title');
	var linkTitle = '';
	
	if ((linkClass == 'm') && (isUserAuthenticated == false))	
	{
		linkTitle = ('This is a members-only resource.  Members can click to log in and access.');
	}
	else	
	{
		linkTitle = ('View the &quot;' + title + '&quot; file.');
	}

	var item = ['<div class="library itemLib2 ', 
	GetPropValue(props, "type"), 
	'"><a class="ca',
	canAccess,
	' ',
	linkClass,
	'" href="',
	((pURL.length > 0) ? pURL : GetPropValue(props, 'path')),
	'" rel="',
	GetPropValue(props, "id"),
	'" title="',
	linkTitle,
	'" target="_blank">',
	title ,
	'</a><br />',
	GetPropValue(props, "creationDateShort"),
	'<hr /></div>'];	
	
	return item.join('');
}

//\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
// Purpose:  Builds a news <div> element for a node.
// Last Revision Date:  05/20/2010
// Parameters:
//		node:  The XML element containing the properties
//		isUserAuthenticated:  A value indicating whether or not the user is authenticated
//\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
function NewsItemBuilder(node, isUserAuthenticated)
{

	var props = $(node).find("props");
	var nodeID = GetPropValue(props, "id");
	var title = GetPropValue(props, "title");
	var excerpt = GetPropValue(props, "excerpt");
	
	var item = ['<div class="sni"><div class="headline"><a class="colorbox-if" href="', MF_RETRIEVE_URL, '?mid=', nodeID, '" title="SEPA News:  ', title, '">', title, '</a><div class="excerpt">', excerpt, '</div><div class="itemBreak" /></div>'];	
	
	return item.join('');
}

//\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
// Purpose:  Overrides the link click behavior for
// links marked as members-only or registered-user only.
// Last Revision Date:  05/20/2010
// Parameters:
//		section:  The section containing the links.
//\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
function RedirectProtectedLinksToLogin(section)
{
	if (section)	
	{		
		var _section = $(section.GetSectionSelectorJID());	
	
		// Is the user logged in?
		if (IsUserAuthenticated() == false)		
		{
			_section.find("a.r,a.m").click(function()		
			{
				ShowLogInDialogFromLinkOrRedirect(this);
				
				return false;
			});
		}
	}	
}

function AfterMultimediaItemsRetrieved(section)
{
	var jid = section.GetSectionSelectorJID();
	
	// For each of the multimedia hyperlinks, identify the hyperlinks that are audio/video.
	$(jid + " a.ca1[href$='.mp3']," + jid + " aca1[href$='.MP3']," + jid + " aca1[href$='.wmv']," + jid + " a.ca1[href$='.WMV']," + jid + " a.ca1[href$='.flv']," + jid + " a.ca1[href$='.FLV']").each(function(i, link)
	{
		var href = this.href;
		var ww = 750; // The width of the container window.
		var wh = 275; // The height of the container window.
		var pw = 200; // The width of the media player.
		var ph = 20; // The height of the media player.		
		// Index of final period.  href is guaranteed to be non-null, non-empty by the jQuery selector.
		var ip = href.lastIndexOf(".");
		
		var ext = (ip > -1) ? href.substr(ip, (href.length - ip)).toLowerCase() : "";
		
		switch (ext)
			{
				case (".flv"):
				case (".wmv"):
					{
						pw = 720;
						ph = 480;
						ww = 795;
						wh = 590;
						
						break;
					}
				default:
					{
						// Keep the defaults.
						break;
					}
			}
		
		$(link).attr(
			{
				'title': this.innerHTML,
				'href': ('/solar-tools/media-file-display.aspx?w=' + pw + '&amp;h=' + ph + '&amp;mid=' + this.rel + '&amp;width=' + ww + '&amp;height=' + wh)
			}).addClass('colorbox-if').colorbox(
			{
				width: ww,
				height: wh,
				iframe: true
			});
	});
}	


function AfterNewsItemsRetrieved(section)
{
	section.GetSectionSelector().find("a[class!='colorbox-if']").attr("target", "_blank");
	section.GetSectionSelector().find("a.colorbox-if").colorbox({width:"50%", height:"50%", iframe:true});		
}

//\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
// Purpose:  Defines a section to be retrieved with
// a specified file type, response section, etc.
// Last Revision Date:  05/20/2010
// Parameters:
//		mediaFileType:			The media file type to retrieve
//		elementName:			The element name in the XML
//		sourceElementName:		The source element in the XML
//		elementFilter:			The filter query text
//		sectionSelectorJID:		The JID for the section selector element
//		progressControlJID:		The JID for the progress control element
//		permanentContentLevel:	The permanent content level
//		minRetrieveCount:		The minimum node count to retrieve
//		iterationFunction:		The node iteration function
//\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
function RetrievalSection(mediaFileType,
elementName,
sourceElementName,
elementFilter,
sectionSelectorJID,
progressControlJID, 
permanentContentLevel,
minRetrieveCount,
iterationFunction
)
{
	// The jQuery object instance for the class instance.
	var _jQueryInstanceThis = $(this);
	
	this.GetJQueryInstance = function(){return _jQueryInstanceThis;}	
	
	// 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};
	
	// The section selector JID:
	var _sectionSelectorJID = sectionSelectorJID;
	
	this.GetSectionSelectorJID = function(){return _sectionSelectorJID};
	this.SetSectionSelectorJID = function(sectionSelectorJID){_sectionSelectorJID = sectionSelectorJID};
	
	var _sectionSelector = null;
	
	this.GetSectionSelector = function()	
	{
		if (_sectionSelector == null)		
		{
			_sectionSelector = $(_sectionSelectorJID);
		}
		
		return _sectionSelector;
	};
	
	this.SetSectionSelector = function()	
	{
		_sectionSelector = $(_sectionSelectorJID);
	};	
	
	// Instance response cache:
	var _responseCache = null;
	
	this.GetResponseCache = function(){return _responseCache};
	this.SetResponseCache = function(responseCache){_responseCache = responseCache};	
	
	// Instance XML cache:
	var _xmlCache = null;
	
	this.GetXMLCache = function()		
	{
		if (_xmlCache == null)
		{
			_xmlCache = $(this.GetResponseCache());	
		}
		
		return _xmlCache;
		
	};
	this.SetXMLCache = function(xmlCache){_xmlCache = $(xmlCache)};		
	
	var _elementFilter = elementFilter;
	
	this.GetElementFilter = function(){return _elementFilter};
	this.SetElementFilter = function(elementFilter){_elementFilter = elementFilter};	

	// Progress Control JID:
	var _progressControlJID = progressControlJID;
	
	this.GetProgressControlJID = function(){return _progressControlJID};
	this.SetProgressControlJID = function(progressControlJID){_progressControlJID = progressControlJID};

	var _progressControl = null;
	
	this.GetProgressControl = function()	
	{
		if (_progressControl == null)		
		{
			_progressControl = $(_progressControlJID);
		}
		
		return _progressControl;
	};
	
	this.SetProgressControl = function()	
	{
		_progressControl = $(_progressControlJID);
	};	
	
	// 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(){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};	
	
	var _beforeSectionXMLRetrievedEventName = 'RETRIEVAL_SECTION_BEFORE_SECTION_XML_RETRIEVE';
	this.GetBeforeSectionXMLRetrievedEventName = function(){return _beforeSectionXMLRetrievedEventName};
	this.SetBeforeSectionXMLRetrievedEventName = function(beforeSectionXMLRetrievedEventName){_beforeSectionXMLRetrievedEventName = beforeSectionXMLRetrievedEventName};
	
	var _beforeSectionXMLProcessedEventName = 'RETRIEVAL_SECTION_BEFORE_SECTION_XML_PROCESSED';
	this.GetBeforeSectionXMLProcessedEventName = function(){return _beforeSectionXMLProcessedEventName};
	this.SetBeforeSectionXMLProcessedEventName = function(beforeSectionXMLProcessedEventName){_beforeSectionXMLProcessedEventName = beforeSectionXMLProcessedEventName};
	
	var _afterSectionXMLRetrievedEventName = 'RETRIEVAL_SECTION_AFTER_SECTION_XML_RETRIEVE';
	this.GetAfterSectionXMLRetrievedEventName = function(){return _afterSectionXMLRetrievedEventName};
	this.SetAfterSectionXMLRetrievedEventName = function(afterSectionXMLRetrievedEventName){_afterSectionXMLRetrievedEventName = afterSectionXMLRetrievedEventName};
	
	var _afterSectionXMLProcessedEventName = 'RETRIEVAL_SECTION_AFTER_XML_PROCESSED';
	this.GetAfterSectionXMLProcessedEventName = function(){return _afterSectionXMLProcessedEventName};
	this.SetAfterSectionXMLProcessedEventName = function(afterSectionXMLProcessedEventName){_afterSectionXMLProcessedEventName = afterSectionXMLProcessedEventName};

	this.RetrieveXML = function()		
	{
		// Raise the _beforeSectionXMLRetrievedEventName event.
		_jQueryInstanceThis.triggerHandler(_beforeSectionXMLRetrievedEventName);	
		
		try		
		{
			var _section = this;
		
			// Retrieve the data.
			_DFServiceProxy.invokeXML("GetMediaFileList4", ("mediaFileListRequestXML=" + GetMediaFileListInstructions([_section])),
		    function(responseXML)
		    {
				if (responseXML != null)				
				{
					// Update the section response cache.
					_section.SetResponseCache($(responseXML).find(_section.GetElementFilter()));
					
					// Raise the _afterSectionXMLRetrievedEventName event.
					_section.GetJQueryInstance().triggerHandler(_afterSectionXMLRetrievedEventName);
				}			
		    },
		    function(errorMessage)
		    {
		        alert(errorMessage);
		    },
			IS_WEB_METHOD);
		}
		catch (e)
		{
			alert("There was an error in the 'RetrieveXML' function:\n\n" + e);	
		}			
	}
	
	this.ProcessXML = function()	
	{
			var xml = this.GetResponseCache();
			
			// The target array to store the intermediate item elements.
			var html = [];
			
			// Raise the _beforeSectionXMLProcessedEventName event.
			_jQueryInstanceThis.triggerHandler(_beforeSectionXMLProcessedEventName);
			
			if (xml)		
			{			
				// Retrieve the collection of source root elements.
				var nodes = $(xml).find(this.GetSourceElementName());
							
				// Proceed only if elements exist.	
				if (nodes)
				{	
					var i = 0;	
					var nodeCount = nodes.length;

					var _isUserAuthenticated = IsUserAuthenticated();
					
					while (i < nodeCount)
					{						
						// Call the iteration function for each node.
						html[i] = this.NodeIterator(nodes[i], _isUserAuthenticated);
						
						++i;
					}		
				}
			}
		
			// Raise the _afterSectionXMLProcessedEventName event with the joined array text as the first event parameter.
			_jQueryInstanceThis.triggerHandler(_afterSectionXMLProcessedEventName, [html.join('')]);
	}

	// Retrieves the section's definition.
	this.GetSectionDefintion = function()
	{			
		var mediaFileCreationDateStart = "1900-01-01T00:00:00";
		var mediaFileCreationDateStop = "2200-12-31T23:59:59";
		
		var dfcMFCDStart = $("#dfcStartCreationDate");
		var dfcMFCDStop = $("#dfcStopCreationDate");
		
		// Add the creation date filters.
		if (dfcMFCDStart.length === 1)		
		{			
			mediaFileCreationDateStart = dfcMFCDStart.val();	
		}
		
		if (dfcMFCDStop.length === 1)		
		{
			mediaFileCreationDateStop = dfcMFCDStop.val();
		}		
		
		var sd = ['<section mediaFileType="', 
		this.GetMediaFileType(), 
		('" sortDirection="desc" pageNumber="1" fileCountPerPage="'), 
		(this.GetRetrieveCount()),
		('" mediaFileCreationDateStart="'),
		mediaFileCreationDateStart,
		('" mediaFileCreationDateStop="'),
		mediaFileCreationDateStop,
		('" includePermanentContent="'),
		(this.GetPermanentContentLevel()),
		('"/>')];
		
		return sd.join('');
	};	
	
	// The function to call for each individual file parsed from the result XML.
	this.NodeIterator = iterationFunction;
}
