// banasmoo.com/js/javascript.js
// Copyright (c) 2004-2007 Dan Wright
// www.danwright.info/contact

var haveDebug = (typeof Debug == 'object') && Debug.log != null;

// don't frame me in!
if (top != self)
	top.location.href = location.href;

function runOnLoad(func)
{
	var oldfunc = window.onload;
	if (typeof window.onload != 'function')
		window.onload = func;
	else
		window.onload = function() { oldfunc(); func(); };
}

function addDocumentLoadFunc(func)
{
	runOnLoad(func);
}


// require that another JavaScript library be present. The first parameter
// allows us to avoid loading the library multiple times.
function requireLibrary(doInclude, path)
{
	if (doInclude)
		document.write("<script src=\"" + path + "\" type=\"text/javascript\"></script>");
}

function writeEmailLink(address,description) 
{
	var i = address.indexOf('kah');
	var fixedEmail = address.substring(i+3,address.length) + String.fromCharCode(64) + address.substring(0,i);
	var prefix = '&#109;&#97;&#105;' + '&#108;&#116;&#111;&#58;';  // Unicode for 'mai' + 'lto:'
	var linkStr = '<a href="' + prefix + fixedEmail + '" title="' + fixedEmail + '">';
	document.write(linkStr + description + '<\/a>');
}

function inlineMail(address) 
{
	var i = address.indexOf('kah');
	var fixedEmail = address.substring(i+3,address.length) + String.fromCharCode(64) + address.substring(0,i);
	var prefix = '&#109;&#97;&#105;' + '&#108;&#116;&#111;&#58;';  // Unicode for 'mai' + 'lto:'
	var linkStr = '<a href="' + prefix + fixedEmail + '" title="' + fixedEmail + '">';
	document.write(linkStr + fixedEmail + '<\/a>');
}
	
// it's absolutely disgusting that I have not one, not two, but THREE ways -- in JavaScript alone --
// for evading spammers. This one is not nearly as messy in the xhtml -- because I start out (in the xhtml)
// with a simple web link -- in case JavaScript is disabled -- and then fix it up here if we can do better.
// The "real" address is stored (obfuscated) in the link 'name'.
function fixupEmailLinks()
{
	var i;
	for (i = 0; i < document.links.length; i++)
		{
		// first method:
		//		<a href="nospam:domain attn user">foobar</a>
		//		==> <a href="mailto:user@domain" title="user@domain">foobar</a>
		if (document.links[i].protocol == 'nospam:')
			{
			var path = document.links[i].pathname;
			var matchStr = ' attn ';
			var j = path.indexOf(matchStr);
			if (j < 0)
				{
				matchStr = '%20attn%20'; // MacIE helpfully escapes the spaces for us...
				j = path.indexOf(matchStr);
				}
			if (j >= 0)
				{
				var name = path.substring(j+matchStr.length,path.length);
				var fixedEmail = name + String.fromCharCode(64) + path.substring(0,j);
				document.links[i].href = 'mailto:' + fixedEmail;
				document.links[i].title = fixedEmail;
				//var txt = document.createTextNode(name);
				//document.links[i].appendChild(txt);
				}
			else
				{
				alert("path = " + path);
				}
			}
		// second method:
		//		<a href="contact.html" name="domainattnuser">whatever</a>
		//		==> <a href="mailto:user@domain" title="user@domain">whatever</a>
		//   a message subject can also be specified:
		//		<a href="contact.html" name="domainattnusersubjThis_is_the_subject">whatever</a>
		// This method is designed for compatibility when JavaScript is disabled/unsupported.
		// The contact.html presumably contains a form that submits a message via CGI script, 
		// avoiding "mailto" links altogether.
		if (document.links[i].protocol == 'http:' && document.links[i].name != null)
			{
			var name = document.links[i].name;
			var j = name.indexOf('attn');
			if (j >= 0)
				{
				var domain = name.substring(0,j);
				var useretc = name.substring(j+4, name.length);
				var subject = null;
				var k = useretc.indexOf('subj');
				if (k > 0)
					{
					// It's not clear that spaces are actually illegal in a 'name' field;
					// I take the approach that they are not under the assumption that there
					// exists at least one browser that would throw a hissy fit if a space
					// were present.
					subject = useretc.substring(k+4,useretc.length);
					subject = subject.replace(/_/g, ' '); // underscores -> spaces
					useretc = useretc.substring(0,k);
					}
				var fixedEmail = useretc + String.fromCharCode(64) + domain;
				var extra = (subject != null) ? ("?Subject="+subject) : "";
				document.links[i].href = 'mailto:' + fixedEmail + extra;
				document.links[i].title = fixedEmail;
				}
			}
		}
}

function clearPlaceholder(elem)
{
	if (elem != null)
		{
		if (elem.value == elem.getAttribute('placeholder'))
			{
			elem.value = "";
			elem.style.color = '#000000';
			}
		}
}

function resetPlaceholder(elem)
{
	if (elem != null)
		{
		if (elem.value == "")
			{
			elem.style.color = '#999999';
			elem.value = elem.getAttribute('placeholder');
			}
		}
}

function fixupPlaceholder()
{
	var elems = $$('input#terms');
	elems.each( function (elem)
				{
				elem.addEventListener('focus', function() { clearPlaceholder(elem); }, false);
				elem.addEventListener('blur',  function() { resetPlaceholder(elem); }, false);
				elem.style.color = '#999999';
				elem.value = elem.getAttribute('placeholder');
				}
			);
}

addDocumentLoadFunc(fixupEmailLinks);

function getDomain()
{
	var delim = /\//;
	if( navigator.appName == "Microsoft Internet Explorer" )
		var url = window.document.location.href;
	else
		var url = window.location.href;
	var urlArray = url.split( delim );
	if( navigator.appName == "Microsoft Internet Explorer" )
			return urlArray[1];
	else
		return urlArray[2];
}

function splitURLToDomain(){return getDomain();}

function isLocalDomain(){return getDomain().indexOf(".local") > 0;}


// Enable debug utilities on local domain
do { var __ld = getDomain();
	if (__ld.indexOf(".local") > 0)
		{ var __djs;
		if (__ld.indexOf("banasmoo.local") >= 0)
			__djs = "/js/debug.js";
		else if (__ld.indexOf("danwright.local") >= 0)
			__djs = "/software/js/debug.js";
		else
			break;
		requireLibrary(!haveDebug, __djs);
		haveDebug = (typeof Debug == 'object') && Debug.log != null;
		}
	} while (0);

function haveDOM()
{
	return (document.getElementById && document.createTextNode);
}

function replaceParaText(paraid, newtext)
{
	var txt = document.createTextNode(newtext);
	var elem = document.getElementById(paraid);
	if (!elem) alert("could not locate " + paraid);
	var oldTxt = elem.replaceChild(txt, elem.firstChild);
	return true;
}

function hasClass(elem, className)
{
	return new RegExp('\\b'+className+'\\b').test(elem.className);
}

function addClass(elem, className)
{
	if (!hasClass(elem, className))
		elem.className += elem.ClassName ? (' '+className) : className;
}

function removeClass(elem, className)
{
	var rep = elem.className.match(' '+className) ? (' '+className) : className;
	elem.className = elem.className.replace(rep, '');
}

var imagesButtons = new Object();

function loadButtonImages()
{
	if (document.images)
		{
		imagesButtons["buybutton-onblk"] = new Image(23,73);
		imagesButtons["buybutton-onblk"].src = "/images/buybutton-onblk.png";
		imagesButtons["buybuttononblkpressed"] = new Image(23,73);
		imagesButtons["buybuttononblkpressed"].src = "/images/buybutton-onblk-pressed.png";
		}
}

function setImage(imgElem, imgName)
{
	if (document.images)
		{
		document.images[imgElem].src = imagesButtons[imgName].src;
		}
}

function setImageSrc(imgElem, imgSrc)
{
	var elem = (typeof(imgElem) == "string" ? document.getElementById(imgElem) : imgElem);
	elem.src = imgSrc;
	return true;
}

function isAppleWebKit()
{
	return (navigator.appVersion.indexOf('AppleWebKit') > 0);
}

function isIE()
{
	return (navigator.appVersion.indexOf('MSIE') > 0);
}

function isMacIE()
{
	return isIE() && isPlatformMac();
}

function isNetscape()
{
	return (navigator.appVersion.indexOf('Netscape') > 0);
}

function isPlatformMac()
{
	return (navigator.platform.indexOf('MacPPC') == 0);
}

// ==== form utilities ==== //

function setDelayedFocus(elem)
{
	var srcForElem = "document.register." + elem.name;
	setTimeout(srcForElem + ".focus(); " + srcForElem + ".select();", 0);
}

// ==== parsing the url query ==== //

function queryParamExists(paramName)
{
	var re = new RegExp("[\?&]" + paramName + "\b");	// this will match a param with or without a value ("?param&etc" or "?param=value&etc")
	var matchArray = re.exec(document.URL);
	return (matchArray != null);
}

function getQueryParamValue(paramName)
{	
	var re = new RegExp("[\?&]" + paramName + "=([^#&]+)"); // this will NOT match an empty value! cf queryParamExists
	var matchArray = re.exec(document.URL);
	return (matchArray ? decodeURIComponent(matchArray[1]) : null);
}

// ==== cookie functions ==== //

function getExpDate(days, hours, minutes)
{
	var expDate = new Date();
	if (typeof days == "number" && typeof hours == "number" && typeof minutes == "number")
		{
		expDate.setDate(expDate.getDate() + parseInt(days));
		expDate.setHours(expDate.getHours() + parseInt(hours));
		expDate.setMinutes(expDate.getMinutes() + parseInt(minutes));
		return expDate.toGMTString();
		}
}

function getCookieVal(offset)
{
	var endstr = document.cookie.indexOf(";", offset);
	if (endstr == -1)
		endstr = document.cookie.length;
	return unescape(document.cookie.substring(offset, endstr));
}


function getCookie(name)
{
	var arg = name + "=";
	var alen = arg.length;
	var clen = document.cookie.length;
	var i = 0;
	while (i < clen)
		{
		var j = i + alen;
		if (document.cookie.substring(i, j) == arg)
			return getCookieVal(j);
		i = document.cookie.indexOf(" ", i) + 1;
		if (i == 0) break;
		}
	return "";
}

function setCookie(name, value, expires, path, domain, secure)
{
	document.cookie = name + "=" + escape(value) + 
					(expires ? "; expires=" + expires : "") +
					(path ? "; path=" + path : "") +
					(domain ? "; domain=" + domain : "") +
					(secure ? "; secure" : "");
}

