// www.levitt.com  2003-04
// by Greg Hartwig (greg at hartwig dot com)

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



// Object functions
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;
}


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




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



function validate_mlform(theForm) {
	var msgtxt = "";
	if (theForm["First Name"].value == "" &&
		 theForm["Last Name"].value == "") msgtxt+="Error: You must enter a name.\n";
	if (theForm["Address"].value == "")   msgtxt+="Error: You must enter an address line.\n";
	if (theForm["City"].value == "")      msgtxt+="Error: You must enter a city.\n";
	if (msgtxt != "") {
		alert(msgtxt);
		return false;
	}
	return true;
}








// Adjust the left margin if we're in a frame
// (OLD PAGES only now)
function fixMargin() {
	if (window==window.top) return; // Not in a frame, exit
	
	var bodyStyleObj=null;
	if (document.body && document.body.style)
		bodyStyleObj = document.body.style;
	else if (document.all)
		bodyStyleObj = document.all.body.style;
	
	// If we're in a frame, reduce the left margin
	//prompt("window is "+(window==window.top?"is NOT":"is")+" in a frame.");
	if (bodyStyleObj) bodyStyleObj.marginLeft = "1em";
}




function getWindowHeight() {
	var windowHeight=0;
	if (typeof(window.innerHeight) == "number")
		windowHeight=window.innerHeight;
	else if (document.documentElement && document.documentElement.clientHeight)
		windowHeight=document.documentElement.clientHeight;
	else if (document.body && document.body.clientHeight)
		windowHeight=document.body.clientHeight;

	return windowHeight;
}



// Adjust the height of the navigation section to match the content
function fixNav() {
	var divNav, divContent, navHeight, contentHeight, windowHeight, newNavHeight;
	
	divNav     = getObject("navside");
	divContent = getObject("contentside");
	if (divNav==null || divContent==null) return;
	
	
	// Get heights
	navHeight     = newNavHeight = divNav.offsetHeight;
	contentHeight = divContent.offsetHeight;	
	windowHeight  = getWindowHeight();
	
	// Adjust nav height, if necessary.
	//alert("navHeight="+navHeight+", contentHeight="+contentHeight);	
	if (newNavHeight) {
		newNavHeight = Math.max(newNavHeight, contentHeight, windowHeight);
		
		//alert("newNavHeight="+newNavHeight);		
		if (newNavHeight != navHeight)
			divNav.style.height = newNavHeight+"px";
	}
}



// Set all anchors with "rel=external"  or "rel=newpage" to open in a new window
// See Kevin Yank's article at http://www.sitepoint.com/article/1041/1
/***
function externalLinks() {
	if (!document.getElementsByTagName) return;
	var anchors = document.getElementsByTagName("a");
	for (var i=0; i<anchors.length; i++) {
		var anchor = anchors[i];
		if (anchor.getAttribute("href")) {
			var relval = anchor.getAttribute("rel");
			if (relval == "external" || relval == "newpage")
				anchor.target = "_blank";
			if (relval == "noframe")
				anchor.target = "_top";
		}
	}
}
***/

// Alternative:
// http://www.sitepointforums.com/showpost.php?postid=819586&postcount=19

/***
function setTarget() {
	var refs = [document.links,document.forms];
	for (var refidx in refs) { 
		var collection = refs[refidx]; 
		for (var i=0;i<collection.length;i++) { 
			if      (collection[i].rel == "external")
				collection[i].target="_blank";
			else if (collection[i].rel == "newpage") { 
				collection[i].target="_blank";
			else if (collection[i].rel == "noframe") { 
				collection[i].target="_top";
			}
		}
	}
}
***/



// 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 = "";
		}
	}
}


// Generate email references given a token name
function showemail(addrtoken, statusmsg, linktext) {
	var a,b,c,d, statusdata="", linkdata=linktext;
	c = "com";
	switch (addrtoken) {
		case "staff":
			a="ff"; b="sta"; d="levitt."; break;
		case "wm":
			a="aster"; b="webm"; d="levitt."; break;
		case "travel":
			a="vel"; b="tra"; d="levitt."; break;
//		case "Udi":
//			a="hana"; b="udio"; d="conceptwizard."; break;
		default:
			a="tt"; b="levi"; d="levitt."; break;
	}
	if (typeof(statusmsg)!="undefined" && statusmsg !="") statusdata = 
		" title=\""+statusmsg+"\""  /* + 
		" onmouseover=\"window.status='"+statusmsg+"'; return true;\"" +
		" onmouseout=\"window.status=''; return true;\""*/;

	if (typeof(linktext)=="undefined" || linktext =="")
		linkdata = b+a+"@"+d+c;
		
	document.write("<"+"a href=\"mai"+"lto:"+b+a+"@"+d+c+"\""+statusdata+">" +  linkdata  +  "<"+"/a>");
}



/* 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
			}
		}
	}
}




// For Personal Letter highlighting on/off
function hion() {
	// Turn highlighting on
	setStyleByClass("span","esum","background","#FFF79D");

	var hion  = getStyleObject("hion");
	var hioff = getStyleObject("hioff");
	
	hion.display  = "inline";
	hioff.display = "none";
}


function hioff() {
	// Turn highlighting off
	
	setStyleByClass("span","esum","background","transparent");

	var hion  = getStyleObject("hion");
	var hioff = getStyleObject("hioff");
	
	hion.display  = "none";
	hioff.display = "inline";
}





//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) {
	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() {
	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) {
	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 = "";
		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);
}



// Remove old cookies that get in the way of our new domain cookies
function removeOldCookies() {
	deleteCookie(styleCookieName, "www.levitt.com");
	deleteCookie(styleCookieName, "levitt.com");
	deleteCookie(styleCookieName, "store.levitt.com");
}




/* -------------------------------------- */
/* Table striping 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);
	}
}





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



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


addHandler("resize", fixNav);  // Set to adjust left column (navigation) to match page height when resized

// Add initializer functions in this file
//addHandler("load", fixMargin);   // Remove after all pages have been updated
addHandler("load", fixNav);
addHandler("load", styleStartup);
addHandler("load", fixAllEmails);
addHandler("load", externalLinks);
addHandler("load", function() {fixNav();} );   // Call fixNav() again now that we've changed the page to expand emails; Doesn't work when fixNav is added a second time as a load handler

addHandler("unload", styleShutdown);


styleStartup();  /* For some reason, this is sometimes necessary */

