/*!
// common.js -- common Javascript functions, included on all pages
// www.levitt.com  2003-04
// by Greg Hartwig (greg at hartwig dot com)
*/

// Compile at: http://closure-compiler.appspot.com/home


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

// Use our current actual domain for the cookie
var domainPos, cookieDomain='';
domainPos = window.location.host.search(/levitt/i);
if (domainPos >= 0)
	cookieDomain = window.location.host.substr(domainPos);
if (cookieDomain)
	cookieDomain = "."+cookieDomain;
// Example values:  .levitt.com, .levitt.tv
// Actually, this is a bad idea for performance.
// It causes the cookies to be sent for every http request



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



function validate_mlform(theForm) {
	var msgtxt = "";
	if (theForm["title"].value == "")     msgtxt+="Enter a title.\n";
	if (theForm["first_name"].value == "" &&
		 theForm["last_name"].value == "") msgtxt+="Enter a name.\n";
	if (theForm["address"].value == "")   msgtxt+="Enter a street.\n";
	if (theForm["city"].value == "")      msgtxt+="Enter a city.\n";

	if (theForm["phone_number"].value != "" && /[^0-9\-\+ ]/.test(theForm["phone_number"].value) )
			msgtxt+="Phone number contains invalid characters\n";


	if (theForm["email_address"].value != "") {
		if (theForm["email_address"].value.indexOf('@') < 0)
			msgtxt+= "e-mail must contain '@'\n";

		if (theForm["email_address"].value.indexOf('.') < 0)
			msgtxt+= "e-mail must contain '.'\n";
	}
	

	if (msgtxt != "") {
		alert(msgtxt);
		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() {
	// With JQuery (tested):
	/**
	$("a[href^='email:'], area[href^='email:']").each(function(index) {
		var emailaddr = unscrambleEmail(unescape($(this).attr("href").substr(6)));
		$(this).attr("href", "mailto:" + emailaddr);
		// If text inside anchor tags is empty, set it to the email address
		if ($(this).text() == "")
			$(this).text(emailaddr);
	});
**/

	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
				
				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() {
	// With JQuery:
	$("span.esum").removeClass("plain");
	$("#hioff").hide();
	$("#hion").show();
}


function hioff() {
	// With JQuery:
	$("span.esum").addClass("plain");
	$("#hion").hide();
	$("#hioff").show();
}


function MSIE_hoverfix() {
	// With JQuery (untested):
	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", "");
				}
			}
		}
	}
*/

}




// 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:
	//alert("setting style to "+reqstyle);
	$("link[rel~='stylesheet'][title]").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:
	//var title = $("link[rel~='stylesheet'][title]:enabled").eq(0).attr("title");
	// Above line won't work because :enabled only works with form elements, apparently

	$("link[rel~='stylesheet'][title]").each(function(index) {
		if (!this.disabled) {
			title = $(this).attr("title");
			return title;
		}
	});


	//alert("active="+title);
	return 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");
		// Return the first active named style
		if (tag.getAttribute("rel").indexOf("style") != -1 && stylename && !tag.disabled)
			return stylename;
	}
	return null;
*/
}


function getPreferredStyleSheet() {
	// With JQuery:
	var title = $("link[rel~='stylesheet']:not([rel~='alternate'])[title]").eq(0).attr("title");
	//alert("preferred="+title);
	return title;
/*
	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;
		if (cookieDomain)
			cookievalue += "; domain="+cookieDomain;
		cookievalue += "; 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() {
	//alert("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");
}





/* -------------------------------------- */
/* 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 swapTab(oldActive, newActive) {
	// Swap out divs
	//$("#video-"+oldActive).fadeOut(); 
	$("#frame-"+oldActive).fadeOut('normal', function() {$("#frame-"+newActive).fadeIn(); }); 
	
	// Change active tab
	$("#tab-"+newActive).addClass("active");
	$("#tab-"+oldActive).removeClass("active");
	return false;
}


var activeTab = "";
function activateTab(newActive) {
	if (activeTab != newActive) {
		// Swap out divs
		$("#frame-"+activeTab).fadeOut('normal', function() {$("#frame-"+newActive).fadeIn(); }); 
		//$("#frame-"+activeTab).fadeOut('normal');
		$("#frame-"+activeTab).hide();  // Needed for JQuery 1.3.2 with Firefox
		//$("#frame-"+newActive).fadeIn(); 
		
		// Change active tab
		$("#tab-"+newActive).addClass("active");
		$("#tab-"+activeTab).removeClass("active");
		
		activeTab = newActive;
	}
	return false;
}




// Thinks we can do immediately (before DOM loads)
var has_cookies, on_iPhone;
function startup_common() {

	// This check will detect the browser cookie accept setting immediately (no reload required)
	// The PHP version requires a reload for the server to be informed
	if (readCookie("cookie_test") != "true")
		createCookie("cookie_test", "true", 0);
	has_cookies = ("true" == readCookie("cookie_test"));
	
	// See if we're on iPhone/iPod (not iPad!), i.e. small device
	on_iPhone  = (navigator.userAgent.search(/iPhone/i) >= 0) || (navigator.userAgent.search(/iPod/i) >= 0);
	for_iPhone = on_iPhone && (-1 == window.location.search.search(/^\?full/i));
	
	// Set targets (since they're not valid in xhtml)
	$("a[rel=mediafile]").attr("target", "mediawindow");
	$("a[rel=verse]").attr("target", "verse");
	$("a[rel=newwindow]").attr("target", "_blank");
}




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



// Call startup functions
$(document).ready(function() {
	//styleStartup();
	fixAllEmails();
	externalLinks();
	MSIE_hoverfix();
	
	
	// $("img[title], abbr, a[title]").tooltip({xtip: '.tooltip', predelay: 400, fadeOutSpeed: 100, opacity: 0.9});
	
});


startup_common();


// Set to run when pages unload
//$(window).unload(styleShutdown);

