var nsie5 = (document.documentElement) ? true : false;
var rehash = false;
var _editor_width = "524px";
function getElem(elemID) {
	return document.getElementById(elemID);
}

window.onload = twgInit;

function twgInit() {      
    if (!nsie5) return;
    
      if (location.search.indexOf("popup=true") != -1) {
       //alert('test');
    		document.body.className="popup";
    	}
    	
   /* var url;
    for (var i=0; i<document.images.length; i++) {
        url = document.images[i].src;
        if (url.indexOf("twg.int")!=-1) {
            document.images[i].src = url.replace(/twg.interprisesoftware/,"www.thewordguild");
        }
    } */
  
    if (location.href.indexOf("editor/editor.html")>1) { 
        var cs = getElem("content").style;
        cs.padding = "0";
        cs.width = "530px";
        cs.display = "";
        getElem("sidebar").style.paddingRight = "0";
        getElem("masthead").style.display = "none";
        getElem("footer").style.display = "none";
    } else {
    	if (!rehash) {
        checkFaculty(); //in case function call accidentally gets deleted with wysiweb
    	}
    	if (rehash && location.hash.length>1) {
        location.hash=location.hash; //refresh to ensure correct location after css and images load
    	}

    }
 /*   var menu = getElem("mainMenu");

    ua = navigator.userAgent.toLowerCase();   
    if (ua.indexOf("os x") != -1 || ua.indexOf("msie 5.2") != -1) {
      //Mac OS X - assume American Typewriter font avail.
      menu.style.letterSpacing = "0";
    }

				
    if (location.href.indexOf("/membercare")==-1 && getElem("memberLogin")) {
        getElem("memberLogin").style.display="block";
    }
    */
    if (location.href.indexOf("/members_only") != -1) {
        getContent();
    } else if (location.href.indexOf("editor/editor.html")==-1) {
			findEmails();
			fixLinks();
        brFixTables();
        //getElem("content").onclick = checkLink;
    }
    

}

function makeEmail(recipient,domain) {
	if (!domain) domain = location.host;
	if (domain.indexOf("www")==0) domain = domain.substring(4);
	return (recipient + "@" + domain);
}

function emailLink(recipient,domain) {
	addr = makeEmail(recipient,domain);
	return '<a href="mailto:' + addr + '">' + addr + '</a>';
}

function findEmails(elem) {
	for (var i = 0; i < document.links.length; i++) {
		href = document.links[i].href.toLowerCase();
		if (href.indexOf("ismail:")==0) {
			document.links[i].href = "mailto:" + convertEmail(href);
		}
	} 
	if (!elem) elem = document.body;
	do { //keep checking all html until we catch all instances
		html = elem.innerHTML;
		x = html.toLowerCase().indexOf("ismail:");
		if (x !=- 1) {
			endChunk = html.substring(x+7);
			startChunk = html.substring(0,x);
			addr = "";
           // fullAddress = endChunk.match(/^[A-Z0-9._-]+%[A-Z0-9._-]+\.[A-Z]{2,4}\b/);
			fullAddress = endChunk.match(/^[\w\-_\.]+%[\w\-_\.]+\.\w+\b/);//^\w+%\w+\.\w+\b/);
			if (fullAddress) {
				addr = fullAddress[0].split("%");
				addr = emailLink(addr[0],addr[1]);
				endChunk = endChunk.substring(fullAddress[0].length);					
			} else {
				recip = endChunk.match(/^[\w\-_\.]+\b/);
				if (recip) {
					addr = emailLink(recip[0]);
					endChunk = endChunk.substring(recip[0].length);
				}
			}
			elem.innerHTML = startChunk + addr + endChunk;
		}
	} while (x != -1) 
}

function convertEmail(text) {
	addr = stripSpaces(text.substring(7));
	fullAddress = addr.match(/^[\w\-_\.]+%[\w\-_\.]+\.\w+\b/);
	//fullAddress = addr.match(/^\w+%\w+\.\w+\b/);
	if (fullAddress) {
		addr = fullAddress[0].split("%");
		return makeEmail(addr[0],addr[1]);
	} 
	if (addr.match(/^[\w\-_\.]+$/)) {
		return makeEmail(addr);
	}
	return "";
}

function fixLinks() {
  domain = location.host;
  j = document.links.length - 1;
  for (i=10; i<=j; i++)   { //start after masthead links...
    objLink = document.links[i];
    url = objLink.href;
   // objLink.href = url.replace("membercare","membersonly");
    if (url.indexOf(domain) == -1 && objLink.target == "" && url.indexOf("javascript") == -1 && url.indexOf("mailto") == -1) {
      objLink.target = "_blank";
      if (objLink.title=="") objLink.title = "Opens in new window";
    } else if (url.indexOf("faculty")!=-1 && objLink.hash.indexOf("masthead")==-1) {
        objLink.onclick = function () { return bioPopUp(this); };
        objLink.title = "Opens in pop-up window";
    }
  }
}

function bioPopUp(linkObj) {
    if (linkObj.hash.length>1) {
	makePopUp(linkObj.href,500,315);
        //newWindow = window.open(linkObj.href,"PopUp","status,titlebar,resizable,width=500,height=330");
	//newWindow.focus();
        return false;
    }
    return true;
}

var rxJpg = /.*\/(\w)([\w-]+)\.jpe?g$/i;
function checkFaculty() {
    if (location.hash.length>1 && opener && !opener.closed && opener.location.href.indexOf("wordguild.")!=-1) {
        if (getElem("faculty") || document.title.indexOf("Faculty")!=-1) {
        	var image = document.images
        	for (var i = image.length; --i > 1;) { // all but first 2
        		if (image[i].src.match(rxJpg)) {
        			image[i].parentNode.id = RegExp.$1.toUpperCase() + RegExp.$2;
        		}
        	}
           document.body.className = "popup";
           rehash=true;
        }
    }
}

function toggle(elemId) {
	with (getElem(elemId)) {
		className = (className=="faq2") ? "" : "faq2";
	}
}

function checkLink(e) {

    if (window.event) {
	targetObj = event.srcElement;
    } else if ( (e) && (typeof e == "object") && (e.target) ) {
        targetObj = e.target;
    }
    if (targetObj && targetObj.tagName=="A") {
	if (targetObj.href.indexOf("faculty")!=-1 && targetObj.hash.length>1) {
            //targetObj.href += "?popup";
            makePopUp(targetObj.href,500,315);
           // newWindow = window.open(targetObj.href,"PopUp","status,titlebar,resizable,width=500,height=315");
            //newWindow.focus();
            return false;
	}
    }
    return true; 
}

function stripSpaces(str) { 
  //remove leading and trailing spaces
  return str.replace(/^\s*/, "").replace(/\s*$/, ""); 
}
function brFixTables() {
  if (nsie5) {
	tblArray = document.getElementsByTagName("TABLE"); 
	for (t=0; t<tblArray.length; t++) { 
		elem = tblArray[t];
		if (elem.className=="data") {
			colourRows(elem);
		}
	}
  }
}
function colourRows(tbl) { //give even rows of table a grey stripe
  var start = tbl.thead ? 1 : 0;
  for (var i=start; (i<tbl.rows.length && tbl.rows[i].className.indexOf("noStripes")==-1); i++) {
    if (tbl.rows[i].className.indexOf("subHeader")==-1) {
	  if (i%2==0) {
	    brAddClass(tbl.rows[i],"stripe");
	  }
	}
  }
}


function brAddClass(elem,classStr) {
	cn = elem.className;
	if (cn.indexOf(classStr) == -1) { // only add if not found
		//ie mac cant deal with leading whitespace
		elem.className = (cn != "") ? (cn + " " + classStr) : classStr;
	} 
}

function makePopUp(url,w,h,showMenuBar) {
	features = "status,titlebar,resizable,scrollbars,width="+w+",height="+h;
	if (showMenuBar) {
		features = "menubar," + features;
	} 
	newWindow = window.open(url,"PopUp",features);
	newWindow.focus();
}
function memberLogin(f) {
    var x = parseInt(f.x.value);
    if (isNaN(x)) x=1;
    f.x.value = x*x;
}

var rxContent = /^[^\0]+<body[^>]*>([^\0]*?)<\/body>/i;
var rxTitle = /^[^\0]+<title[^>]*>([^\0]*?)<\/title>/i;
//var ISmail = ["", "%([\w-_]+\.\w+\b)"];
var rxEmail1 = /ismail:([\w\-_\.]+)/gi;
var rxEmail2 = /ismail:([\w\-_\.]+)%([\w\-_\.]+\.\w+)\b/gi;
var rxMailTo1 = /href=".*ismail:([\w\-_\.]+)"/gi;
var rxMailTo2 = /href=".*ismail:([\w\-_\.]+)%([\w\-_\.]+\.\w+)"/gi;
function getContent() {
	var httpReq = false; 
	try {
    	if (window.XMLHttpRequest) {     // native XMLHttpRequest object
        	httpReq = new XMLHttpRequest(); 
    	} else if (window.ActiveXObject) {    // IE/Windows version
        	try {
        		httpReq = new ActiveXObject("Msxml2.XMLHTTP");
      		} catch(e) {
	  				httpReq = new ActiveXObject("Microsoft.XMLHTTP");
					}
    	}
    } catch (e) { }
    if (httpReq) {
    	httpReq.onreadystatechange = function() {
    		if (httpReq.readyState == 4 && httpReq.status == 200) {
    			var domain = location.host;
					if (domain.indexOf("www")==0) { domain = domain.substring(4); }
    			var html = httpReq.responseText.replace(/memberedit/g,"members_only").replace(/member\sedit/gi,"Members Only");
    			html = html.replace(rxMailTo2, 'href="mailto:$1@$2"');
    			html = html.replace(rxMailTo1, 'href="mailto:$1@' + domain + '"');
    			html = html.replace(rxEmail2, '<a href="mailto:$1@$2">$1@$2</a>');
    			html = html.replace(rxEmail1, '<a href="mailto:$1@' + domain + '">$1@' + domain + '</a>');
    			if (html.match(rxContent)) {
    				document.body.innerHTML = RegExp.$1;
    			}
    			if (html.match(rxTitle)) {
    				document.title = RegExp.$1;
    			}
    			getElem("content").style.display="";
    			setTimeout(function() {
    			//	findEmails();
						fixLinks();
        		brFixTables();
        	}, 50);
    		}
    	};
    	var path = location.pathname.replace("members_only","memberedit");
    	httpReq.open("GET", path, true);
      httpReq.send("");
    } 
}
