// Misc functions for pbnradio.com



// --------------------------------------
// MacroMedia functions
// --------------------------------------

function MM_swapImgRestore() { //v3.0
  var i,x,a=document.MM_sr;
  for (i=0; a && i < a.length && (x=a[i]) && x.oSrc; i++) x.src=x.oSrc;
}

function MM_preloadImages() { //v3.0
  var d=document;
  if (d.images) {
    if(!d.MM_p) d.MM_p=new Array();
    var i,j=d.MM_p.length, a=MM_preloadImages.arguments;
    for (i=0; i<a.length; i++)
      if (a[i].indexOf("#")!=0)
        { d.MM_p[j]=new Image; d.MM_p[j++].src=a[i]; }
    }
} // MM_preloadImages

function MM_findObj (n, d) { //v4.01
  var p,i,x;
  if (!d) d=document;
  if ((p=n.indexOf("?"))>0&&parent.frames.length) {
    d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
    if (!(x=d[n]) && d.all) x = d.all[n];
    for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
    for(i=0; !x && d.layers && i<d.layers.length; i++)
      x=MM_findObj(n,d.layers[i].document);
  if(!x && d.getElementById) x = d.getElementById(n);
  return x;
} // MM_findObj

function MM_swapImage() { //v3.0
  var i,j=0,x,a=MM_swapImage.arguments;
  document.MM_sr=new Array;
  for(i=0;i<(a.length-2);i+=3)
   if ((x = MM_findObj(a[i])) != null) {
     document.MM_sr[j++] = x;
     if(!x.oSrc) x.oSrc=x.src;
     x.src=a[i+2];
     }
} // MM_swapImage







// --------------------------------------
// Utility functions
// --------------------------------------

// Return an object by id in any browser
function getObject(id) { ///////////////////////////////////////////////////
  var elm = null;
  if (document.getElementById)
     elm = document.getElementById(id);
  else if (document.layers)
     elm = document.layers[id];
  else if (document.all)
     elm = document.all[id];
  return elm;
} // getObject



function getStyleObject(id)
{
   var elm = getObject(id);
   var styleObject = null;

   if (elm) {
      if (elm.style)
         styleObject = elm.style;
      else if (document.layers)
         styleObject = elm;
   }

  return styleObject;
}


// Return an integer in a given range
function generateRandom (low, high) { //////////////////////////////////////
  return low + Math.floor(Math.random() * (high - low + 1));
} // generateRandom






// --------------------------------------
// Cookie Functions
// --------------------------------------

// See http://www.alistapart.com/stories/alternate/

function createCookie(name,value,days) {
	if (typeof(document.cookie)!="undefined") {
		if (days) {
			var date = new Date();
			date.setTime(date.getTime()+(days*24*60*60*1000));
			var expires = "; expires="+date.toGMTString();
		}
		else expires = "";
		document.cookie = name+"="+value+expires+"; path=/";
	}
}


function readCookie(name) {
	if (typeof(document.cookie)!="undefined") {
		var nameEQ = name + "=";
		var ca = document.cookie.split(';');
		for (var i=0; i < ca.length; i++) {
			var c = ca[i];
			while (c.charAt(0)==" ") c = c.substring(1,c.length);  // Remove leading spaces
			if (c.indexOf(nameEQ) == 0) 
				return c.substring(nameEQ.length,c.length);
		}
	}
	return null;
}




// --------------------------------------
// Utilities
// --------------------------------------

// Randomize an array
// Call via arrayname.shuffle();
if (!Array.prototype.shuffle) Array.prototype.shuffle = function() {
	var i, from, old;
	
	// Shuffle the array
	for (i=0; i < this.length; i++) {
		from = Math.floor(Math.random() * this.length);
		old = this[i];
		this[i] = this[from];
		this[from] = old;
	}
}




// --------------------------------------
// Initialize/uninitialize helpers
// --------------------------------------

// From http://www.stewartspeak.com/dtr/demo/replacement.js
// See  http://www.alistapart.com/articles/dynatext/
function addLoadHandler(handler) { 
	addHandler("load", handler);
} 


function addUnloadHandler(handler) { 
	addHandler("unload", handler);
} 



function addHandler(handlerType, handler) { 
	if (typeof handlerType=="undefined" || handlerType=="")
		handlerType = "load";
	var onName = "on" + handlerType;
	
	if (typeof window.addEventListener != "undefined")
		window.addEventListener(handlerType, handler, false);  // Mozilla, Safari, etc.
	else if (typeof window.attachEvent != "undefined")
		window.attachEvent(onName, handler);   // Win/IE
	else if (typeof document.addEventListener != "undefined")
		document.addEventListener(handlerType, handler);   // Opera 7
	else if (typeof window.onName != "undefined") { 
		var oldHandler = window.onName; 
		window.onName = function piggyback() { 
			oldHandler(); 
			handler(); 
		}
	} 
	else window.onName = handler; 
} 



function removeHandler(handlerType, handler) { 
	if (typeof handlerType=="undefined" || handlerType=="")
		handlerType = "load";
	var onName = "on" + handlerType;
	
	if (typeof window.removeEventListener != "undefined")
		window.addEventListener(handlerType, handler, false);  // Mozilla, Safari, etc.
	else if (typeof window.detachEvent != "undefined")
		window.detachEvent(onName, handler);   // Win/IE
	else if (typeof document.removeEventListener != "undefined")
		document.removeEventListener(handlerType, handler);   // Opera 7
	else if (typeof window.onName != "undefined")
		window.onName = null;  // Kills them all!
} 







// --------------------------------------
// Email functions
// --------------------------------------


/* Generate an email address link */
function decryptEmail (a) {
  var n1='pbnr', n2='adio.c', n3='om';
  document.write('<' + 'a href="mai' + 'lto:' + a + '@' + n1 + n2);
  document.write(n3 + '">' + a + '@');
  document.writeln(n1 + n2 + n3 + "<" + "/a>");
} // decryptEmail


/* Samples:  "email:com!sample*jones?bob*junk" */
/* Samples:  "email:com   domain#sample*jones$$$$$$bob*junk!and more#junk" */
/* --> mailto: bob.jones@sample.domain.com */
/* Called by the following function */
function unscrambleEmail(email) {
	var parts = email.split("*");
	var p1 = parts[0].split(/\W+/);
	var p2 = parts[1].split(/\W+/);
	
	return p2.reverse().join(".") + "@" + p1.reverse().join(".");
}


/* Unravel email addresses into proper "mailto:" tags */
/* Email addresses are in the HTML in a coded fashion to avoid spambots */
/* This is called on startup */

/* Leave <a> tag blank and address will be filled in automatically. */
/* Example:  <a href="com sample*webmaster"></a>  will show the email address as a link */

function fixAllEmails() {
	var refs;
	if (document.getElementsByTagName)
		refs = [document.links, document.getElementsByTagName("area")];
	else
		refs = [document.links];
	
	for (var refidx in refs) { 
		var collection = refs[refidx]; 
		for (var j=0;j<collection.length;j++) { 
			var item = collection[j]
			var addr = item.getAttribute("href");
			if (/^email\:/i.test(addr)) {
				/* It's one of ours.  Decode it */
				
				var emailaddr = unscrambleEmail(unescape(addr.substr(6)));
				item.href = "mailto:" + emailaddr;
				/* If text inside anchor tags is empty, set it to the email address */
				if (item.innerHTML=="") item.innerHTML = emailaddr
			}
		}
	}
}





// --------------------------------------
// Generic image reloader
// --------------------------------------


// Load an image into a named html img (with possible MSIE filter effects)
// If URL is not given, reload the current image
// Force reload by adding the current seconds as an argument (if URL is not given)
function reloadImage(objectName, imageUrlArg) {
   var now = new Date();
   
   var imageObject = getObject(objectName);
	if (imageObject != null && !bIdle) {
		var imageUrl;
		// Get the URL without any arguments
		if (typeof(imageUrlArg) == "undefined" || imageUrlArg=="") {
			imageUrl = imageObject.src;
			var urlend = imageUrl.indexOf("?");
			if (urlend != -1) imageUrl = imageUrl.substring(0,urlend);
			imageUrl += "?" + now.getTime();  // Add the time to the URL so it will appear changed
		} else {
			imageUrl = imageUrlArg;
		}
		
		// Cause the image to reload, with MSIE transition, if any
		if (imageObject.filters) imageObject.filters.blendTrans.apply();
		//alert("Loading " + objectName + " with " + imageUrl);
		imageObject.src = imageUrl;
		if (imageObject.filters) imageObject.filters.blendTrans.play();
   }
}



// Load an image into a named html img (with possible MSIE filter effects)
// If URL is not given, reload the current image
// Change URL, then change it back (work-around for .gif URLs that don't accept arguments)
function reloadImage2(objectName, imageUrlArg) {
   var now = new Date();
   
   var imageObject = getObject(objectName);
	if (imageObject != null && !bIdle) {
		var imageUrlRaw, imageUrl;
		// Get the URL without any arguments
		if (typeof(imageUrlArg) == "undefined" || imageUrlArg=="") {
			imageUrlRaw = imageObject.src;
			var urlend = imageUrlRaw.indexOf("?");
			if (urlend != -1) imageUrlRaw = imageUrlRaw.substring(0,urlend);
			imageUrl = imageUrlRaw + "?" + now.getTime();  // Add the time to the URL so it will appear changed
		} else {
			imageUrlRaw = imageUrlArg;
			imageUrl    = imageUrlArg;
		}
		
		// Cause the image to reload, with MSIE transition, if any
		if (imageObject.filters) imageObject.filters.blendTrans.apply();
		//alert("Loading " + objectName + " with " + imageUrl);
		imageObject.src = imageUrl;
		imageObject.src = imageUrlRaw;
		if (imageObject.filters) imageObject.filters.blendTrans.play();
   }
}




// --------------------------------------
// Table stripe functions
// --------------------------------------

// See http://alistapart.com/articles/zebratables/


// this function is needed to work around 
// a bug in IE related to element attributes
function hasClass(obj) {
	var result = false;
	if (obj.getAttributeNode("class") != null)
		result = obj.getAttributeNode("class").value;
	return result;
}   


function stripeTable(table) {
	// the flag we'll use to keep track of 
	// whether the current row is odd or even
	var even = false;
	
	// if arguments are provided to specify the colours
	// of the even & odd rows, then use the them;
	// otherwise use the following defaults:
	var evenColor = arguments[1] ? arguments[1] : "#fff";
	var oddColor  = arguments[2] ? arguments[2] : "#eee";
	
	// by definition, tables can have more than one tbody
	// element, so we'll have to get the list of child
	// <tbody>s 
	var tbodies = table.getElementsByTagName("tbody");
	
	// and iterate through them...
	for (var h = 0; h < tbodies.length; h++) {

		// find all the <tr> elements... 
		var trs = tbodies[h].getElementsByTagName("tr");
		
		// ... and iterate through them
		for (var i = 0; i < trs.length; i++) {
			
			// avoid rows that have a class attribute
			// or backgroundColor style
			if (!hasClass(trs[i]) && !trs[i].style.backgroundColor) {
				
				// get all the cells in this row...
				var tds = trs[i].getElementsByTagName("td");
				
				// and iterate through them...
				for (var j = 0; j < tds.length; j++) {
					var mytd = tds[j];
					
					// avoid cells that have a class attribute
					// or backgroundColor style
					if (!hasClass(mytd) && !mytd.style.backgroundColor)
						mytd.style.backgroundColor = even ? evenColor : oddColor;
				}
			}
			
			// flip from odd to even, or vice-versa
			even =  !even;
		}
	}
}


function stripeTableById(id, evenColor, oddColor) {
	// obtain a reference to the desired table
	// if no such table exists, abort
	var table = document.getElementById(id);
	if (!table) return;
	
	stripeTable(table, evenColor, oddColor);
}


function stripeTableInDiv(divClass, evenColor, oddColor) {
	// Find all tables
	var divs = document.getElementsByTagName("div");
	
	// and iterate through them...
	for (var d = 0; d < divs.length; d++) {
		var c = hasClass(divs[d]);
		if (c == divClass) {
			var tables = divs[d].getElementsByTagName("table");
	
			// and iterate through them...
			for (var t = 0; t < tables.length; t++) {
				stripeTable(tables[t], evenColor, oddColor);
			}
		}
	}
}

 
function stripeTableAll(evenColor, oddColor) {
	// Find all tables
	var tables = document.getElementsByTagName("table");
	
	// and iterate through them...
	for (var t = 0; t < tables.length; t++) {
		stripeTable(tables[t], evenColor, oddColor);
	}
}






////////////////////////////////////////////////////////////////////////////
// Check for idle user
// Used to stop auto-loading photos when the user isn't active
////////////////////////////////////////////////////////////////////////////
var bIdle = false;
var idleTimer = null;
var timeUntilIdle = 5*60 * 1000;  // 5 minutes


function foundActivity() {
	bIdle = false;
	
	// Kill the current timer and start it again
	window.clearTimeout(idleTimer);
	idleTimer = window.setTimeout("bIdle=true;", timeUntilIdle);
}


// Add listeners for various activities
addHandler("mousemove", foundActivity);
addHandler("mousedown", foundActivity);
addHandler("keydown",   foundActivity);
addHandler("keypress",  foundActivity);





// --------------------------------------
// Initialize/uninitialize
// --------------------------------------

// Add functions to run when page loads
addLoadHandler(fixAllEmails);


