/*

FamilyLife Article Listing - Source code
Version: beta

This contains the source code for the Broadcast Listing and Search. 
Pulling from Kintera Sphere RSS feeds

Requires:
	Google AJAX Feed API
	http://code.google.com/apis/ajaxfeeds/

*/
var sitepath = $('homeTodaysBroadcast').getAttribute('sitepath');
var statusobj = [];
var xhrs = [];
var today = new Date();

/*
	-------------------------------------------------
	Data is gathered by google 
	-------------------------------------------------
*/
/* 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;
			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[self.count] = filter;
					    statusobj.splice(self.count,1); /* remove status */
						delete self.request;
				} else {
					alert('There was a problem with the request. '+self.request.status);
				}
			}
	   }
}

/* 
	-----------------------------------------
	initial display from google rss feed
	Displays todays broadcast
	mon-fri read daily rss feed
	sat, sun reads weekly rss feed
	-----------------------------------------
*/
/* standard functions below */
function getTodaysBroadcast(filter, div) {

	/* sort by date */
	filter.sort(function (a, b){
				a = a['date'];
				b = b['date'];
				if (a>b) return 1;
				if (a <b) return -1;
				return 0; } );

	var filterItemContent='';

	for (i=0;i<filter.length;i++) {
		/* compare todays date to record date */
		if (today.getDay() > 0 && today.getDay() < 6) {  /* 1-5 = mon-fri */
			if (formatdatec(today) == formatdatec(filter[i].date)) {
				filterItemContent += buildContent(filter[i]);
				break;
			}
		} else { /*0 = sun, 6 = sat */
			if ((today.getWeek() == filter[i].date.getWeek()) && (today.getFullYear() == filter[i].date.getFullYear())) {
				filterItemContent += buildContent(filter[i]);
				break;
			}
		}
	}

	$(div).innerHTML=writeOutput(filterItemContent);
}


/* builds content to be written */
function buildContent(filter) {
	var content = "";
	content += "<div id='home_audio_broadcasts'><h1>"+filter.title+"</h1>";
	content += "<p>"+truncate(filter.description, 120, '...');
	content += "</p>";
	content += "<p><a href='"+filter.linkurl+"&from=hpbrooadcastbox'>Learn More</a></p>";
	return content;
}

/* write's output data */
function writeOutput(content) {
	var filter = "";
	filterDiv = content;
	return filterDiv;
}

function truncate(text, charlimit, tail) {
	var origtextlen = text.length;
	if (text.length > charlimit) {
		for (x=(charlimit-1);x<text.length;x++) {
			if (text.charAt(x) == ' ') break; /* if space found then break */
		}
		text = text.substr(0, x) /* cut off chars */
		if (x<origtextlen) text += tail; /* append tail if space found before end of text */
	}
	return text;
}

/* getweek function */
Date.prototype.getWeek = function() {
	var onejan = new Date(this.getFullYear(),0,1);
	/* normally - Sun-sat --> changed it to sat thru fri by adding a day*/
	return Math.ceil( ( ( ((this - onejan) / 86400000 ) + onejan.getDay()) + 2 )/7);
} 

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;
									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"] = "";
									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;
}

function formatdatec(d) {return (d.getMonth()+1)+''+d.getDate()+''+d.getFullYear();}

function buildTodaysBroadcast() {
	xhrs = []; /* clear old array */
	var obj = new AjaxRequest();
	obj.count = 0;
	statusobj[0] = obj; /* store for status */
	if (today.getDay() > 0 && today.getDay() < 6) {/* mon-fri */
		obj.rss = $('homeTodaysBroadcast').getAttribute('rss');
	} else { /*if sat or sun */
		obj.rss = $('homeTodaysBroadcast').getAttribute('rssw');
	}
	obj.init();
	checkStatus();
}

function checkStatus() {
	if (statusobj.length>0) {
		setTimeout("checkStatus()", 200); /* check status every 2 seconds */
	} else {
		getTodaysBroadcast(xhrs[0], 'homeTodaysBroadcast');
	}
}

window.onload = function() {
	buildTodaysBroadcast();
}