// Standard Script file - contains AJAX routines and other misc widely used functions
// Dean Huntley (c) 2008
// Kintera 
/*

Standard Scripts - Source code
Version: beta

This contains the source code for the standard scripts used througout site
*/
statusobj = [];
xhrs = [];
xhrsobj = {};

//google.load("feeds", "1"); /* initialize google feed */			

/* dynamic rss ajax call - based on rss feed */
function AjaxRequest()
      {
	  var self = this;
	  this.dataonly = false;  
	  this.xhrs = [];
	  this.xhrsobj = {};
	  this.count = 0;
	  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) {
  			statusobj[this.count] = "running";    //set data status
			// Firefox uses onload, but only when you have multiple AJAX requests going.
			// Usually you can bind to onreadystatechange, but only if you are not doing too many requests at once.
			if (!this.Async) {
				if (navigator.appName == "Netscape") {
					this.request.onload = function( e ) {
						var evt = window.event ? window.event : e;
						var targ = evt.target ? evt.target : evt.srcElement;
						self.handleResponse();
					}
				} else {
					// IE does not have an onload handler, so bind the onreadystatechange
					this.request.onreadystatechange=this.handleResponse;
				}
			} else {
				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
					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;
						xhrsobj[self.count] = filter;
						self.xhrs[self.count] = filter;
						self.xhrsobj[self.count] = filter;
					} else {
						xhrs[self.count] = self.request.responseText;
						xhrsobj[self.count] = self.request.responseText;
						self.xhrs[self.count] = self.request.responseText;
						self.xhrsobj[self.count] = self.request.responseText;
					}
					statusobj[self.count]="done"; /* remove status */
					delete self.request;
				} else {
					setTimeout(function() {self.PerformReload();}, 500);
				}
			}
	    }
		this.PerformReload = function() {
			this.init();
		}
}
/* dynamic rss ajax call - based on rss feed */
function AjaxRequestPost()
      {
	  var self = this;
	  this.dataonly = false;  
	  this.count = 0;
	  this.rss = "";
      this.Method = "POST";//OR "POST" 
	  this.Params = null;
      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) {
  			statusobj[this.count] = "running";    //set data status
			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.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
			this.request.setRequestHeader("Content-length", this.Params.length);
			this.request.setRequestHeader("Connection", "close");
			this.request.send(this.Params);
			//if (!this.Async) {
			//	alert(this.request);
			//	xhrs[this.count] = this.request.responseText;
			//}
		}
	  }
  	  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 result = self.request.responseText;
						xhrs[self.count] = self.request.responseText;
						statusobj[self.count]="done"; /* remove status */
						delete self.request;
					//}
				} else {
					setTimeout(function() {self.PerformReload();}, 500);
				}
			}
	   }
		this.PerformReload = function() {
			this.init();
		}
}
/* 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() {
  			statusobj[this.count] = "running";    //set data status
			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;
				xhrsobj[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);
								self.PerformReload();
								}, 500);
			}
		}
		this.PerformReload = function() {
			this.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();
				XMLItem[i]["allnodes"] = new Object();
				
				for (k=0; XMLNode[i].childNodes.length>k; k++)
				{
					if(XMLNode[i].childNodes[k].firstChild != null) {
						XMLItem[i]["allnodes"][XMLNode[i].childNodes[k].tagName] = XMLNode[i].childNodes[k].firstChild.data;
						 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:keywords" :
							 case "keywords" : XMLItem[i]["keywords"] = 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:submitted_image_02" :
 							 case "submitted_image_02" :
							 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;
							 case "k:submitted_image_01" :
 							 case "submitted_image_01" :
							 case "k:feature_img" :
							 case "feature_img" : XMLItem[i]["featureimage"] = XMLNode[i].childNodes[k].firstChild.data;
											break;
							 case "k:additional_text" :
							 case "additional_text" : XMLItem[i]["additional_text"] = XMLNode[i].childNodes[k].firstChild.data;
											break;
							 case "k:additional_link1" :
							 case "additional_link1" : XMLItem[i]["additional_link1"] = XMLNode[i].childNodes[k].firstChild.data;
											break;
							 case "k:additional_link2" :
							 case "additional_link2" : XMLItem[i]["additional_link2"] = XMLNode[i].childNodes[k].firstChild.data;
											break;
							 case "dc:creator" :
							 case "creator" : XMLItem[i]["creator"] = XMLNode[i].childNodes[k].firstChild.data;
											break;
							 case "content:encoded" : XMLItem[i]["content"] = XMLNode[i].childNodes[k].firstChild.data;
											break;
						}
					} 
				 }
			}
			
			return XMLItem;
		}
}

/* 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;
}

	String.prototype.linkify = function() {
		return this.replace(/[A-Za-z]+:\/\/[A-Za-z0-9-_]+\.[A-Za-z0-9-_:%&\?\/.=]+/, function(m) {
			return m.link(m);
		});
	};
	
	function relative_time(time_value) {
	  var values = time_value.split(" ");
	  time_value = values[1] + " " + values[2] + ", " + values[5] + " " + values[3];
	  var parsed_date = Date.parse(time_value);
	  var relative_to = (arguments.length > 1) ? arguments[1] : new Date();
	  var delta = parseInt((relative_to.getTime() - parsed_date) / 1000);
	  delta = delta + (relative_to.getTimezoneOffset() * 60);
	  
	  var r = '';
	  if (delta < 60) {
		r = 'a minute ago';
	  } else if(delta < 120) {
		r = 'couple of minutes ago';
	  } else if(delta < (45*60)) {
		r = (parseInt(delta / 60)).toString() + ' minutes ago';
	  } else if(delta < (90*60)) {
		r = 'an hour ago';
	  } else if(delta < (24*60*60)) {
		r = '' + (parseInt(delta / 3600)).toString() + ' hours ago';
	  } else if(delta < (48*60*60)) {
		r = '1 day ago';
	  } else {
		r = (parseInt(delta / 86400)).toString() + ' days ago';
	  }
	  
	  return r;
	}
	
function Get_Cookie(name) {
  var start = document.cookie.indexOf(name+"=");
  var len = start+name.length+1;
  if ( (!start) && (name != document.cookie.substring(0,name.length)) )  return null;
  if (start == -1) return null;
  var end = document.cookie.indexOf(";",len);
  if (end == -1) end = document.cookie.length;
  return unescape(document.cookie.substring(len,end));
}

function Set_Cookie(name,value,expires,path,domain,secure) {
  document.cookie = name + "=" +escape(value) +
  ( (expires) ? ";expires=" + expires.toGMTString() : "")  +
  ( (path) ? ";path=" + path : "") + 
  ( (domain) ? ";domain=" + domain : "") +
  ( (secure) ? ";secure" : "");
}

// this deletes the cookie when called
function Delete_Cookie( name, path, domain ) {
	if ( Get_Cookie( name ) ) document.cookie = name + "=" +
	( ( path ) ? ";path=" + path : "") +
	( ( domain ) ? ";domain=" + domain : "" ) +
	";expires=Thu, 01-Jan-1970 00:00:01 GMT";
}

// Check whether cookies enabled
function cookiesEnabled() {
	document.cookie = "Enabled=true";
	var cookieValid = document.cookie;
	// if retrieving the VALUE we just set actually works
	// then we know cookies enabled
	if (cookieValid.indexOf("Enabled=true") != -1)   {
		cookiesEnabled = true;
	}   else   {
		cookiesEnabled = false;   
	}
	if(cookiesEnabled) document.write("Cookies are enabled!")
	else document.write("Cookies are disabled!")
}
function dateKey(date) {
	var month = date.getMonth();
	month++;
	var dd = date.getDate() <= 9 ? '0' + date.getDate() : date.getDate();
	var mm = month <= 9 ? '0' + month : month;
	var key = date.getFullYear() + '' + mm + '' + dd; 
	return key;
}
	
//change the opacity for different browsers
function changeOpac(opacity, object) {
	if (opacity < 0) opacity=0;
	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) {
	console.log(opacity);
	if (opacity < 0) opacity=0;
	var object = document.getElementById(id).style;
	object.opacity = (opacity / 100);
	object.MozOpacity = (opacity / 100);
	object.KhtmlOpacity = (opacity / 100);
	object.filter = "alpha(opacity=" + opacity + ")";
	console.log('2'+opacity);
}

function formatdate(d) {
	return (d.getMonth()+1)+'/'+d.getDate()+'/'+d.getFullYear();
}

function formattime(d) {
	return d.getHours()+':'+((d.getMinutes() < 10) ? '0'+d.getMinutes():d.getMinutes())+' '+((d.getHours() > 11) ? "PM" : "AM");
}
// 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;}

