/*

Standard Scripts - Source code
Version: beta

This contains the source code for the standard scripts used througout site
*/
statusobj = [];
xhrs = [];

//google.load("feeds", "1"); /* initialize google feed */			

/* dynamic rss ajax call - based on rss feed */
function AjaxRequest()
      {
	  this.dataonly = false;  
	  this.count = 0;
	  this.returndata = [];
	  this.rss = "";
      this.Method = "GET";//OR "POST" 
      this.Async = true; //OR false (asynchronous or synchronous call) 
      this.init = function() {
		  if (this.dataonly) {this.Async = false;}
		  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);
			if (this.dataonly) {
				xhrs[this.count] = self.request.responseText;
			}
		}
	  }
	  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
					if (!self.dataonly) {
						var xmldoc = self.request.responseXML;
						var root_node = xmldoc.getElementsByTagName("item");
						var readRSS = new readRSSData(root_node);
						var filter = readRSS.parseRSSData(root_node);
						xhrs[self.count] = filter;
						self.returndata[self.count] = filter;
						statusobj[self.count]="done"; /* 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 readRSS = new readRSSData();
				var filter = readRSS.parseRSSData(root_node);
				xhrs[self.count] = filter;
				statusobj[self.count]="done"; /* remove status */
			} else {
				//alert(result.error.message + 'id: '+self.count);
				setTimeout(function() {
								var ajaxreload = new AjaxReload();
								ajaxreload.PerformReload(self.count, self.rss);
								}, 500);
			}
		}
}
function AjaxReload() {
		/* if google fails - retry */
		this.PerformReload = function(divcnt, rss) {
			var obj = new AjaxRequestGoogle();
			obj.rss = rss;
			obj.count = divcnt;
			obj.init();
		}
}

function readRSSData() {
		/* read record and store parts */
		this.parseRSSData = function(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]["subtitle"] = XMLNode[i].childNodes[k].firstChild.data;
											XMLItem[i].subtitle = XMLNode[i].childNodes[k].firstChild.data.replace(/\(Day \d+? of \d+?\)/g,""); /* remove day # of # */
											XMLItem[i].subtitle= XMLItem[i].subtitle.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]["byline"] = XMLNode[i].childNodes[k].firstChild.data;
											break;
							 case "k:Type" :
							 case "Type" : XMLItem[i]["type"] = XMLNode[i].childNodes[k].firstChild.data;
											break;
							 case "k:Category" :
							 case "Category" : XMLItem[i]["category"] = XMLNode[i].childNodes[k].firstChild.data;
											break;
							 case "k:SubCategory" :
							 case "SubCategory" : XMLItem[i]["subcategory"] = XMLNode[i].childNodes[k].firstChild.data;
											break;
							 case "k:Calendar" :
							 case "Calendar" : XMLItem[i]["calendar"] = XMLNode[i].childNodes[k].firstChild.data;
											break;
							 case "k:Theme" :
							 case "Theme" : XMLItem[i]["theme"] = XMLNode[i].childNodes[k].firstChild.data;
											break;
							 case "k:Other_category" :
							 case "Other_category" : XMLItem[i]["otherCategories"] = XMLNode[i].childNodes[k].firstChild.data;
											break;
							 case "k:ListenURL" :
							 case "ListenURL" : XMLItem[i]["listenurl"] = XMLNode[i].childNodes[k].firstChild.data;
											break;
							 case "k:ListenLink" :
							 case "ListenLink" : XMLItem[i]["listenlink"] = XMLNode[i].childNodes[k].firstChild.data;
											break;
							 case "k:read_more_url" :
							 case "read_more_url" : XMLItem[i]["read_more_url"] = XMLNode[i].childNodes[k].firstChild.data;
											break;
							 case "k:read_more_label" :
							 case "read_more_label" : XMLItem[i]["read_more_label"] = XMLNode[i].childNodes[k].firstChild.data;
											break;
							 case "k:thumb_img" :
							 case "thumb_img" : XMLItem[i]["thumbnail"] = XMLNode[i].childNodes[k].firstChild.data;
											break;
							 case "k:number_days" :
							 case "number_days" : XMLItem[i]["days"] = XMLNode[i].childNodes[k].firstChild.data;
											break;
							 case "k:seasons" :
							 case "seasons" : XMLItem[i]["seasons"] = XMLNode[i].childNodes[k].firstChild.data;
											break;
							 case "k:special_times" :
							 case "special_times" : XMLItem[i]["specialtimes"] = XMLNode[i].childNodes[k].firstChild.data;
											break;
							 case "k:date_display" :
							 case "date_display" : XMLItem[i]["datedisplay"] = XMLNode[i].childNodes[k].firstChild.data;
											break;
							 case "k:days" :
							 case "days" : XMLItem[i]["days"] = XMLNode[i].childNodes[k].firstChild.data;
											break;
							 case "k:labels" :
							 case "labels" : XMLItem[i]["labels"] = XMLNode[i].childNodes[k].firstChild.data;
											break;
						}
					} 
				 }
			}
			
			return XMLItem;
		}
}

function formatdate(d) {
	return (d.getMonth()+1)+'/'+d.getDate()+'/'+d.getFullYear();
}

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];
}

// remove multiple, leading or trailing spaces
function trim(s) {s = s.replace(/(^\s*)|(\s*$)/gi,"");s = s.replace(/[ ]{2,}/gi," ");s = s.replace(/\n /,"\n");return s;}

Array.prototype.find = function(searchStr) {
	var returnArray = false;
	for (i=0; i<this.length; i++) {
		if (typeof(searchStr) == 'function') {
			if (searchStr.test(this[i])) {
				if (!returnArray) { returnArray = [] } 
				returnArray.push(i);
			}
		} else {
			if (this[i]===searchStr) {
				if (!returnArray) {	returnArray = [] } 
				returnArray.push(i);
			}
		}
	}
	return returnArray;
}

// array-like enumeration
if (!Array.forEach) { // mozilla already supports this
	Array.forEach = function(array, block, context) {
		for (var i = 0; i < array.length; i++) {
			block.call(context, array[i], i, array);
		}
	};
}

// generic enumeration
Function.prototype.forEach = function(object, block, context) {
	for (var key in object) {
		if (typeof this.prototype[key] == "undefined") {
			block.call(context, object[key], key, object);
		}
	}
};

// character enumeration
String.forEach = function(string, block, context) {
	Array.forEach(string.split(""), function(chr, index) {
		block.call(context, chr, index, string);
	});
};

// globally resolve forEach enumeration
var forEach = function(object, block, context) {
	if (object) {
		var resolve = Object; // default
		if (object instanceof Function) {
			// functions have a "length" property
			resolve = Function;
		} else if (object.forEach instanceof Function) {
			// the object implements a custom forEach method so use that
			object.forEach(block, context);
			return;
		} else if (typeof object == "string") {
			// the object is a string
			resolve = String;
		} else if (typeof object.length == "number") {
			// the object is array-like
			resolve = Array;
		}
		resolve.forEach(object, block, context);
	}
};

//change the opacity for different browsers
function changeOpac(opacity, object) {
	object.style.opacity = (opacity / 100);
	object.style.MozOpacity = (opacity / 100);
	object.style.KhtmlOpacity = (opacity / 100);
	if(opacity == 100) {
		object.style.filter = '';
	} else {
		object.style.filter = "alpha(opacity=" + opacity + ")";
	}
}
function changeOpacId(opacity, id) {
	var object = document.getElementById(id).style;
	object.opacity = (opacity / 100);
	object.MozOpacity = (opacity / 100);
	object.KhtmlOpacity = (opacity / 100);
	object.filter = "alpha(opacity=" + opacity + ")";
}

// fader function
function fader(id, opacStart, opacEnd, millisec) {
	//speed for each frame
	var speed = Math.round(millisec / 100);
	var timer = 0;

	//determine the direction for the blending, if start and end are the same nothing happens
	if(opacStart > opacEnd) {
		var i;
		for(i = opacStart; i >= opacEnd; i--) {
			setTimeout("changeOpacId(" + i + ",'" + id + "')",(timer * speed));
			timer++;
		}
	} else if(opacStart < opacEnd) {
		var i;
		for(i = opacStart; i <= opacEnd; i++) {
			setTimeout("changeOpacId(" + i + ",'" + id + "')",(timer * speed));
			timer++;
		}
	}
}

/* standard js functions */
/* XMLHTTPREQUEST function */
function getXMLHttp() {
	if (window.XMLHttpRequest) { // Mozilla, Safari,...
		var xmlhttp = new XMLHttpRequest();
		if (xmlhttp.overrideMimeType) {xmlhttp.overrideMimeType('text/xml');}
	} else if (window.ActiveXObject) { // IE
		try {
			xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
		} catch (e) {
			try {
			xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
			} catch (e) {}
		}
	}

	if (!xmlhttp) {alert('Giving up :( Cannot create an XMLHTTP instance');return false;}
	return xmlhttp;
}
//change the opacity for different browsers
function changeOpac(opacity, object) {
	object.style.opacity = (opacity / 100);
	object.style.MozOpacity = (opacity / 100);
	object.style.KhtmlOpacity = (opacity / 100);
	if(opacity == 100) {
		object.style.filter = '';
	} else {
		object.style.filter = "alpha(opacity=" + opacity + ")";
	}
}
function changeOpacId(opacity, id) {
	var object = document.getElementById(id).style;
	object.opacity = (opacity / 100);
	object.MozOpacity = (opacity / 100);
	object.KhtmlOpacity = (opacity / 100);
	object.filter = "alpha(opacity=" + opacity + ")";
}
