//
// This contains the source code for data obtained from an RSS Feed.
//
// Object that gets feed and creates data display
//
//setup scrolling FX for gallery scroller

var imgHolder = {};

var MyFX = {
	//set some basic options, like timeout and step for scroll
	// (less means smoother scroll)
	setFXOptions: function(element,timeout,step){
		//var element=$(element);
		var element=$('#galThumbList')[0];
		element.fxoptions={
			timeout:timeout,
			step:step,
			timeoutHandler:{},
			active:false
		}

	},

	scrolLeft:function(element,step){
		//element=$(element);
		element=$('#galThumbList')[0];
		//IE RETURNS NULL SO NEED TO SET VALUE TO STRING O
		var margin=($(element).css('margin-left') != null) ? $(element).css('margin-left') : '0';
		margin=parseInt(margin.replace('px',''));
		if (margin >= 0) margin=0;
		margin=margin+4;
		$(element).css('margin-left',margin+'px');
 
		element.fxoptions.timeoutHandler=setTimeout(function(){$('#galThumbList').scrolLeft()}, 20);

	},
	
	scrolRight:function(element,step){
		//element=$(element);
		element=$('#galThumbList')[0];
		//IE RETURNS NULL SO NEED TO SET VALUE TO STRING O
		var margin=($(element).css('margin-left') != null) ? $(element).css('margin-left') : '0';
		margin=parseInt(margin.replace('px',''));
		margin=margin-4;
		
		var width = $('.gallery-item').css('width');
		width = parseInt(width.replace('px',''))+10;

		if (margin+parseInt($(element).css('width')) <= width) margin=margin+4;
		$(element).css('margin-left',margin+'px');

		element.fxoptions.timeoutHandler=setTimeout(function(){$('#galThumbList').scrolRight()}, 20);

	},
	stopScroll:function(element){
		//element=$(element);
		element=$('#galThumbList')[0];
		clearTimeout(element.fxoptions.timeoutHandler);
	}

}

//Extend element methods with our FX functions that we use for scrolling
$.fn.extend(MyFX);

function RSSContentSearch (params) {
	this.element = '';
	/*
	 *	Initializing parameters
	 */
	this.createParams = function (params) {
				this.params = new Array();
				if($('#'+params.eventsAreaId)[0]) {
					this.eventsAreaId = params.eventsAreaId;
				} else {
					alert('Error: Events Area not found\nLooking for object with id \''+params.eventsAreaId+'\'');
				}
				if($('#'+params.contentAreaId)[0]) {
					this.contentAreaId = params.contentAreaId;
				} else {
					alert('Error: Content Area not found\nLooking for object with id \''+params.contentAreaId+'\'');
				}
				if(params.loadingImage) {
					this.loadingImage = params.loadingImage;
				}
				if(params.feeds) {
					//this.feed = params.feed;
					var feedlist = new Object(params.feeds);
					this.feeds = [];
					for (var key in feedlist) {
						this.feeds.push(feedlist[key]);
					}
				} else {
					alert('Error: Feed not found in initilization\nInclude feeds in initilization function');
				}
				this.params = params;
				this.itemsPerPage = params.itemsPerPage;				
				this.sitepath = params.sitepath;
				this.uniqueid = (params.uniqueid != undefined) ? params.uniqueid : 0;
				this.themeURLS = params.themeURLS;
				this.params.google = params.google;
				this.display = (params.display != undefined) ? params.display : 'column';
				this.month = (params.month != undefined) ? params.month : '';
				this.day = (params.day != undefined) ? params.day : '';
				this.year = (params.year != undefined) ? params.year : '';
				this.keyword = (params.keyword != undefined) ? params.keyword : '';
				this.showsearch = (params.showsearch != undefined) ? params.showsearch : true;
				this.showview = (params.showview != undefined) ? params.showview : true;
				this.showsort = (params.showsort != undefined) ? params.showsort : true;
				this.shownav = (params.shownav != undefined) ? params.shownav : true;
				this.showcount = (params.showcount != undefined) ? params.showcount : true;				
				this.showmonths = (params.showmonths != undefined) ? params.showmonths : false;
				this.showimage = (params.showimage != undefined) ? params.showimage : true;
				this.showtitle = (params.showtitle != undefined) ? params.showtitle : true;
				this.showsubtitle = (params.showsubtitle != undefined) ? params.showsubtitle : true;
				this.showdate = (params.showdate != undefined) ? params.showdate : true;
				this.showtype = (params.showtype != undefined) ? params.showtype : true;
				this.showdesc = (params.showdesc != undefined) ? params.showdesc : true;
				this.showtheme = (params.showtheme != undefined) ? params.showtheme : true;
				this.showauthor = (params.showauthor != undefined) ? params.showauthor : true;				
				this.showkeywords = (params.showkeywords != undefined) ? params.showkeywords : true;
				this.lightboxdisplay = (params.lightboxdisplay != undefined) ? params.lightboxdisplay : true;
				this.galleryscroller = (params.galleryscroller != undefined) ? params.galleryscroller : true;
				this.showtooltips = (params.showtooltips != undefined) ? params.showtooltips : false;
				this.showfeeds = (params.showfeeds != undefined) ? params.showfeeds : false;
				//test to see if Prototip inlcuded - can't show tips otherwise
				try {
					//if (Prototip == undefined) this.showtooltips = false;
				} 
				catch(e){this.showtooltips = false;}
				if (!this.showdate)
					this.sort = (params.sort != undefined) ? params.sort : 'title';
				else
					this.sort = (params.sort != undefined) ? params.sort : 'date';
					
				this.contentAreaNode = $('#'+this.contentAreaId)[0];			
				this.eventsAreaNode = $('#'+this.eventsAreaId)[0];
			}

	this.createLoading = function() {
				var loadingId = this.params.eventsAreaId;
				$('#'+loadingId)[0].innerHTML = ''; //clear current contents
				var loadingNode = $('#'+loadingId)[0];
				var loadingImage = this.params.loadingImage;
				var html = '';

				var loadingNode = document.createElement('div');
				loadingNode.id = "items-loading";
				if(loadingImage) {
					html = '<div class="loading">'+
							'<img src="'+this.sitepath+'/'+this.loadingImage+'" />'+
							'</div>';
				} else {
					html = 'Loading...';
				}
				loadingNode.innerHTML = html;
				var contentParentNode = this.contentAreaNode.parentNode;
				var contentFirstChild = this.contentAreaNode.firstChild;
				if(document.all) {
					this.contentAreaNode.insertBefore(loadingNode, contentFirstChild);
				} else {
					contentParentNode.insertBefore(loadingNode, this.contentAreaNode);
				}
				this.loadingNode = loadingNode;
			}
	
	this.loadFeedData = function() {
			//get data feed
			for (var divcnt=0;divcnt<this.feeds.length;divcnt++) {
				if (this.params.google)
					var obj = new AjaxRequestGoogle();
				else
					var obj = new AjaxRequest();
				obj.rss = this.feeds[divcnt];
				obj.count = this.uniqueid+divcnt;
				obj.init();
			}

			/* check status of data retrieval */
			this.checkStatus();
	}
	
	this.checkStatus = function() {
		var self = this;
		var complete = true;
		for (x=0;x<this.feeds.length;x++) {
		   if (statusobj[x+this.uniqueid] == "running") {
			   complete = false;
			   break;
		   }
		}
		if (!complete) {
			setTimeout(function() {self.checkStatus()}, 200); /* check status every 2 seconds */
		} else {
			//store data 
			var feedData = [];
			x = 0;
			var feedlist = new Object(this.params.feeds);
			for (var key in feedlist) {
				if (this.feedkey == undefined) this.feedkey = key;
				feedData[key] = this.parseItems(xhrs[x+this.uniqueid]);     /* article data       */
				x++;
			}
			
			this.feedData = feedData;
			this.itemData = feedData[this.feedkey];
			this.limit = this.itemsPerPage;
			this.filterdata = this.itemData;

			setTimeout(function(){self.startBuild()},200);
		}
	}

	/*
	*	Initilizes and creates items to send back
	*/
	this.parseItems = function(items) {
				for (var i = 0; i < items.length; i++) {
					/* Getting standar information */
					items[i].byline = (items[i].byline != undefined) ? this.parseTheme(items[i].byline) : '';
					items[i].itemlink = ( items[i].read_more_url ) ? items[i].read_more_url : items[i].linkurl;
					items[i].theme = (items[i].theme != undefined) ? this.parseTheme(items[i].theme) : '';
					items[i].themes = (items[i].theme != undefined) ? items[i].theme : '';
					items[i].type = (items[i].type != undefined) ? items[i].type : '';
					items[i].keywords = (items[i].keywords != undefined) ? items[i].keywords : '';
					items[i].otherCategories = this.parseTheme(items[i].otherCategories);
				
				}
				return items;
			}
	
	this.parseTheme = function(themes) {
				if(themes != undefined) {
					var newThemes = themes.split(',');
					for(var i=0; i<newThemes.length; i++) {
						newThemes[i] = newThemes[i].replace(/^\s+|\s+$/g,"");
					}
					return newThemes;
				} else {
					return false;
				}
		}
			
	/*
	 *	Initialization function - only looking for 1 feed
	 */
	this.init = function (params) {
				/* initializing params  */
				this.createParams(params);
				/*display loading image */
				this.createLoading();
				/* get calendar data */
				this.loadFeedData();
		}
	
/* Run initialization function */
	this.init(params);

	this.createInitialHTML = function() {
			var self = this;
			
			/* main area events are displayed */
			var splashListing = document.createElement('div');
			splashListing.id = "splash-listing";
			this.eventsAreaNode.appendChild(splashListing);    /* apply event area */
			
			/* store for future use in this function */
			this.nodeSplashListing = splashListing;
		}

	this.searchData = function(page) {
			page = (page != undefined) ? page : 1;
			var newfilter = [], j=0;
			/* setup object names */
			var lastClass = '';
			
			for(i=0; i<this.itemData.length; i++) {
				var itemDetail = this.itemData[i];
				/* add highlighting */
				cont=true;
				if (cont) {				
					newfilter[j] = [];
					for (var key in itemDetail) {
						newfilter[j][key] = itemDetail[key];
					}
					j++;
				}
			}
			this.filterdata = newfilter;

			this.viewData(page);
		}

	this.viewData = function(page) {
			var self = this;
			this.page = page;
			var html = document.createElement("div");
			var lastClass = '';
			html.className = "item-detail";
			html.id = "galformat";
			//add pagination if not gallery scroller
			if (this.filterdata.length > 0) {
				//image nav list
				this.imagelist = [];
				
				var outerdiv = document.createElement("div");
				outerdiv.id = "galOContainer";
					var table = document.createElement("div");
					table.id = "galContainer";
					table.className = "galContainer";
					this.galContainer = table;
					if (!this.lightboxdisplay) {
							var divimg = document.createElement("div");
							//divimg.id = "lightbox";
							divimg.className = "galImgContainer";
							this.imgcontainer = divimg;
						table.appendChild(divimg);
							var divimg = document.createElement("div");
							divimg.className = "galAltText";
							this.imgaltcontainer = divimg;
						table.appendChild(divimg);
					}
						var htmld = document.createElement("div");
						htmld.className = 'galThumbList';
						htmld.id = 'galThumbList';
						this.galItemContainer = htmld;
					var firstimage = 'notfound';
					var start = this.limit * (this.page - 1);
					var limit = this.limit + start;
					limit = (limit > this.filterdata.length) ? this.filterdata.length : limit;
					var k=1;
					for(var i=start; i<limit; i++) {
						var itemDetail = this.filterdata[i];
						lastClass = (lastClass == 'even') ? 'odd' : 'even';
						if (itemDetail.featureimage != undefined && itemDetail.featureimage != '') {
							htmld.appendChild(this.createArticleHTMLGallery(itemDetail, i));
							if (firstimage == 'notfound' && !this.lightboxdisplay) {
								var imgx = document.createElement("img");
								imgx.src = itemDetail.featureimage;
								imgx.className = "item-image-large";
								this.imgcontainer.innerHTML = '';
								this.imgcontainer.appendChild(imgx);
								this.imgaltcontainer.innerHTML = itemDetail.description;
								firstimage = 'found';
								this.currimg = imgx;
							}
						}
					}
					table.appendChild(htmld);
				//determine whether to use standard div or scroller div
				if (!this.galleryscroller) 
					html.appendChild(table);
				else {
					if ($('#arrowLeft') != undefined) {
						$('#arrowLeft')[0].onmouseover = function(){
							$('#galThumbList').scrolLeft();
						}
						$('#arrowLeft')[0].onmouseout = function(){
							$('#galThumbList').stopScroll();
						}
					}
					if ($('#arrowRight') != undefined) {
						$('#arrowRight')[0].onmouseover = function(){
							$('#galThumbList').scrolRight();
						}
						$('#arrowRight')[0].onmouseout = function(){
							$('#galThumbList').stopScroll();	
						}
					}
					outerdiv.appendChild(table);
						var arrowl = document.createElement("div");
						arrowl.className = "arrow-left";
						arrowl.innerHTML = "&nbsp;";
						arrowl.onmouseover = function(){
							$('#galThumbList').scrolLeft();
						}
						arrowl.onmouseout = function(){
							var thmblist = $('#galThumbList');
							thmblist.stopScroll();
						}
					html.appendChild(arrowl);
					
					html.appendChild(outerdiv);
					
						var arrowl = document.createElement("div");
						arrowl.className = "arrow-right";
						arrowl.innerHTML = "&nbsp;";
						arrowl.onmouseover = function(){
							var thmblist = $('#galThumbList');
							thmblist.scrolRight();
						}
						arrowl.onmouseout = function(){
							var thmblist = $('#galThumbList');
							thmblist.stopScroll();
						}
					html.appendChild(arrowl);
					
				}
			}				
			this.nodeSplashListing.innerHTML = '';
			this.nodeSplashListing.appendChild(html);
			$(function() {
				$('#galformat .item-image').lightBox({fixedNavigation:true});
			});
			//if (this.galleryscroller) this.scrollmsg();
		}

	this.createArticleHTMLGallery = function(itemDetail, imgnum) {
			var self = this;
			var imgthumb = itemDetail.featureimage;
			var thumb = (itemDetail.thumbnail != undefined) ? itemDetail.thumbnail : imgthumb.substr(0,imgthumb.length-4)+'_thumb'+imgthumb.substr(imgthumb.length-4,4);
			
			var html = document.createElement("div");
			//html.id = 'galID0';
			html.id = "item-detail";
			html.className = "gallery-item";
				var span = document.createElement("span");
				var htmls = '';
				htmls +=    '<div class="item-heading">';
				if (this.showsubtitle)
					htmls +=    '<div class="item-subtitle">'+((itemDetail.subtitle != undefined) ? itemDetail.subtitle : '') +'</div>';
				if (itemDetail.read_more_url)
					itemlink = '<a href="'+itemDetail.itemlink+'">'+itemDetail.title+'</a>';
				else
					if (itemDetail.read_more_label)
						itemlink = '<a href=\''+itemDetail.linkurl+'\' target=\'_new\'>'+itemDetail.title+'</a>';
					else
						itemlink = itemDetail.title; 
				if (this.showtitle)
					htmls +=    '<div class="item-title">'+itemlink+'</div>';
				htmls +=    '<div id="item-date-type">';
				sep = '';
				if (this.showtype)
					htmls += '<div class="item-type">'+((itemDetail.type != undefined && itemDetail.type != '') ? (sep+itemDetail.type) : '')+'</div>';
				htmls += '</div>';
				span.innerHTML = htmls;
			html.appendChild(span);
				var imagediv = document.createElement("a");
				imagediv.className = "item-image ";
				imagediv.href = imgthumb;
					var image = new Image(); //preload large image
					image.src = itemDetail.featureimage;
					var thimage = new Image();
					thimage.src = thumb; //preload thumb
					var imgx = document.createElement("img");
					imgx.className=""; //reflect ropacity60"; //
					imgx.largeimg = imgthumb;
					imgx.src = thumb;
					imgx.title = itemDetail.title;
					imgx.setAttribute("alt",itemDetail.description);
					if (this.showtooltips) {
						imgx.onmouseover = function() { 
							new Tip(('<strong>'+itemDetail.title+'</strong><br />'+itemDetail.description+'<div class="img_more">Click Image for more info...</div>'), 
								BALLOON, true, 
								BALLOONIMGPATH,(self.sitepath+'tip_balloon/'), 
								ABOVE, true, 
								OFFSETX, -17,
								WIDTH, 200,
								FADEIN, 600, 
								FADEOUT, 600)
							};
						imgx.onmouseout = function() {UnTip()}; 
					}
					imgx.rel=imgnum;
					
					var titlearea = document.createElement("div");
					titlearea.id = "title-area";
						var divtitle = document.createElement("div");
						divtitle.className = "title";
						divtitle.innerHTML = itemDetail.title;
						this.imagetitle = divtitle;
					titlearea.appendChild(divtitle);
						var divtitle = document.createElement("div");
						divtitle.className = "summary";
						divtitle.innerHTML = itemDetail.description;
						this.imagesummary = divtitle;
					titlearea.appendChild(divtitle);
						var divtitle = document.createElement("div");
						divtitle.className = "byline";
						divtitle.innerHTML = (itemDetail.byline != undefined) ? itemDetail.byline : '';
						this.imagebyline = divtitle;
					titlearea.appendChild(divtitle);
						var divtitle = document.createElement("div");
						divtitle.className = "subtitle";
						if (itemDetail.subtitle != undefined) {
							if (itemDetail.subtitle.substr(0,4) == 'http')
								divtitle.innerHTML = "<a href='"+itemDetail.subtitle+"'>urllink</a>";
							else
								divtitle.innerHTML = itemDetail.subtitle;
						} else 
							divtitle.innerHTML = '';
						this.imagesubtitle = divtitle;
					titlearea.appendChild(divtitle);					
					imgHolder[imgthumb] = titlearea;
					this.imagelist.push(imgx);
				imagediv.appendChild(imgx);
			html.appendChild(imagediv);
				var div = document.createElement("div");
				div.className = "item-additional";
				if (this.showtheme) {
					var divadd = document.createElement("div");
					divadd.className = "item-themes";
					if(itemDetail.theme.length) {
						divadd.innerHTML = '<strong>Themes:</strong> '+themes;	
					}
					div.appendChild(divadd);
				}
				if (this.showauthor) {
					var divadd = document.createElement("div");
					divadd.className = "item-author";
					divadd.innerHTML = ((itemDetail.byline != '') ? (itemDetail.byline) : '');
					div.appendChild(divadd);
				}
				if (this.showkeywords){
					var divadd = document.createElement("div");
					divadd.className = "item-keywords";
					divadd.innerHTML = ((itemDetail.keywords != '') ? (itemDetail.keywords) : '');
					div.appendChild(divadd);
				}
			html.appendChild(div);
			return html;
		}
		
	this.removeLoading = function() {
			changeOpac(100,this.contentAreaNode);
			this.loadingNode.style.display = 'none';
		}

	this.displayLoading = function() {
			changeOpac(40,this.contentAreaNode);
			this.loadingNode.style.display = 'block';
		}
	
	this.startBuild = function() {
			this.sortdir = 'd'; //default sort value - date is default
			this.filterdata = this.itemData;
			this.createInitialHTML();
			this.searchData(1);
			this.removeLoading();
			this.element = $('#galThumbList');
			this.element.setFXOptions(20,4);
		}
}
//google.load("feeds", "1");