// Site:    www.greghartwig.com
// File:    common.inc

// Usage:   Common JavaScript functions, included on all pages
// Author:  Greg Hartwig (greg at hartwig dot com)
// Date:	   2003-04
// Updated: 2009-11





var styleCookieName = "displayStyle";  // Cookie used to remember display style

// Use our current actual domain for the cookie
var cookieDomain = "." + window.location.host.substr(window.location.host.search(/levitt/i));
// Example values:  .levitt.com, .levitt.tv




// Check for blank "Search" field
function search_check(theForm) {
	var txt;
	if      (theForm["sp-q"])  txt = theForm["sp-q"].value;
	else if (theForm["q"])     txt = theForm["q"].value;
	else if (theForm["query"]) txt = theForm["query"].value;
		
	if (txt == "") {
		alert("Enter search.");
		return false;
	}
	return true;
}







// Set all external anchors or anchors with "rel=external" or "rel=newpage" to open in a new window
// Improved version based on code at these sites:
//    See Kevin Yank's article at http://www.sitepoint.com/article/1041/1
//    http://www.sitepointforums.com/showpost.php?postid=819586&postcount=19
function externalLinks() {
	if (!document.links) return;
	//var anchors = document.getElementsByTagName("a");
	var anchors = document.links;
	for (var i=0; i<anchors.length; i++) {
		var anchor = anchors[i];
		var href   = anchor.getAttribute("href");
		if (href) {
			/* Check for hrefs starting with "http:" or "https:" outside our domain */
			/* zolalevitt.com & zolalevitt.org will pass also */
			if (/^https?\:/i.test(href) && !/levitt\.(com|org|tv)/i.test(href) &&
			    !/freefind.com/i.test(href))
				anchor.target = "_blank";
			//if (href.substr(0,7) == "http://" && !/\.levitt\./i.test(href))
				
			var relval = anchor.getAttribute("rel");
			if (relval == "external" || relval == "newpage")
				anchor.target = "_blank";
			else if (relval == "noframe")
				anchor.target = "_top";
			else if (relval == "internal")
				anchor.target = "";
		}
	}
}


/* Samples:  "email:com!sample*jones?bob*junk" */
/* Samples:  "email:com   domain#sample*jones$$$$$$bob*junk!and more#junk" */
/* --> mailto: bob.jones@sample.domain.com */
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 should be called on startup */

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;
			}
		}
	}
}




function MSIE_hoverfix() {
	// With JQuery:
	// if ($.browser.msie)
	// 	$("#navitems li").mouseover(function() {$(this).addClass("over");}).mouseout(function() {$(this).removeClass("over");});


	if (document.all && document.getElementById) {
		var navRoot = document.getElementById("navitems");
		for (var i=0; i<navRoot.childNodes.length; i++) {
			var node = navRoot.childNodes[i];
			if (node.nodeName=="LI") {
				node.onmouseover=function() {
					this.className+=" over";
				}
				node.onmouseout=function() {
					this.className=this.className.replace(" over", "");
				}
			}
		}
	}
}




//Custom JavaScript Functions by Shawn Olson
//Copyright 2004
//http://www.shawnolson.net
//If you copy any functions from this page into your scripts, 
// you must provide credit to Shawn Olson & http://www.shawnolson.net
//*******************************************
// RG Hartwig, see http://bugzilla.mozilla.org/show_bug.cgi?id=51944
// for a possible problem with this

function changeClassStyle(theClass,element,value) {
	//documentation for this script at http://www.shawnolson.net/a/503/
	var cssRules;
	if (document.all) {
		cssRules = 'rules';
	}
	else if (document.getElementById) {
		cssRules = 'cssRules';
	}
	
	for (var S = 0; S < document.styleSheets.length; S++) {
		for (var R = 0; R < document.styleSheets[S][cssRules].length; R++) {
			if (document.styleSheets[S][cssRules][R].selectorText == theClass) {
				document.styleSheets[S][cssRules][R].style[element] = value;
			}
		}
	}	
}
	
	
	
	
	
	
// Functions to change the active style and remember the setting between browser sessions
//
// ----------------------------------------------
// StyleSwitcher functions written by Paul Sowden
// - - - - - - - - - - - - - - - - - - - - - - -
// For the details, visit ALA:
// http://www.alistapart.com/stories/alternate/
//
// Modified a bit by Greg Hartwig 5/2003  greg at hartwig d o t com
// ----------------------------------------------


// Style Functions

function setActiveStyleSheet(reqstyle) {
	// With JQuery:
	// $("link[rel='*style']").attr("disabled", true).filter("[title='"+reqstyle+"']").attr("disabled", false);

	var i, tag, tagarray, stylename;
	if (!document.getElementsByTagName) return null;
	
	tagarray = document.getElementsByTagName("link");
	for (i=0; (tag = tagarray[i]); i++) {
		stylename = tag.getAttribute("title");
		// Only process named styles
		// Disable all, then enable just the one we want
		if (tag.getAttribute("rel").indexOf("style") != -1 && stylename) {
			tag.disabled = true;
			if (stylename == reqstyle) tag.disabled = false;
		}
	}
}


function getActiveStyleSheet() {
	// With JQuery:
	// $("link[rel='*style'][title='"+reqstyle+"']").attr("title");

	var i, tag, tagarray, stylename;
	if (!document.getElementsByTagName) return null;
	
	tagarray = document.getElementsByTagName("link");
	for (i=0; (tag = tagarray[i]); i++) {
		stylename = tag.getAttribute("title");
		// Return the first active named style
		if (tag.getAttribute("rel").indexOf("style") != -1 && stylename && !tag.disabled)
			return stylename;
	}
	return null;
}


function getPreferredStyleSheet() {
	var i, tag, tagarray, tagrel, stylename;
	if (!document.getElementsByTagName) return null;
	
	tagarray = document.getElementsByTagName("link");
	for (i=0; (tag = tagarray[i]); i++) {
		// Return the first non-alternate named style
		tagrel    = tag.getAttribute("rel");
		stylename = tag.getAttribute("title");
		if (tagrel.indexOf("style") != -1 && 
		    tagrel.indexOf("alt")   == -1 &&
			 stylename) 
			return stylename;
	}
	return null;
}



// Cookie Functions

function deleteCookie(name, domain) {
	if (typeof(document.cookie)!="undefined") {
		var domainvalue= domain ? "; domain="+domain : "";
		var cookievalue = name+"=; expires=Thu, 01-Jan-70 00:00:01 GMT"+domainvalue+"; path=/";
		document.cookie = cookievalue;
		//alert("storing " + cookievalue);
	}
}


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


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;
}





var lastStyle="";  // GLOBAL

function styleStartup() {
	var cookie = readCookie(styleCookieName);
	lastStyle = cookie ? cookie : getPreferredStyleSheet();
	if (lastStyle != "")
		setActiveStyleSheet(lastStyle);
	//alert("Style=" + lastStyle);
}


function styleShutdown() {
	var stylename = getActiveStyleSheet();
	if (!stylename) stylename="";
	// Don't set an empty value.  This means the style has never been set (use default)
	if (stylename != lastStyle && stylename != "") {
		//removeOldCookies();
		createCookie(styleCookieName, stylename, 365*5);
	}
	//alert("NewStyle=" + stylename + ", oldstyle="+lastStyle);
}











/* -------------------------------------- */
/* Event handler utilities                */
/* -------------------------------------- */


// From http://www.onlinetools.org/articles/unobtrusivejavascript/chapter4.html
// See  http://www.scottandrew.com/weblog/articles/cbs-events
// Calling example:  addEvent(window, 'load', foo);
function addEvent(obj, evType, fn) { 
	if (obj.addEventListener) {       // Mozilla, Safari, etc.
		obj.addEventListener(evType, fn, false); 
		return true; 
	} else if (obj.attachEvent) {    // Win/IE5
		var r = obj.attachEvent("on"+evType, fn); 
		return r; 
	} else { 
		return false; 
	} 
}

function removeEvent(obj, evType, fn) {
	if (obj.removeEventListener) {
		obj.removeEventListener(evType, fn, false);
		return true;
	} else if (obj.detachEvent) {
		var r = obj.detachEvent("on"+evType, fn);
		return r;
	} else {
		return false; 
	}
}

// From http://www.stewartspeak.com/dtr/demo/replacement.js
// See  http://www.alistapart.com/articles/dynatext/
function addLoadHandler(handler) { 
	if (window.addEventListener)
		window.addEventListener("load", handler, false); 
	else if (window.attachEvent)
		window.attachEvent("onload", handler); 
	else if (window.onload) { 
		var oldHandler = window.onload; 
		window.onload = function() { 
			oldHandler(); 
			handler(); 
		}
	} 
	else window.onload = handler; 
} 


function addUnloadHandler(handler) { 
	if (window.addEventListener)
		window.addEventListener("unload", handler, false); 
	else if (window.attachEvent)
		window.attachEvent("onunload", handler); 
	else if (window.onunload) { 
		var oldHandler = window.onunload; 
		window.onunload = function() { 
			oldHandler(); 
			handler(); 
		}
	} 
	else window.onunload = 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/IE5
	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() { 
			oldHandler(); 
			handler(); 
		}
	} 
	else window.onName = handler; 
	
	//alert("window.addEventListener="+window.addEventListener+", window.attachEvent="+window.attachEvent+", document.addEventListener="+document.addEventListener+", window.onName="+window.onName);
} 



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!
} 



/* -------------------------------------- */
/* Misc                                   */
/* -------------------------------------- */

// From: http://addons.mozilla.org/js/search-plugin.js
// Calling example:  <a href="javascript:addEngine('IMDB','png','Arts','0')">IMDB</a>
function addEngine(name,ext,cat,type) {
	if ((typeof window.sidebar == "object") && (typeof window.sidebar.addSearchEngine == "function")) {
		window.sidebar.addSearchEngine(
			"http://www.levitt.com/sherlock/" + name + ".src",
			"http://www.levitt.com/sherlock/" + name + "."+ ext, name, cat );
	} else if (typeof window.external.AddSearchProvider == "function") {
		window.external.AddSearchProvider("http://www.levitt.com/sherlock/" + name + ".xml");
	} else {
		alert("You will need a Mozilla-based browser or an OpenSearch browser (MSIE 7+) to install a search plugin.");
	}
}


function swapDivs(oldDiv, newDiv) {
	// With JQuery:
	// $(newDiv).show();
	// $(oldDiv).hide();

	document.getElementById(newDiv).style.display = 'block';
	document.getElementById(oldDiv).style.display = 'none'; 
	/*return false;*/
}






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



// Add initializer functions in this file
addHandler("load", styleStartup);
addHandler("load", fixAllEmails);
addHandler("load", externalLinks);
addHandler("load", MSIE_hoverfix);
addHandler("unload", styleShutdown);


