/**
 *******************************************
 * Object wbArticleList
 *******************************************
 * Author: Emmanuel Moreno noel@gatech.edu
 * Created 10/11/2007
 * Object uses ajax to load a list of articles into a WebBuzz page
 * Requires wbforms.js
 * Requires sarissa.js
 */

/**
 * Constructor wbArticleList();
 * @param {string} myID The ID to use for this object.  You should use a unique value so you can have multiple lists on the same page.  The id must start with a letter.
 * @param {string} site_id The WebBuzz parent site ID.
 */
function wbArticleList(myID,my_path){
	this.myID = myID;
	this.my_path = my_path;
	
	// Examine my_path to determine the current wb top directory, if any
	this.topdir = my_path.replace( new RegExp( '\/CMS_resources\/ajax.php$' ),'' );
}

/**
 * Method initialize() Initializes the object.  This should be called after the page loads.
 */
wbArticleList.prototype.initialize = function()
{
	// Grab the template from the container
	this.container=wbGetElement(this.myID+'Container');
	if( this.container != null ) {
		this.getOpts();
		this.getXML();
	}
}

/**
 * Method getXML() Retrives the Article List XML document via ajax
 */
wbArticleList.prototype.getXML = function(){
	/**
	 ****************************************
	 * Remove existing content if needed
	 ****************************************
	 */
	// Check for and remove the empty content object if it exists in the container
	var testEmpty = wbGetElement(this.myID+'EmptyContent');
	if(testEmpty!=null && testEmpty.parentNode.id == this.myID+'Container') this.container.removeChild(testEmpty);
	
	// Check for and remove the item selector if it exists in the container
	var testSelector=wbGetElement(this.myID+'CatSelect');
	if(testSelector!=null&&testSelector.parentNode.id==this.myID+'Container')this.container.removeChild(testSelector);
	
	// Check for and remove the summary list if it exists in the container
	var testSummary=wbGetElement(this.myID+'ListSummary');
	if(testSummary!=null&&testSummary.parentNode.id==this.myID+'Container')this.container.removeChild(testSummary);
	
	/**
	 **********************************************
	 * Load the "Loading" message temporary content
	 **********************************************
	 */
	this.container.appendChild(this.load_content);
	if(this.config.wbshowloading==true) this.container.style.visibility='visible';
	
	// Load all the properties into string to be posted via ajax
	var dataString = '';
	for( var prop in this.config ){
		if( dataString!='' ) dataString=dataString+'&'+prop+'='+this.config[prop];
		else dataString=prop+'='+this.config[prop];
	}
	var connect = wbAjaxObj();
	if(connect) {
		var id = this.myID;
		var config = this.config;
		connect.open("POST", this.my_path+'?mod=ajArticleList', true );
		connect.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
		connect.onreadystatechange = function()
		{
			if ( connect.readyState == 4 && connect.status == 200 ) window[id].loadXML( connect.responseXML, config );
		}
		connect.send(dataString);
	}
}

/**
 * Method getOpts() Retrieve configuration options for the object.
 * Configuration options are passed as custom attributes in the container element.
 * The container element is a <div> with an id = this.myID + 'Container'
 * The following configuration attributes are accepted:
 * - wbshowhtmllist (optional) true|false. True the object will assume the html returned via ajax will be inserted into a <ul> element with id = this.myID + ListTemplate
 * - wbshowblurb true|false True (default): the blurb will be included. False: The blurb will not be included
 * - wbShow_Body true|false True: The body content will be included.  False (default): The body content will not be included
 * - wbTitle_Limit integer (default = 20) The display word limit for the title.
 * - wbBlurb_Limit integer (default = 30) The display word limit for the blurb.
 * - wbBody_Limit integer (default = 30) The display word limit for the body.
 */
wbArticleList.prototype.getOpts=function() {
	// Set the default config items first
	this.config=new Object();
	this.config.wbsiteid=null;
	this.config.wbshowblurb=true;
	this.config.wbshowbody=false;
	this.config.wbshowthumb=true;
	this.config.wbshowempty=true;
	this.config.wbshowloading=true;
	this.config.wbtitlelimit=20;
	this.config.wbblurblimit=25;
	this.config.wbbodylimit=30;
	this.config.wbthumbwidth=100;
	this.config.wbthumbheight=75;
	this.config.wbtable='WEBBUZZ_NEWS';
	this.config.wblimit=null;
	this.config.wbstart=null;
	this.config.wbarticlepage='/news.htm';
	
	/**
	 **********************************************************************
	 * Set the object config values based on the found container attributes
	 **********************************************************************
	 */
	var attr = this.container.attributes;
	for( var i=0; i<this.container.attributes.length; i++ ){
		var attribute=this.container.attributes[i].name;
		attribute.toLowerCase(); // support for multiple browsers.  Some browsers have attributes all lower case.
		var value=this.container.attributes[i].value;
		if( attribute.match( new RegExp( '^wb' ) ) ){
			// Convert string booleans to boolean.
			switch(value){
				case 'true': value=true; break;
				case 'false': value=false; break;
			}
			this.config[attribute] = value;
		}
	}
	
	/**
	 ****************************************
	 * Prepare the category selector template
	 ****************************************
	 */
	// Check for a category selector template
	var catSelector=wbGetElement(this.myID+'CatSelect');
	if(catSelector!=null){
		this.catSelector=catSelector.cloneNode(true);
		this.catOptTemp=catSelector.options[0].cloneNode(true); // Grab the templated option
		
		this.container.removeChild(catSelector); // remove the template selector from the container
		this.catSelector.remove(0); // remove the templated option from the selector
		//alert(this.catSelector.parentNode.id);
	}
	
	/**
	 ***************************************
	 * Prepare the summary list template
	 ***************************************
	 */
	// Check to see if there is a summary list template (template for titles only, with internal links to individual list items - like a list of questions for a FAQ page...
	var listSummaryAnchor=wbGetElement(this.myID+'SummaryList');
	if(listSummaryAnchor!=null){
		// Get the summary list item template.  It should have an id == this.myID+'SummaryItemTemplate'
		this.summaryItemTemplate=wbGetElement(this.myID+'SummaryItemTemplate').cloneNode(true); // Save it as a clone of the node
		listSummaryAnchor.removeChild(wbGetElement(this.myID+'SummaryItemTemplate'));
		this.listSummaryAnchor=listSummaryAnchor.cloneNode(true);
		
		// Remove the summar list template from the container
		this.container.removeChild(listSummaryAnchor);
	}
	
	/**
	 ***************************************
	 * Prepare the empty content template
	 ***************************************
	 */
	var emptyContent=wbGetElement(this.myID+'EmptyContent');
	if(emptyContent!=null){
		// Get the summary list item template.  It should have an id == this.myID+'SummaryItemTemplate'
		this.emptyContent=emptyContent.cloneNode(true) // Save it as a clone of the node
		this.container.removeChild(emptyContent) // remove the empty content template from the container
	} else {
		// Create a default text node for empty content
		var emptyContent=document.createElement('div'); // create the element
		this.container.appendChild(emptyContent); // annend it to the container so it can be modified (ie support)
		emptyContent.id=this.myID+'EmptyContent'; // set the id
		emptyContent.appendChild(document.createTextNode('There are no articles currenly available')); // Add the text content
		this.emptyContent=emptyContent.cloneNode(true); // Save a copy of the node as the object's emptyContent
		this.container.removeChild(emptyContent); // remove the object from the container.
	}
	
	/**
	 ***************************************
	 * Prepare the main list anchor template
	 ***************************************
	 */
	var listAnchor=wbGetElement(this.myID+'ListTemplate'); // Get the html list anchor template.  The html list would have an id of this.myID+'ListTemplate'
	this.listItemTemplate=wbGetElement(this.myID+'ItemTemplate').cloneNode(true); // Get the main list item template.  It should have an id == this.myID+'ItemTemplate'
	
	// Create a version without the template image
	this.listItemTemplateNoThumb=wbGetElement(this.myID+'ItemTemplate').cloneNode(true);
	this.listItemTemplateNoThumb.innerHTML=this.listItemTemplateNoThumb.innerHTML.replace( new RegExp( '\<img(.*?)'+this.myID+'ListThumb(.*?)\>', 'gi' ), '' ); // remove the template image
	
	listAnchor.removeChild(wbGetElement(this.myID+'ItemTemplate')); // Remove the list item template from the list anchor
	this.listAnchor=listAnchor.cloneNode(true); // Clone the listAnchor as the object's list anchor template
	this.container.removeChild(listAnchor); // Remove the list template from the container
	
	/**
	 ****************************************
	 * Create the temporay "Loading" content
	 ****************************************
	 */
	// Create and style the load content div
	var load_content = document.createElement('div');
	this.container.appendChild(load_content);
	load_content.id=this.myID+'Loading';
	load_content.style.backgroundColor='#e6e6e6';
	load_content.style.padding='10px';
	load_content.style.textAlign='center';
	
	// Create and style the load content image
	var load_image=document.createElement('img');
	load_content.appendChild(load_image);
	load_image.src=this.topdir+'/CMS_images/SYS_ICONS/loading.gif';
	load_image.id=this.myID+'LoadingImg';
	load_image.style.margin='10px';
	load_image.style.cssFloat='middle';
	load_image.style.width='50px';
	load_image.style.height='50px';
	
	// Create and style the load content text
	load_content.appendChild(document.createElement('br')); // add a line break
	var loadText=document.createTextNode('...Loading...');
	load_content.appendChild(loadText);
	
	this.load_content=load_content.cloneNode(true);
	this.container.removeChild(load_content);
}

/**
 * Method loadXML() Loads the XML response into the display template
 * @param object XMLDoc The XML document.
 */
wbArticleList.prototype.loadXML=function( XMLDoc, config ) {
	// clear the temporary load content
	this.container.removeChild(wbGetElement(this.myID+'Loading'));
	
	var docElement=XMLDoc.documentElement;
	var parentNode=docElement.getElementsByTagName('article');
	var articlesAvailable=(parentNode.length>0);
	
	/**
	 ********************************
	 * Prepare the category selector
	 ********************************
	 */
	if(this.catSelector!=null){
		// Add the category selector to the container if it doesn't still exist elsewhere in the doc
		//if(wbGetElement(this.myID+'CatSelect')==null) 
		this.container.appendChild(this.catSelector);
		
		// Clear any previous content from the catSelector
		while(this.catSelector.childNodes.length>0)this.catSelector.removeChild(this.catSelector.firstChild);
		
		// Reload the catSelector
		var firstOpt = this.catOptTemp.cloneNode(true);
		this.catSelector.appendChild(firstOpt);
		firstOpt.value='';
		firstOpt.innerHTML=firstOpt.innerHTML.replace( new RegExp( '\{label\}' ), 'Select Category' );
		
		// Load the category selector with the categories in the XML doc
		var catNode=docElement.getElementsByTagName('category');
		for(var c=0;c<catNode.length;c++){
			var tempOpt = this.catOptTemp.cloneNode(true); // copy the template option
			this.catSelector.appendChild(tempOpt); // add the copy to the selection list
			
			// Update the new option's properties accordingly
			var category=catNode[c].firstChild.nodeValue;
			tempOpt.value=category;
			tempOpt.innerHTML=tempOpt.innerHTML.replace( new RegExp( '\{label\}' ), category );
			
			if(category==this.config['wbshowgroup']) tempOpt.selected=true;
		}
		// Add the onchange function to the select object
		this.catSelector.onchange=function(){
			if(this.value!=''&&this.value!=null){
				var parentID=this.id.replace( 'CatSelect','' );
				if(window[parentID].lockOnChange!=true) window[parentID].getNewGroup(this.value);
			}
		}
	}
	
	/**
	 ****************************
	 * Prepare the Summary List
	 ****************************
	 */
	if(articlesAvailable&&this.listSummaryAnchor!=null){
		// add a named anchor for the top of the list
		try {
			// this method supports IE
			var topAnchor = document.createElement('<a name="'+this.myID+'ListTop"></a>');
			this.container.appendChild(topAnchor);
		}
		catch (e) {
			// non IE browsers...
			var topAnchor = document.createElement('a');
			this.container.appendChild(topAnchor);
			topAnchor.setAttribute('name',this.myID+'ListTop');
		}
		// Add the summary list to the container if it doesn't still exist elsewhere in the doc
		//if(wbGetElement(this.myID+'SummaryList')==null) 
		this.container.appendChild(this.listSummaryAnchor);
	}
	
	/**
	 ****************************
	 * Prepare the main list
	 ****************************
	 */
	if(articlesAvailable) { // there are images assigned to this gallery
		this.container.appendChild(this.listAnchor); // Add the main list back to the container
		for( var w=0; w < parentNode.length; w++ ){
			var articleNode = parentNode[w].getElementsByTagName('id');
			var articleID = articleNode[0].firstChild.nodeValue;
			var titleNode = parentNode[w].getElementsByTagName('title');
			var title = titleNode[0].firstChild.nodeValue;
			var articleNode = parentNode[w].getElementsByTagName('id');
			var articleID = articleNode[0].firstChild.nodeValue;
			
			// Check to see if thumbs have been requested and a thumb exists.  Use templates accordingly
			var imageNode = parentNode[w].getElementsByTagName('file_id');
			var doThumb = ( config.wbshowthumb==true && parentNode[w].getElementsByTagName('file_id').length>0 );
			
			if(doThumb) var currentItem=this.listItemTemplate.cloneNode(true); // Use the template with thumbnail
			else var currentItem=this.listItemTemplateNoThumb.cloneNode(true); // Use the template with the thumbnail removed
			this.listAnchor.appendChild(currentItem); // the current list item to the list anchor
			
			// Set the id for the currentItem
			currentItem.id=this.myID+'ListItem'+articleID;
			
			// If there is a summaryList, add the current item to the summary list
			if(this.listSummaryAnchor!=null){
				// Add a named anchor to the current item
				currentItem.innerHTML='<a name="'+this.myID+articleID+'"></a>'+currentItem.innerHTML;
				
				var currentSummaryTemp=this.summaryItemTemplate.cloneNode(true); // create a copy of the item template for this item
				this.listSummaryAnchor.appendChild(currentSummaryTemp); // Add the new item to the list anchor
				currentSummaryTemp.id=this.myID+'SummaryListItem'+articleID; // change the ID
				currentSummaryTemp.innerHTML=currentSummaryTemp.innerHTML.replace( new RegExp( '\{title\}','g' ), title ); // Replace the title anchor with the title value in the innerHTML
				
				// Find the internal link in the template, and replace the value accordingly to link to the list item
				var currSumLink=wbGetElement(this.myID+'SummaryLink');
				currSumLink.id=this.myID+'SummaryLink'+articleID;
				currSumLink.href="#"+this.myID+articleID;
			}
			/** Replace the template anchors with the data provided in the current XML node */
			for(x in this.anchors){
				var anchorNode = parentNode[w].getElementsByTagName(this.anchors[x]);
				if(anchorNode!=null&&anchorNode.length>0&&anchorNode[0].firstChild!=null)currentItem.innerHTML=currentItem.innerHTML.replace( new RegExp( '\{'+this.anchors[x]+'\}','g' ), anchorNode[0].firstChild.nodeValue );
				else currentItem.innerHTML=currentItem.innerHTML.replace( new RegExp( '\{'+this.anchors[x]+'\}','g' ), '' );
			}
			
			// Update the template link properties

			
			var linkcount=1;
			var article_link_node=parentNode[w].getElementsByTagName('article_link');
			var my_link=article_link_node[0].firstChild.nodeValue;
			for(var y=0;y<document.links.length;y++){
				if(document.links[y].id==this.myID+'Link'){
					document.links[y].id=this.myID+'Link'+linkcount+'id'+articleID;
					document.links[y].href=my_link;
				}
			}
			
			// Update the thumb image properties
			if(doThumb){
				var currentThumb=wbGetElement(this.myID+'ListThumb');
				if(currentThumb!=null){
					currentThumb.id=this.myID+'ListThumb'+articleID; // Change the thumb id
					
					var image_path_node = parentNode[w].getElementsByTagName('image_path');
					currentThumb.src = image_path_node[0].firstChild.nodeValue; // Change the image source
					
					var file_caption_node = parentNode[w].getElementsByTagName('file_caption');
					if(file_caption_node.length>0&&file_caption_node[0].firstChild!=null) currentThumb.alt = file_caption_node[0].firstChild.nodeValue; // Change the image alt
					
					var image_width_node = parentNode[w].getElementsByTagName('image_width');
					if(image_width_node.length>0) currentThumb.width = image_width_node[0].firstChild.nodeValue; // Change the img width
					
					var image_height_node = parentNode[w].getElementsByTagName('image_height');
					if(image_height_node.length>0) currentThumb.height = image_height_node[0].firstChild.nodeValue; // Change the img height
				}
			}
		}
		this.container.style.visibility='visible';
	} else {
		if(this.config.wbshowempty==true){
			// Display the empty content message,
			this.container.appendChild(this.emptyContent.cloneNode(true));
		} else {
			// Remove the container completely from the page document
			this.container.parentNode.removeChild(this.container);
		}
	}
}

wbArticleList.prototype.getNewGroup=function( groupName ) {
	this.lockOnChange = true;
	
	// Remove all summary items if needed
	if(this.listSummaryAnchor!=null&&wbGetElement(this.myID+'SummaryList')!=null){
		while(this.listSummaryAnchor.childNodes.length>0) this.listSummaryAnchor.removeChild(this.listSummaryAnchor.firstChild);
		
		// If the summary list is currently contained in this.container, remove it.
		if(wbGetElement(this.myID+'SummaryList').parentNode==this.container.id) this.container.removeChild(wbGetElement(this.myID+'SummaryList'));
	}
	
	// Remove all items in the main list
	while(this.listAnchor.childNodes.length>0) this.listAnchor.removeChild(this.listAnchor.firstChild);
	
	// Update the object properties according to the new selection
	for(var prop in this.config){
		switch(true){
			case( prop.match( new RegExp( '^wbshowgroup' ) )!=null ):
				// Clear out all currently wbshowgroup values
				this.config[prop]=null;
				break;
		}
	}
	
	// Add the selected item to the showgroup
	this.config.wbshowgroup=groupName;
	
	// Retrieve the new selection
	this.getXML();
	
	this.lockOnChange = false;
}

/**
 * WbArticleList Default Config Values
 */
wbArticleList.prototype.anchors=new Array('id','title','blurb','body','newsgroup','pubstart','pubend','moddate','pubstatus','articletype','startstr','endstr','modstr','article_link','file_id','file_name','file_caption','file_credit','file_type','extension','image_path','image_width','image_height');
wbArticleList.prototype.template=null;
