// Shared JavaScript code for http://www.pixeldevelopment.com by Peter Jones

// Based on an idea from http://www.alistapart.com/articles/bodyswitchers/
// FYI: MUST use letter for first name of class.  Eg: pass "wide".

var pmjStyleSwitcher = new Array(9);
var myStyles = new Array(9);
var pmjInitBodyClasses;
var pmjStyleFirstRun;

pmjStyleFirstRun = true;

pmjCurrVersion = "3";

myStyles[0] = "style_version";
myStyles[1] = "style_color";
myStyles[2] = "style_layout";
myStyles[3] = "style_align";
myStyles[4] = "style_font";
myStyles[5] = "style_size";
myStyles[6] = "style_css"; // off or blank
myStyles[7] = "style_linksnewwindow";
myStyles[8] = "style_threecolumn";

for(var i=0; i < myStyles.length; i++)
	pmjStyleSwitcher[myStyles[i]] = "";

function pmjResetStyles()
{
	pmjZapStyleCookies();
	for(var i=0; i < myStyles.length; i++)
		pmjStyleSwitcher[myStyles[i]] = "";
	pmjStyleSwitcher["style_version"] = pmjCurrVersion;
	pmjStyleSwitcher["style_color"] = "highc";
	pmjStyleSwitcher["style_layout"] = "narrow";
	pmjStyleSwitcher["style_align"] = "leftalign";
	pmjStyleSwitcher["style_threecolumn"] = "threecolumn";
	pmjWriteStylesToCookie();
	pmjSetBodyClass();
	// highc narrow leftalign threecolumn
}

function pmjZapStyleCookies()
{
	for(var i=0; i < myStyles.length; i++)
		deleteCookie(myStyles[i]);
}

function pmjWriteStylesToCookie()
{
	for(var i=0; i < myStyles.length; i++)
		createCookie(myStyles[i], pmjStyleSwitcher[myStyles[i]], 365);
}

function pmjValidateStyles()
{
	version = parseInt(pmjStyleSwitcher["style_version"]);
	pmjStyleSwitcher["style_version"] = pmjCurrVersion;

	switch (version)
	{
		case 3:
			break;
		default:
			pmjResetStyles();
	}
}

function pmjReadStylesFromCookie()
{
	for(var i=0; i < myStyles.length; i++)
	{
		pmjStyleSwitcher[myStyles[i]] = "";
		style = readCookie(myStyles[i]);
		if (style)
			if (style != "null")
				pmjStyleSwitcher[myStyles[i]] = style;
	}
	pmjValidateStyles();
}

function pmjSetBodyClass()
{
	prev = document.getElementsByTagName('body')[0].className;
	bodyClasses = pmjInitBodyClasses;
	for(var i=1; i < myStyles.length; i++)
		if (pmjStyleSwitcher[myStyles[i]])
			bodyClasses = bodyClasses + " " + pmjStyleSwitcher[myStyles[i]];

	bodyClasses = replacestring(bodyClasses, "seriffont bigfont", "serifbigfont", true);

	document.getElementsByTagName('body')[0].className = bodyClasses;
//	document.title = '<' + bodyClasses.replace(/ /g,'_') + '>'; // for debug

	cssEnabled = (pmjStyleSwitcher["style_css"].length == 0);
	enableMainStyleSheet(cssEnabled);
}

function enableCssIfDiffGroup(group)
{
	if (group != "style_css")
		pmjStyleSwitcher["style_css"] = "";
}

function pmjGroupExists(group)
{
	found = false;
	for(var i=0; i < myStyles.length; i++)
		if (myStyles[i] == group)
			found = true;
	return found;
}

function pmjSetStyle(group,className)
{
	if (pmjGroupExists(group))
	{
		enableCssIfDiffGroup(group);
		pmjStyleSwitcher[group] = className;
		pmjSetBodyClass();
		pmjWriteStylesToCookie();
	}
}

function pmjToggleStyle(group,className1, className2)
{
	if (pmjGroupExists(group))
	{
		enableCssIfDiffGroup(group);
		if (pmjStyleSwitcher[group] == className1)
			pmjStyleSwitcher[group] = className2;
		else
			pmjStyleSwitcher[group] = className1;
		pmjSetBodyClass();
		pmjWriteStylesToCookie();
	}
}


function enableMainStyleSheet(enable) {
	var i, a;

	for(i=0; (a = document.getElementsByTagName("link")[i]); i++)
		if(a.getAttribute("rel").indexOf("style") != -1
		   && !a.getAttribute("title"))
			a.disabled = !enable;
}


// code for creating style switcher controls using DOM
// Created using Javascript to avoid search engines reading non-content code. PMJ

function createLink(url, onClickCode, title)
{
	var newLink = document.createElement("a");
	if (url.length > 0)
		newLink.setAttribute("href", url);
	if (onClickCode.length > 0)
	{
		newLink.setAttribute("onclick", onClickCode);
		if ((document.all)&&(document.getElementById))
			newLink.onclick = new Function(onClickCode);
	}
	if (title.length > 0)
		newLink.setAttribute("title", title);
	return newLink;
}

function createImg(src, border, className, title, height, width)
{
	var newImg = document.createElement("img");
	if (src.length > 0)
		newImg.setAttribute("src", src);
	if (className.length > 0)
	{
		newImg.setAttribute("class", className);
		newImg.setAttribute("className", className); // Explorer!
	}
	if (border >= 0)
		newImg.setAttribute("border", border);
	newImg.setAttribute("height", height + "px" );
	newImg.setAttribute("width", width + "px" );
	if (title.length > 0)
	{
		newImg.setAttribute("title", title);
		newImg.setAttribute("alt", title);
	}
	return newImg;
}

function createBR()
{
	var newBR = document.createElement("br");
	return newBR;
}

/* language translation code */

function addLanguage(thisURL, babelLang, imageName, desc)
{
	try {
		desc = unescape(desc);
	}
	catch (e) {}
	if (babelLang == "")
	{
		theUrl = thisURL; 
		theUrl = replacestring(theUrl, "www.pixeldevelopment.com/www.pixeldevelopment.com/", "www.pixeldevelopment.com/", true);
		theUrl = replacestring(theUrl, "74.220.207.70/%E2%80%BEpixeldev", "74.220.207.70/~pixeldev", true);
		theUrl = replacestring(theUrl, "74.220.207.70/%7Epixeldev", "74.220.207.70/~pixeldev", true);
		theTitle  = desc;
	}
	else
	{
    // theUrl = "http://babelfish.altavista.com/babelfish/urltrurl?tt=url&url="+escape(thisURL)+"&lp="+babelLang;
    theUrl = "http://babelfish.yahoo.com/translate_url_load?lp=" + babelLang + "&trurl="+escape(thisURL);
		theTitle = desc + " (Yahoo Babelfish)";
	}
	theImage = createImg("css/"+imageName, 0, "", theTitle, 14, 20);
	theLink  = createLink(theUrl, "", "");
	theLink.appendChild(theImage);
	theNode = document.getElementById("translate");
	if (theNode)
		theNode.appendChild(theLink);
}

// escape table http://developer.irt.org/script/100.htm

function addTranslation(thisURL) {
	if (document.getElementById)
	{
		theNode = document.getElementById("translate");
		thisURL = "http://www.pixeldevelopment.com/"; // theNode.title;
		addLanguage(thisURL, "",	"en_flag.gif", "View in original English");
		addLanguage(thisURL, "en_fr", "fr_flag.gif", "View in French");
		addLanguage(thisURL, "en_de", "de_flag.gif", "View in German");
		addLanguage(thisURL, "en_nl", "nl_flag.gif", "View in Dutch");
		addLanguage(thisURL, "en_el", "el_flag.gif", "View in Greek");
		addLanguage(thisURL, "en_es", "sp_flag.gif", "View in Spanish");
		addLanguage(thisURL, "en_ja", "jp_flag.gif", "View in Japanese");	
		addLanguage(thisURL, "en_zh", "zh_flag.gif", "View in Chinese");
	}
}


/* style switcher controls */

function controlSetStyle2(clickCode, image, className, title) {
	clickCode = clickCode + "; return false;";
	theImage = createImg("css/"+image, -1, className, title, 20, 20);
	theLink  = createLink("#", clickCode, "");
	theLink.appendChild(theImage);
	theNode = document.getElementById("styleswitch");
	theNode.appendChild(theLink);
}

function controlSetStyle(styleKind, setting, image, className, title) {
	clickCode = "pmjSetStyle('"+styleKind+"','"+setting+"')";
	controlSetStyle2(clickCode, image, className, title);
}

function controlToggleStyle(styleKind, setting1, setting2, image, className, title) {
	clickCode = "pmjToggleStyle('"+styleKind+"','"+setting1+"','"+setting2+"')";
	controlSetStyle2(clickCode, image, className, title);
}


function addStyleSwitcherControls() {
	var newHeader = document.createElement("h3");
	var newText = document.createTextNode("Preferences");
	newHeader.appendChild(newText);		
	theNode = document.getElementById("styleswitch");
	if (theNode)
	{
		theHeader = document.getElementById("styleswitchheader");
		if (theHeader)
			theHeader.className = "";

		controlSetStyle('style_color', 'lowc',  'stylesoft.gif', 's1low', 'Low Contrast');
		controlSetStyle('style_color', 'highc', 'stylecontrast.gif', 's1high', 'High Contrast');
//		controlSetStyle('style_color', 'reverse',  'stylereverse.gif', 's1rev', 'Reverse');
		controlSetStyle('style_color', 'reverse2', 'stylereverse.gif', 's1rev2', 'Reverse');
		controlSetStyle2("pmjToggleStyle('style_css','off','');", "styleplain.gif", "s1plain", "Unstyled");
		controlSetStyle2("pmjResetStyles()", "stylereset.gif", "s9reset", "Default")

		var theBR = createBR();
		theNode = document.getElementById("styleswitch");
		theNode.appendChild(theBR);

		controlToggleStyle('style_layout', 'wide', 'narrow', 'stylewide.gif', 's1wide', 'Wider page');
		controlToggleStyle('style_align', 'leftalign', 'justify', 'styleleftalign.gif', 's1align', 'Left align text');
		controlToggleStyle('style_threecolumn', 'threecolumn', '', 'stylethreecol.gif', 's1threecolumn', 'Three columns');
		controlToggleStyle('style_size', 'bigfont', '', 'stylebigfont.gif', 's1fontsize', 'Larger text');
		controlToggleStyle('style_font', 'seriffont', '', 'styleseriffont.gif', 's1serif', 'Serif text');
//		controlSetStyle2("toggleExternalLinks()", "stylelinktoggle.gif", "s1extlinks", "External sites to new window")
	}
}


// cannot be placed within the body.onload because <body> isn't defined yet? nope just window.onload

function pdInitialize() {
	if (document.getElementById)
	{
		pmjInitBodyClasses = "pmj";
	//	pmjZapStyleCookies();
		pmjReadStylesFromCookie();
		pmjSetBodyClass();
		pmjStyleFirstRun = false;
		emailCloak();
		addStyleSwitcherControls();
		addTranslation("");
	}
}

window.onload = pdInitialize;

function showPDGallery(callingPage, gallery, imagePath, touchupSetting)
{
	galleryUrl = 'showgallery.asp?gallery='+gallery+"&image=" + imagePath + touchupSetting;
	if (callingPage != "")
		galleryUrl = galleryUrl + '&caller=' + callingPage;
	winParams = 'top=10,left=10,scrollbars=no,status=no,resizable=yes,width=780,height=515';
	GGalleryWin = window.open(galleryUrl, 'PDGallery', winParams);
}

function showPDImage(callingPage, gallery, imagePath) {
	return showPDGallery(callingPage, gallery, imagePath, "");
}


function showPDImageTouchup(callingPage, gallery, imagePath) {
	return showPDGallery(callingPage, gallery, imagePath, "&touchup=on");
}




// Cookie routines

function createCookie(name,value,days) { 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) { 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); if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length); } return null; }

function deleteCookie(name) {
  var now = new Date();
  var exp = new Date(now.getTime() - 1);
  document.cookie = name + "=;" +
                    "expires=" + exp.toGMTString() + ";" + 
                    "path=/";
}


// *Offered freely by Darren J Semotiuk, Collaborative Learning Network Inc., http:////www.co-learn.net/ Just keep this comment line intact. Thanks! *

function replacestring(str_normal,str_find,str_replace,int_case_insensitive)
{
	if (arguments.length<3 || str_find=="" || str_normal=="" ||
 typeof("".split)!="function")
		return(str_normal);

	//no parm means default, "case SENSITIVE"...
	if(!(int_case_insensitive))
		return(str_normal.split(str_find)).join(str_replace);

	str_find=str_find.toLowerCase();

	var rv="";
	var ix=str_normal.toLowerCase().indexOf(str_find);
	while(ix>-1)
	{
		rv+=str_normal.substring(0,ix)+str_replace;
		str_normal=str_normal.substring(ix+str_find.length);
		ix=str_normal.toLowerCase().indexOf(str_find);
	};
	return(rv+str_normal);
}



// AutoBlink
// Puts Google's Autolink on the Blink :)
// (c) 2005 Chris Ridings http://www.searchguild.com
// Redistribute at will but leave this message intact
// PMJ: added try to catch errors if the browser is not Explorer

var linkcount;
function checklinks() {
  try {
  if (!(linkcount==document.links.length)) {
   // Something changed the links!
   // Iterate for an id of _goog
   for (i=0; i < document.links.length; i++) {
    if (document.links[i].id.substring(0,5)=="_goog") {
     // If we find an id of _goog then remove the link!
     var tr = document.links[i].parentTextEdit.createTextRange();
     tr.moveToElementText(document.links[i]);
     tr.execCommand("Unlink",false);
     tr.execCommand("Unselect",false);
    }
   }
  }
   setTimeout("checklinks()",2000);
 }
 catch (e)
 {
 }
}
if (document.getElementById && document.createElement) {
  linkcount=document.links.length;
  setTimeout("checklinks()",2000);
}



// http://www.badboy.ro/articles/2005-01-25/index.php
// note: XHTML you cannot use document.write

function emailCloak() {
	if (document.getElementById) {
		var alltags = document.all? document.all : document.getElementsByTagName("*");
		for (i=0; i < alltags.length; i++) {
		  if (alltags[i].className == "emailCloak") {
		  	var oldText = alltags[i].firstChild;
		  	var emailAddress = alltags[i].firstChild.nodeValue;
		  	var user = emailAddress.substring(0, emailAddress.indexOf("("));
		  	var website = emailAddress.substring(emailAddress.indexOf(")")+1, emailAddress.length);
		  	var newText = user+"@"+website;
		  	var a = document.createElement("a");
		  	a.href = "mailto:"+newText;
			a.className = "textlink";
			var address = document.createTextNode(newText);
			a.appendChild(address);
			alltags[i].replaceChild(a,oldText);
		  }
		}
	}
}

function setObjClasses(objName, objClasses)
{
	if (document.getElementById)
		document.getElementById(objName).className = objClasses;
}
