/*

FamilyLife Article Listing - Source code
Version: beta

This contains the source code for the Broadcast Listing and Search. 
Pulling from Kintera Sphere RSS feeds
*/
var sitepath = $('articleSearch').getAttribute('sitepath');
var statusobj = [];
var xhrs = [];
var itemsPerPage = $('articleSearch').getAttribute('itemsperpage');
var FLTSearch = []; /* all results stored here */
/*global array foy autocomplete guest list */
var GuestList = [];

/* dynamic rss ajax call - based on rss feed */
function AjaxRequest()
      {
	  this.count = 0;
	  this.rss = "";
      this.Method = "GET";//OR "POST" 
      this.Async = true; //OR false (asynchronous or synchronous call) 
      this.init = function() {
		  this.request = new getXMLHttp();
		  if (this.request) {
			this.request.onreadystatechange=this.handleResponse;
			//we will develope this.handleResponse function in step 3 
			this.request.open(this.Method, this.rss , this.Async);
			this.request.send(null);
		}
	  }
	  var self = this;
  	  this.handleResponse = function() {
			if (self.request.readyState == 1) { /* Not Loaded yet */ }
			if (self.request.readyState == 4) { 
				if (self.request.status == 200) { // Loaded
						var xmldoc = self.request.responseXML;
						var root_node = xmldoc.getElementsByTagName("item");
						var filter = parseRSSBroadcast(root_node);
						xhrs.push(filter);
					    statusobj.splice(self.count,1); /* remove status */
						delete self.request;
				} else {
					alert('There was a problem with the request. '+self.request.status);
				}
			}
	   }
}
/* dynamic rss google call - based on passed rss feed */
function AjaxRequestGoogle() {
		this.count = 0;
		this.rss = "";
		this.google = google;
		/* Setting up google feeds */
		this.init = function() {
			this.google.load("feeds", "1");
			var feed = new this.google.feeds.Feed(this.rss);
			feed.setNumEntries(3000);
			feed.setResultFormat(this.google.feeds.Feed.XML_FORMAT);
			feed.load(this.handleresponse);
		}
		var self = this;
		this.handleresponse = function(result) {
			if (!result.error) {
				var root_node = result.xmlDocument.getElementsByTagName("item");
				var filter = parseRSSBroadcast(root_node);
				xhrs.push(filter);
				statusobj.splice(self.count,1); /* remove status */
				//if(!root_node.length) {	setTimeout('ArticleReload(self.count);', 3000);}
			} else {
				//alert(result.error.message + ": " + result.error);
				setTimeout('ArticleReload('+self.count+');', 500);
			}
		}
}
/* if google fails - retry */
function ArticleReload(divcnt) {
	var obj = new AjaxRequestGoogle();
	obj.rss = $('chk'+divcnt).getAttribute('rss');		
	obj.init();
}
function parseRSSBroadcast( XMLNode ) {
	var XMLItem = new Array();

	for (i=0; XMLNode.length>i; i++)
	{
		var dayval = '', daylen = 0;
		XMLItem[i] = new Array();
		
		for (k=0; XMLNode[i].childNodes.length>k; k++)
		{
			if(XMLNode[i].childNodes[k].firstChild != null) {
				 switch(XMLNode[i].childNodes[k].tagName) {
					 case "link" : XMLItem[i]["linkurl"] = XMLNode[i].childNodes[k].firstChild.data;
									break;
					 case "description" : XMLItem[i]["description"] = (XMLNode[i].childNodes[k].firstChild.data) ? XMLNode[i].childNodes[k].firstChild.data : "x";
									break;
					 case "title" :  XMLItem[i]["title"] = XMLNode[i].childNodes[k].firstChild.data;
									XMLItem[i].title = XMLItem[i].title.replace(/\\\"/gi,'"');	/* replace additional rss tags */
									break;
					 case "pubDate" : XMLItem[i]["date"] = new Date(XMLNode[i].childNodes[k].firstChild.data);
									break;
					 case "k:subtitle" :
					 case "subtitle" : XMLItem[i]["group"] = XMLNode[i].childNodes[k].firstChild.data;
									XMLItem[i].group = XMLNode[i].childNodes[k].firstChild.data.replace(/\(Day \d+? of \d+?\)/g,""); /* remove day # of # */
									XMLItem[i].group= XMLItem[i].group.replace("<strong> Series Title:</strong>",""); /* remove html */
									dayval = XMLNode[i].childNodes[k].firstChild.data.search(/\(Day \d+? of \d+?\)/);
									daylen = dayval.length;
									XMLItem[i]["groupday"] = ( dayval > 0) ? XMLNode[i].childNodes[k].firstChild.data.match(/\(Day \d+? of \d+?\)/g):'';
									XMLItem[i]["groupdaycount"] = (dayval > 0) ? XMLNode[i].childNodes[k].firstChild.data.substr(dayval, daylen).match(/\d+?/) : 1;
									break;
					 case "k:byline" :
					 case "byline" : XMLItem[i]["guests"] = XMLNode[i].childNodes[k].firstChild.data;
									break;
					
				}
			} else {
				 switch(XMLNode[i].childNodes[k].tagName) {
					 case "link" : XMLItem[i]["linkurl"] = "";
									break;
					 case "description" : XMLItem[i]["description"] = "x";
									break;
					 case "title" :  XMLItem[i]["title"] = "";
									break;
					 case "pubDate" : XMLItem[i]["date"] = new Date();
									break;
					 case "k:subtitle" :
					 case "subtitle" : XMLItem[i]['group'] = "";
									XMLItem[i]['groupday'] = "";
									XMLItem[i]['groupdaycount'] = 1;
									break;
					 case "k:byline" :
					 case "byline" : XMLItem[i]["guests"] = "";
									break;
				 }
			}
		 }
	}
	
	return XMLItem;
}


/* passed are the google filter array, the archive filter array and the div of where the input field values are retrieved */
function filterArticles(filter, div) {

	//var filter = prevfilter.concat(currfilter); /* add current year array onto archive array */
	var filterGuest = []; /* clear guestfilter array since we will be rebuilding it */
	var currentDate = new Date();
	$(div).innerHTML='Creating List of Articles... <img src="'+sitepath+'/loading.gif" />';		
	var newfilter = [], j=0, pagecnt=1;
	/* setup object names */
	var objectm = div+'month';
	var objectd = div+'day';
	var objecty = div+'year';
	var objectg = div+'guests';
	var objectk = div+'keywords';
	/* get values */
	var passmonth = ($(objectm).selectedIndex > 0) ? $(objectm).value : 0;	
	var passday = ($(objectd).selectedIndex > 0) ? $(objectd).value : 0;	
	var passyear = ($(objecty).selectedIndex > 0) ? $(objecty).value : 0;	
	var passguest = ($(objectg).value != '') ? $(objectg).value : "";		
	var passkeyword = ($(objectk).value != '') ? $(objectk).value : "";	

	for (i=0;i<filter.length;i++) {
		cont=true;
		if (filter[i].description == undefined) filter[i].description = ""; /* test for blank description */
		if (passmonth != 0 && passmonth != (filter[i].date.getMonth()+1)) cont=false;
		if (passday != 0 && passday != filter[i].date.getDate()) cont=false;
		if (passyear != 0 && passyear != (filter[i].date.getFullYear())) cont=false;
		if (passguest != "" && filter[i].guests.toLowerCase().indexOf(passguest.toLowerCase()) == -1) cont=false;
		if (passkeyword != "" &&
			(filter[i].group.toLowerCase().indexOf(passkeyword.toLowerCase()) == -1) && 
			(filter[i].title.toLowerCase().indexOf(passkeyword.toLowerCase()) == -1) &&
			(filter[i].description.toLowerCase().indexOf(passkeyword.toLowerCase()) == -1)) cont=false;
		if (cont) {
			newfilter[j] = new Array();
			newfilter[j].linkurl = filter[i].linkurl;
			newfilter[j].title = filter[i].title;
			newfilter[j].date = new Date(filter[i].date);
			newfilter[j].description = filter[i].description;
			newfilter[j].guests = filter[i].guests;
			newfilter[j].group = filter[i].group;
			newfilter[j].groupday = filter[i].groupday;
			newfilter[j].groupdaycount = filter[i].groupdaycount;
			newfilter[j].pagecount = pagecnt;
			if ((j+1)/pagecnt==itemsPerPage) pagecnt++; /* add 1 to page count every 10 records */

			/* add highlighting */
			if (passguest != "") {
				newfilter[j].guests = this.doHighlight(newfilter[j].guests, passguest,'','');
			}
			if (passkeyword != "") {
				newfilter[j].group = this.doHighlight(newfilter[j].group, passkeyword,'','');
				newfilter[j].title = this.doHighlight(newfilter[j].title, passkeyword,'','');
				newfilter[j].description = this.doHighlight(newfilter[j].description, passkeyword,'','');
			}
			j++;
		}
		var guests = filter[i].guests.replace("<strong>Guests Include:</strong> ","");
		var filterg = guests.split(",");
		if (filterg.length > 0) {
			for (s=0;s<filterg.length;s++) {
				/* check to see if guest in array already */
				if (filterGuest.indexOf(trim(filterg[s])) == -1) {
					filterGuest.push(trim(filterg[s]));
				}
			}
		} else {
			/* check to see if guest in array already */
			if (filterGuest.indexOf(trim(guests)) == -1) {
				filterGuest.push(trim(guests));
			}
		}
	}
	var newfilterdata = new Array(newfilter, filterGuest);
	return newfilterdata;
}

/* name of highlevel filter array passed, the actual name, div the data will return to and the pagecount to display */
function displayFilterData(filter, filtername, div, pagecnt) {
	var prevgroup='', filterItemContent='', itemstart=-1, itemcount=-1;
	var prevbtn = "<img src='"+sitepath+"/arrow_gray_left.gif'> prev";
	var nextbtn = "next <img src='"+sitepath+"/arrow_gray.gif'>";
	var firstbtn = "<img src='"+sitepath+"/arrow_gray_left.gif'><img src='"+sitepath+"/arrow_gray_left.gif'>&nbsp;first";
	var lastbtn = "last&nbsp;<img src='"+sitepath+"/arrow_gray.gif'><img src='"+sitepath+"/arrow_gray.gif'>";

	/* sort descending - put all articles in title order */
	filter.sort(function (a, b){
				a = a['title'];
				b = b['title'];
				if (a>b) return 1;
				if (a <b) return -1;
				return 0; } );
	
	/* remove duplicate articles */
	filter = removeDups(filter);

	filterItemContent += '<div id="'+div+'title" class="searchsummary"></div>';
	filterItemContent += '<div id="'+div+'moredata" class="moredata">';
	filterItemContent += '<table cellpadding=0 cellspacing=0 class="'+div+'moredatalr" width="100%"><tr>';
	filterItemContent += '<td id="'+div+'morecount" class="morecount" align="left"></td>';
	filterItemContent += '<td id="'+div+'moredatafirst" class="moredatafirst" align="right"></td>';
	filterItemContent += '<td id="'+div+'moredatal" class="moredatal" align="right"></td>';
	filterItemContent += '<td id="'+div+'moredatar" class="moredatar" align="right"></td>';
	filterItemContent += '<td id="'+div+'moredatalast" class="moredatalast" align="right"></td>';
	filterItemContent += '</tr></table></div>';
	if (filter.length > 0) {
		var pstart = (pagecnt*itemsPerPage)-itemsPerPage;
		var pend = ((pagecnt*itemsPerPage) < filter.length) ? (pagecnt*itemsPerPage) : filter.length;

		if (pagecnt > 1) {
			prevbtn = '<a href="javascript:displayFilterData('+filtername+', \''+filtername+'\', \''+div+'\', '+(pagecnt-1)+')"><img src="'+sitepath+'/arrow_blue_left.gif"/> prev </a>'
			firstbtn = '<a href="javascript:displayFilterData('+filtername+', \''+filtername+'\', \''+div+'\', 1)"><img src="'+sitepath+'/arrow_blue_left.gif"/><img src="'+sitepath+'/arrow_blue_left.gif"/>&nbsp;first</a>'
		}
		if ((filter.length/itemsPerPage) > pagecnt) {
			nextbtn = '<a href="javascript:displayFilterData('+filtername+', \''+filtername+'\', \''+div+'\', '+(pagecnt+1)+')"> next <img src="'+sitepath+'/arrow_blue.gif"/> </a>'
			lastbtn = '<a href="javascript:displayFilterData('+filtername+', \''+filtername+'\', \''+div+'\', '+Math.ceil((filter.length-7)/itemsPerPage)+')">last</a>&nbsp;<img src="'+sitepath+'/arrow_blue.gif"/><img src="'+sitepath+'/arrow_blue.gif"/>'			
		}
		
		filterItemContent += '<br /><div id="summarydata">';		
		for (i=pstart;i<pend;i++) {
			filterItemContent += buildContent(prevgroup, filter[i]);
			if (prevgroup != filter[i].group && filter[i].group != null) {
				prevgroup = filter[i].group;
			}
		}
		filterItemContent += '</div>';		
		filterItemContent += '<div id="'+div+'moredatab" class="moredata"></div>';
	} else {
		filterItemContent += "<p><h4>No articles found matching specified filter criteria!</h4></p>"
	}
	$(div).innerHTML=writeOutput(filterItemContent);
	$(div+"moredatafirst").innerHTML = firstbtn;
	$(div+"moredatalast").innerHTML = lastbtn;
	$(div+"moredatal").innerHTML = prevbtn;
	$(div+"moredatar").innerHTML = nextbtn;
	var enditemcount = (itemcount>=0) ? (itemcount+1) : 0
	$(div+'morecount').innerHTML = (pstart+1) + " to " + pend + " of " + filter.length;
	var searchcriteria = "";
	if (($(div+'month').value != "") || ($(div+'day').value != "") || ($(div+'year').value != "")) {
		searchcriteria += "Date: <span class='searchsummarydata'>"
		searchcriteria +=  ($(div+'month').value != "") ? $(div+'month').value : "--";
		searchcriteria += "/";
		searchcriteria +=  ($(div+'day').value != "") ? $(div+'day').value : "--";
		searchcriteria += "/";				
		searchcriteria +=  ($(div+'year').value != "") ? $(div+'year').value : "----";
		searchcriteria += "</span>";				
	}
	if ($(div+'guests').value != "")
		searchcriteria += " Guests: <span class='searchsummarydata'>" + $(div+'guests').value + "</span>";
	if ($(div+'keywords').value != "")
		searchcriteria += " Keywords: <span class='searchsummarydata'>" + $(div+'keywords').value + "</span>";
	if (searchcriteria =="") searchcriteria = "All";
	$(div+"title").innerHTML = "<span class='searchsummarytitle'>Search Criteria:</span>"+searchcriteria;
	if ($(div+'moredatab')) $(div+'moredatab').innerHTML = $(div+'moredata').innerHTML;
}
/* builds content to be written */
function buildContent(prevgroup, filter) {
	var content = "";
	//subtitle matches summary
	//if (prevgroup != filter.group && filter.group != null) {
	//	content += "<br /><h1>"+filter.group+"</h1><br />";
	//}
	content += "<a class='btitle' href='"+filter.linkurl+"'>"+filter.title+"</a>&nbsp;<span class='bdate'>"+formatdate(filter.date)+"</span>&nbsp;<span class='bdays'>"+filter.groupday+"</span><br />";
	content += "<div class='bsummary'>"+filter.description+"</div>";
	content += "<div class='bguests'>"+filter.guests+"</div>";
	return content;
}

/* write's output data */
function writeOutput(content) {
	content = "<div id='articleResults'><p>"+content+"</p></div>";
	return content;
}

function formatdate(d) {
	return (d.getMonth()+1)+'/'+d.getDate()+'/'+d.getFullYear();
}
function removeDups(filter) {
	var prevtitle = '';
	var reccnt = 0;
	var titlecnt = filter.length;
	while (reccnt < titlecnt) {
		var currtitle = filter[reccnt].title;
		if (currtitle == prevtitle) {
			filter.splice(reccnt,1); /* remove dup */
			titlecnt--;
		} else {
			reccnt++;
		}
		prevtitle = currtitle;
	}
	
	return filter;
}

function rebuildGuestList(filter) {
	var prevguest = '';
	var reccnt = 0;
	var guestcnt = filter.length;

	filter.sort(function (a, b){
			if (a>b) return 1;
			if (a <b) return -1;
			return 0; } );

	while (reccnt < guestcnt) {
		var currguest = filter[reccnt];
		if (currguest == prevguest) {
			filter.splice(reccnt,1); /* remove dup */
			guestcnt--;
		} else {
			reccnt++;
		}
		prevguest = currguest;
	}
	return filter;
}
		

function resetArticles(){
	$('articleSearchmonth').selectedIndex=0;
	$('articleSearchday').selectedIndex=0;
	$('articleSearchyear').selectedIndex=0;
	$('articleSearchguests').value="";
	$('articleSearchkeywords').value="";
	$('articleSearch').innerHTML = '';
}

function doHighlight(bodyText, searchTerm, highlightStartTag, highlightEndTag) 
{
  // the highlightStartTag and highlightEndTag parameters are optional
  if ((!highlightStartTag) || (!highlightEndTag)) {highlightStartTag = "<font style='color:blue; background-color:yellow;'>";highlightEndTag = "</font>";}
  
  // find all occurences of the search term in the given text and add some "highlight" tags to them (we're not using a
  // regular expression search, because we want to filter out matches that occur within HTML tags and script blocks, so
  // we have to do a little extra validation)
  var newText = "",i = -1,lcSearchTerm = searchTerm.toLowerCase(),lcBodyText = bodyText.toLowerCase();
  while (bodyText.length > 0) {
    i = lcBodyText.indexOf(lcSearchTerm, i+1);
    if (i < 0) {
      newText += bodyText;
      bodyText = "";
    } else {
      // skip anything inside an HTML tag
      if (bodyText.lastIndexOf(">", i) >= bodyText.lastIndexOf("<", i)) {
        // skip anything inside a <script> block
        if (lcBodyText.lastIndexOf("/script>", i) >= lcBodyText.lastIndexOf("<script", i)) {
          newText += bodyText.substring(0, i) + highlightStartTag + bodyText.substr(i, searchTerm.length) + highlightEndTag;
          bodyText = bodyText.substr(i + searchTerm.length);
          lcBodyText = bodyText.toLowerCase();
          i = -1;
        }
      }
    }
  }
  
  return newText;
}

function getUrlVal( name ){
	name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
	var regexS = "[\\?&]"+name+"=([^&#]*)";
	var regex = new RegExp( regexS );
	var results = regex.exec( window.location.href );
	if( results == null )
		return "";
	else
		return results[1];
}

function buildArticleList() {
	xhrs = []; /* clear old article array */
	$('articleSearch').innerHTML='Building List of Articles... <img src="'+sitepath+'/loading.gif" />';	
	var divcnt = 0;
	do {
		if ($('chk'+divcnt).checked) {
			if ($('chk'+divcnt).getAttribute("google") == "yes")
				var obj = new AjaxRequestGoogle();
			else 
				var obj = new AjaxRequest();
			statusobj.push(obj);
			obj.rss = $('chk'+divcnt).getAttribute('rss');		
			obj.init();
		}
		divcnt++;
	}
	while ($('chk'+divcnt))
	if (statusobj.length==0) {
		alert("Please select a Topic or Specialty to Search!");
		$('articleSearch').innerHTML='';
	}
	else
		checkStatus();
}

function checkStatus() {
	if (statusobj.length>0) {
		setTimeout("checkStatus()", 200); /* check status every 2 seconds */
	} else {
		$('articleSearch').innerHTML='';
		FLTSearch = []; /* clear previous filter data */
		for (x=0;x<xhrs.length;x++) {
			var returndata = filterArticles(xhrs[x], 'articleSearch');
			FLTSearch = FLTSearch.concat(returndata[0]);
			GuestList = GuestList.concat(returndata[1]);
		}
		displayFilterData(FLTSearch, 'FLTSearch', 'articleSearch', 1);
		/* sort descending - put all articles in title order */
		GuestList = rebuildGuestList(GuestList); /* sort and remove dups */
		new Autocompleter.Local('articleSearchguests', 'guestlist', GuestList, {fullSearch: false, partialSearch: true, partialChars: 0});					
	}
}
function checkAll() {
	x = 0;
	while (x<20) {
		if ($('chk'+x)) $('chk'+x).checked = true;		
		x++;
	}
}
function checkAllTopics() {
	x = 0;
	while (x<8) {
		if ($('chk'+x)) $('chk'+x).checked = true;		
		x++;
	}
}
function checkAllSpecialties() {
	x = 8;
	while (x<11) {
		if ($('chk'+x)) $('chk'+x).checked = true;		
		x++;
	}
}

google.load("feeds", "1"); /* initialize google feed */

/* Check url parms and set default search vals*/
window.onload = function() {
	if (getUrlVal("quicksearch") == "true") {
		var divid="";
		divid="articleSearch";
		$(divid+'month').selectedIndex = getUrlVal("searchmonth");
		$(divid+'day').selectedIndex = getUrlVal("searchday");
		var x=0;
		var chkfnd = false;
		while (x<20) {
			if (getUrlVal("chk"+x) != ""){
				$('chk'+x).checked = true;		
				chkfnd = true;
			}
			x++;
		}
		/* if quicksearch and no chks found then check all */
		if (!chkfnd) {
			checkAll();
		}
		if (getUrlVal("searchyear") != "") {
			for (x=0;x<$(divid+'year').length;x++) {
				if ($(divid+'year').options[x].value == getUrlVal("searchyear")) {
					$(divid+'year').selectedIndex = x;
					break;
				}
			}
		}
		$(divid+'guests').value = unescape(getUrlVal("searchguests"));
		$(divid+'keywords').value = unescape(getUrlVal("searchkeywords"));
		buildArticleList();
	}
}

