//LWB Ajax Browse

var scriptincludes = new Array();
var srctags = new Array("img");
var hreftags = new Array();
var pagehead = document.getElementsByTagName("head")[0];
var ajaxloadexec = "";
var lwbpageajax = false; //whether or not ajax is enabled or disabled
var lwbajaxloaded = false;
if (typeof lwb == 'undefined') var lwb = true;
if (lwb) {
	document.write("<base id='ajaxbase' href=" + location.href + "\">");
	document.write("<style type='text/css'>.lwbnavigation { display:none; } .hidden-iframe { visibility: hidden; border-width: 0;height: 0;width: 0;overflow: hidden;} #iframe-div {visibility: hidden;height: 0;width: 0;overflow: hidden;}.showtermshighlight {color:blue; background-color:yellow;}</style>");
	var lwbwebsite = "";
}
var hashListener = {ie:/MSIE/.test(navigator.userAgent),ieSupportBack:true,hash:document.location.hash,check:function () {var h = document.location.hash;if (h != this.hash) {this.hash = h;this.onHashChanged();}},init:function () {if (this.ie && this.ieSupportBack) {var frame = document.createElement("iframe");frame.id = "state-frame";frame.style.display = "none";document.body.appendChild(frame);this.writeFrame("");}var self = this;if ("onpropertychange" in document && "attachEvent" in document) {document.attachEvent("onpropertychange", function () {if (event.propertyName == "location") {self.check();}});}window.setInterval(function () { self.check() }, 50);},setHash: function (s) {if (this.ie && this.ieSupportBack) {this.writeFrame(s);}document.location.hash = s;},getHash: function () {return document.location.hash;},writeFrame:function (s) {var f = document.getElementById("state-frame");var d = f.contentDocument || f.contentWindow.document;d.open();d.write("<script>window._hash = '" + s + "'; window.onload = parent.hashListener.syncHash;<\/script>");d.close();},syncHash:function () {var s = this._hash;if (s != document.location.hash) {document.location.hash = s;}},onHashChanged:function () {}};
var pagerequest = function () {
	this.fetchingdata = false;
	this.datareceived = null; 
	this.datasuccess = false; 
	this.requestlink = '';
	this.execdata = null;
	this.waitingcode = null;
	this.waitinginterval = null;
	this.waitingintervalms = 500;
	this.fetchmethod = 'GET';
	this.content_type == null;
	this.async = true;
	this.prerror = function(e){alert(e);}; //empty function
	var pagerequest_self = this;
	this.forcerefresh = true;
	var poststr = null;
	this.response = '';
	this.sendrequestlink = null;
	this.ajaxsupport = true;
	this.convertlinks = true;
	this.onreadystatechange = function() { try { var contentdisp = pagerequest_self.datareq.getResponseHeader("Content-Disposition"); } catch (e) {var contentdisp = false;} if (contentdisp) { window.location.href = pagerequest_self.requestlink; pagerequest_self.fetchingdata = false; return; }
		if (pagerequest_self.datareq.readyState == 4) pagerequest_self.requestreturn();};
	if (window.XMLHttpRequest) {     // Object of the current windows 
		this.datareq = new XMLHttpRequest();     // Firefox, Safari, ...
	} else if (window.ActiveXObject) {  // ActiveX version
		try {this.datareq = new ActiveXObject("MSXML2.XMLHTTP"); } catch (e) {
			try{ this.datareq = new ActiveXObject("Microsoft.XMLHTTP"); }  catch(e) {this.ajaxsuppport=false;this.prerror('AJAX could not be enabled in your browser. Please make sure you have javascript and ActiveX enabled.');return;}}// Internet Explorer
	} else {
		this.fetchingdata = false;this.ajaxsupport = false;this.prerror('AJAX could not be enabled in your browser. Please make sure you have javascript and ActiveX enabled.');return;
	}
	this.requestreturn = function() {
		if (String(pagerequest_self.datareq.status).match(/(200)|(304)/)) {
			pagerequest_self.processreq(pagerequest_self.datareq.responseText);
		} else {
			pagerequest_self.prerror("Could not connect to Living Word Broadcast. Please make sure that you are connected to the internet (or maybe you clicked on a bad link). Page: " + pagerequest_self.requestlink  + "\r\n"+ pagerequest_self.datareq.statusText);
			pagerequest_self.fetchingdata = false;
		}
	}
	this.sendreq = function () {
		if (pagerequest_self.fetchingdata) {
			return;
		}
		pagerequest_self.fetchingdata = true;
		pagerequest_self.sendrequestlink = pagerequest_self.requestlink;
		if (pagerequest_self.content_type == null) {
			if (pagerequest_self.fetchmethod.toUpperCase() == "GET")
				pagerequest_self.content_type = "text/html";
			else pagerequest_self.content_type = "application/x-www-form-urlencoded";
		}
		if (pagerequest_self.fetchmethod.toUpperCase() == "GET") {
			if (pagerequest_self.forcerefresh) { 
				if (pagerequest_self.requestlink.indexOf("?") != -1) {
					pagerequest_self.sendrequestlink += "&randajaxid=" + Math.random();
				} else {
					pagerequest_self.sendrequestlink += "?randajaxid=" + Math.random();
				}
			}
		}
		pagerequest_self.datareq.open(pagerequest_self.fetchmethod, pagerequest_self.sendrequestlink, pagerequest_self.async); 
		if (pagerequest_self.async) {pagerequest_self.datareq.onreadystatechange = pagerequest_self.onreadystatechange;	}
		pagerequest_self.datareq.setRequestHeader("Content-Type", pagerequest_self.content_type);  
		pagerequest_self.datareq.send(pagerequest_self.poststr);
		if (pagerequest_self.waitingcode != null) pagerequest_self.waitinginterval = window.setInterval(pagerequest_self.waitingcode,pagerequest_self.waitingintervalms);
		if (!pagerequest_self.async) {
			pagerequest_self.requestreturn();	
		}
	}
	this.processreq = function (datareceived) {
		try { window.clearInterval(pagerequest_self.waitinginterval); } catch (e) {}
		if (pagerequest_self.convertlinks) datareceived = convertlinks(datareceived);
		if (pagerequest_self.execdata) eval(pagerequest_self.execdata);
		pagerequest_self.response = datareceived;
		pagerequest_self.fetchingdata = false;
	}
}
//addEvent & removeEvent
function addEvent( obj, type, fn ){
	if (obj.addEventListener)
		obj.addEventListener( type, fn, false );
	else if (obj.attachEvent)
	{
		obj["e"+type+fn] = fn;
		obj[type+fn] = function() { obj["e"+type+fn]( window.event ); }
		obj.attachEvent( "on"+type, obj[type+fn] );
	}
}

function removeEvent( obj, type, fn )
{
	if (obj.removeEventListener)
		obj.removeEventListener( type, fn, false );
	else if (obj.detachEvent)
	{
		obj.detachEvent( "on"+type, obj[type+fn] );
		obj[type+fn] = null;
		obj["e"+type+fn] = null;
	}
}

//Page Processing
function convertlinks (html) {
	if (typeof (html) != "string") {
		html = document.body.innerHTML;
		var bodyhtml = true;
	}
	linkregex = new RegExp ("(<a [^>]*)href=([\\]?['\"])(http://"+location.hostname+")?(:"+location.port+")?([^\"']+)([\\]?['\"])([^>]*>)","im");
	while(html.match(linkregex)) {
		var matches = linkregex.exec(html);
		var linkpath = matches[5];
		if (!String(matches[5]).match(/^javascript:/i)) {
			newhref = "javascript:go_to('" + matches[5] + "')";
			html = html.replace(linkregex,"$1hrefreplace=$2" + newhref + "$6$7");
		} else {
			html = html.replace(linkregex,"$1hrefreplace=$2$5$6$7");
		}
	}
	html = html.replace(/hrefreplace=/gim,"href=");
	if (bodyhtml) { 
		document.body.innerHTML = html; 
		lwbajaxloaded = true;
		window.setTimeout(ajaxloadexec,0);
	} else return html;
}
if(typeof HTMLElement!="undefined") {
	if (!HTMLElement.prototype.insertAdjacentElement) {
		HTMLElement.prototype.insertAdjacentElement = function (where,parsedNode) {
			switch (where){
			case 'beforeBegin':
				this.parentNode.insertBefore(parsedNode,this)
				break;
			case 'afterBegin':
				this.insertBefore(parsedNode,this.firstChild);
				break;
			case 'beforeEnd':
				this.appendChild(parsedNode);
				break;
			case 'afterEnd':
				if (this.nextSibling) this.parentNode.insertBefore(parsedNode,this.nextSibling);
				else this.parentNode.appendChild(parsedNode);
				break;
			}
		}
	}
	if (!HTMLElement.prototype.insertAdjacentHTML) {
		HTMLElement.prototype.insertAdjacentHTML = function (where,htmlStr) {
			var r = this.ownerDocument.createRange();
			r.setStartBefore(this);
			var parsedHTML = r.createContextualFragment(htmlStr);
			this.insertAdjacentElement(where,parsedHTML);
		}
	}
	if (!HTMLElement.prototype.insertAdjacentText) {
		HTMLElement.prototype.insertAdjacentText = function (where,txtStr){
			var parsedText = document.createTextNode(txtStr);
			this.insertAdjacentElement(where,parsedText);
		}
	}
}
String.prototype.trim = function() {return this.replace(/^\s+|\s+$/g,"");}
String.prototype.ltrim = function() {return this.replace(/^\s+/,"");}
String.prototype.rtrim = function() {return this.replace(/\s+$/,"");}
function loadpage(pagehtml,loadingarea) {
	var contentstart = '<!--START CONTENT DIV--><DIV ID="CONTENT" STYLE="DISPLAY:INLINE;PADDING:0PX;MARGIN:0PX;">';
	var contentend =   '<\/DIV><!--END CONTENT DIV-->';
	var pagehtmlupper = pagehtml.toUpperCase();
	if (pagehtmlupper.indexOf(contentstart) != -1) {
		var start = pagehtmlupper.indexOf(contentstart) + contentstart.length;
		var end = pagehtmlupper.indexOf(contentend);
	} else if (pagehtmlupper.match(/<body[^>]+>/i)) {
		var bodytag = pagehtml.match(/<body[^>]+>/i);
		var start = pagehtml.indexOf(bodytag) + bodytag.length;
		var end = pagehtmlupper.indexOf("</BODY>");
	} else {
		var start = 0; var end = pagehtml.length-1;
	}
	var pagetitle = pagehtml.substring(pagehtmlupper.indexOf("<TITLE>")+7,pagehtmlupper.indexOf("</TITLE>"));
	document.title = pagetitle;
	var contenthtml = pagehtml.substring(start,end);
	document.getElementById(loadingarea).innerHTML="";
	var contenthtmlarr = contenthtml.split(/<script /i);
	var contenthtmloutput = "";
	if (contenthtmlarr.length == 1) {
		document.getElementById(loadingarea).innerHTML = contenthtml;convertlinkserial();
	} else {
		document.getElementById(loadingarea).insertAdjacentHTML("beforeEnd",contenthtmlarr[0]);window.setTimeout(convertlinkserial,0);
		for (var i=1;i < contenthtmlarr.length;i++) {
			var scripttag = String(contenthtmlarr[i]).match(/^[^>]+>/im);
			if (String(scripttag).toLowerCase().indexOf('src=') != -1) {
				var scriptrep = String(contenthtmlarr[i]).substring(0,String(contenthtmlarr[i]).toLowerCase().indexOf("</script>")+9);
				var scriptregex = /src=['"]([^'"]+)['"]/i;
				var scriptmatch = scriptregex.exec(scripttag);
				var jslink = String(scriptmatch[1]).replace(/^\//,"");
				jscode = fetchjs(scriptmatch[1]);
			} else {
				var scriptrep = String(contenthtmlarr[i]).substring(0,String(contenthtmlarr[i]).toLowerCase().indexOf("</script>")+9);
				var jsstart = String(contenthtmlarr[i]).indexOf(">")+1;
				var jsend = String(contenthtmlarr[i]).toLowerCase().indexOf("</script>");
				var jscode = String(contenthtmlarr[i]).substring(jsstart,jsend);
			}
			while (jscode.match(/document.write\(/i)) {
					jscode = jscode.replace(/document.write\(([^\)]+)\)/i,"document.getElementById('" + loadingarea + "').insertAdjacentHTML(\"beforeEnd\", $1);");
			}
			try {
				if (window._content && typeof(window._content.eval) == 'function') window._content.eval(jscode);
				else if (window.execScript) window.execScript(jscode);
				else  { window.setTimeout(jscode,0); }
			} catch (e) {}
			document.getElementById(loadingarea).insertAdjacentHTML("beforeEnd",String(contenthtmlarr[i]).replace(scriptrep,""));
			window.setTimeout(convertlinkserial,0); //parallel processing
		}
	}
	menuregex = /LWBGenerateMenu.php\?([^'"]+)/i;
	try { var menumatchres = menuregex.exec(pagehtml);
		var menumatch = String(menumatchres[1]).split("=");
		var menutype,prevlink,nextlink;
		for (i=0;i<menumatch.length;i++) {
			if (String(menumatch[i]).indexOf('menutype') != -1) {
				menutype = menumatch[(i+1)].substring(0,String(menumatch[(i+1)]+"&").indexOf("&"));
			}
			if (String(menumatch[i]).indexOf('next') != -1) {
				nextlink = menumatch[(i+1)].substring(0,String(menumatch[(i+1)]+"&").indexOf("&"));
			}
			if (String(menumatch[i]).indexOf('prev') != -1) {
				prevlink = menumatch[(i+1)].substring(0,String(menumatch[(i+1)]+"&").indexOf("&"));
			}
		}
	updatemenu(menutype,prevlink,nextlink);
	} catch (e) {}
	
	loadcss(pagehtml);
	formsupdate();
	try { window.clearTimeout(stats_update_timeout); updatestats();} catch (e) {};
}
hashListener.onHashChanged = function () {
	var pagehash = hashListener.getHash();
	if (!ignorechangedhash) {
		if (String(pagehash).match(/^#LWB:/)) { 
			var matches = String(pagehash).split("#LWB:");
			go_to(matches[1],true);
		} else if (hashListener.getHash().match(/^#?$/)) {
			go_to(window.location.pathname,true);
		}
	} else {
		ignorechangedhash = false;
	}
}
var ignorechangedhash = false;
newpage = new pagerequest();
function go_to (pglink,keephash,tempajax,loadingarea) {
	if ((lwbpageajax||tempajax) && pglink.match(/^[/]/) && !pglink.match(/^http:\/\//i)) {
		newpage.convertlinks = false;
		if (!loadingarea) loadingarea = 'content';
		newpage.requestlink = pglink;newpage.execdata = "loadpage(datareceived,'" + loadingarea + "');";
		newpage.sendreq();
		if (!keephash) {
			ignorechangedhash = true;
			hashListener.setHash("LWB:" + pglink);
		}
	} else {
		if (typeof(playing) == 'undefined') var playing = false;
		if (playing && confirm('Following this link will close the player. Click cancel to to stay on this page and keep playing.')) window.location.href = pglink;
		else window.location.href = pglink;
	}
}
function fetchjs (jslink) {
	var jspagereq = new pagerequest();
	var jsdata;
	jspagereq.requestlink = jslink; //+ ((jslink.indexOf('?') != -1) ? "&" : "?") + "randajaxid=" + Math.random();
	jspagereq.async = false;jspagereq.convertlinks = false;
	jspagereq.execdata = null;
	jspagereq.sendreq();jsdata = jspagereq.response;
	return jsdata;
}
function loadcss (pagehtml) {
	csstagregex = /<style[^>]+>/im;
	var pagehtmlarr = pagehtml.split(csstagregex);
	for (var i=1; i<pagehtmlarr.length;i++) {
		var csstext = String(pagehtmlarr[i]).substring(0,String(pagehtmlarr[i]).toLowerCase().indexOf("</style>")).replace("<!--","").replace("-->","");
		if (csstext.indexOf("csshover.htc") == -1) addcss(csstext);
	}
	pagehtml = pagehtml.replace(/<link([^>]+rel=(['"])?stylesheet)/ig,'<linktobeprocessed\\1')
	while (pagehtml.match(/<linktobeprocessed/i)) {
		linkregex = /<linktobeprocessed([^>]+href=['"]([^'"]+)['"])/i;
		var matches = linkregex.exec(pagehtml);
		if (!String(matches[2]).match(/(TopBotMenu.css)|(tabmenu.css)/i)) {
			var newcss = document.createElement('link');
			newcss.rel = "stylesheet";
			newcss.type = "text/css";
			newcss.href = matches[2];
			pagehead.appendChild(newcss);
		}
		pagehtml = pagehtml.replace(linkregex,"");
	}
}
function addcss (csstext) {
	var newcss = document.createElement("style");
	newcss.type="text/css";
	newcss.media="all";
	csstext = csstext.replace(/\r\n/gm," ");
	var cssrules = csstext.split("}");
	document.getElementsByTagName("head")[0].appendChild(newcss);
	newcss = document.styleSheets.item(document.styleSheets.length-1);
	if(newcss.rules && newcss.addRule && !newcss.cssRules) { //IE
		for(var i =(cssrules.length-2);i>=0;i--) {
			newrule = cssrules[i].split("{");
			try { newcss.addRule(newrule[0],newrule[1]); } catch (e) {}
		}
	} else if(newcss.cssRules) { //Firefox etc
		for(i=cssrules.length-1;i>=0;i--) {
			if (String(cssrules[i]).trim() != "") {
			try { newcss.insertRule(cssrules[i].trim()+"}",0);} catch (e) {} }
		}
	}
}
function convertlinkserial (ignore,container,tempajax,loadingarea,linkappend) {
	if (typeof(container) != 'undefined') var href_elems = container.getElementsByTagName("a");
	else var href_elems = document.getElementsByTagName("a");
	locregstr = "http://" + window.location.hostname.replace(/\./g,"\\.") + "(:" + window.location.port + ")?";
	locationregex = new RegExp("http://" + window.location.hostname.replace(/\./g,"\\.") + "(:" + window.location.port + ")?");
	for (var i=0;i<href_elems.length;i++) {
		if (!href_elems[i].ajaxsrc && !String(href_elems[i].getAttribute("href",2)).match(/^(javascript:)|(%22)?(#)/i)) {
			var newhref = "javascript:go_to('" + String(href_elems[i].getAttribute("href",2)).replace(locationregex,"") + (linkappend ? linkappend : "") + "'" + (tempajax ? ",false,true" : "") + (loadingarea ? ",'" + loadingarea + "'": "") + ");";
			if (!newhref.match('http://')) {
				href_elems[i].href = newhref;
				href_elems[i].ajaxsrc = true;
				if (href_elems[i].target) href_elems[i].target = "";
			}
		} else if (String(href_elems[i].getAttribute("href",2)).match(/^(%22)?(#)/i)) {
			href_elems[i].href = "javascript:gotoanchor('" + String(href_elems[i].getAttribute("href",2)).replace(/^(%22)?(#)/i,"") + "')";	
			href_elems[i].ajaxsrc = true;
		}
	}
	lwbajaxloaded = true;
	window.setTimeout(function () {eval(ajaxloadexec);ajaxloadexec="";},0);
}
if (typeof(updatestats)!= 'function') {
	updatestats = function () { addjs("/LWBStats/LWBGlobStatsJs.php");}
}
function updatemenu (menutype,prevlink,nextlink) {
	addjs("/LWBMenus/TopBotMenu/LWBGenerateMenu.php?ajax="+lwbpageajax+"&menutype=" + menutype + (nextlink? '&next=' + nextlink : '') + (prevlink? '&prev=' + prevlink : ''));
}
function addjs (path,sync) {
	if (!sync||!lwb) {
		var newjsfile = document.createElement('script');
		newjsfile.type = "text/javascript";
		newjsfile.src = path + (path.indexOf("?")!=-1 ? "&" : "?") + "randajaxid=" + Math.random();
		pagehead.appendChild(newjsfile);
	} else {
		var jscode = fetchjs(path);
		try {
			if (window._content && typeof(window._content.eval) == 'function') { window._content.eval(jscode); }
			else if (window.execScript) { window.execScript(jscode);}
			else if (typeof(eval.call) == 'function' && window.opera) {eval.call(window,jscode); }
			else  { window.setTimeout(jscode,0); for (var i=0;i<100000;i++){}; } //loop can waste some time..
			} catch (e) {}
	}
}
function getWindowHandle(iframeObj) {
    var iframeWin = null;
    if (iframeObj.contentWindow) {
        iframeWin = iframeObj.contentWindow;
    } else if (iframeObj.contentDocument) {
        iframeWin = iframeObj.contentDocument.defaultView;
    } else if (iframeObj.Document) {
        iframeWin = iframeObj.Document.parentWindow;
    }
    return iframeWin;
}
function extractIFrameBody(iFrameEl) {
  var doc = null;
  if (iFrameEl.contentDocument) {
    doc = iFrameEl.contentDocument; 
  } else if (iFrameEl.contentWindow) {
    doc = iFrameEl.contentWindow.document;
  } else if (iFrameEl.document) {
    doc = iFrameEl.document;
  } else {
    return null;
  }
  if (doc.getElementById("content")) return doc.getElementById("content").innerHTML;
  return doc.body.innerHTML;
}
function createIframe(iframeName) {
    var iframeObj = null;
    try {
        var tmpFrame;
        var tmpDiv = document.createElement("div");
        tmpDiv.setAttribute("id", "iframe-div");
        tmpFrame = document.createElement("iframe");
        tmpFrame.setAttribute("id", iframeName);
        tmpFrame.setAttribute("name", iframeName);
        tmpFrame.name = iframeName;
        if (typeof document.body.getAttribute("className") == 'string')
            tmpFrame.setAttribute("className", "hidden-iframe");
        else
            tmpFrame.setAttribute("class", "hidden-iframe");
        tmpDiv.appendChild(tmpFrame);
        document.body.appendChild(tmpDiv);
        if (typeof document.frames != "undefined") {
            iframeObj = document.frames[iframeName];
        }
        if (!iframeObj || typeof iframeObj.nodeType == "undefined") {
            iframeObj = document.getElementById(iframeName);
        }
    }
    catch (e) {
        var iframeHTML='<iframe id="'+iframeName+'" name=id="'+iframeName+'" class="hidden-iframe"><\/iframe>';
        if (!document.getElementById("iframe-div")) {
            tmpDiv = document.createElement("div");
            tmpDiv.setAttribute("id", "iframe-div");
            tmpDiv.innerHTML = iframeHTML;
            document.getElementsByTagName('DIV')[0].appendChild(tmpDiv);
        } else {
            document.getElementById("iframe-div").innerHTML = iframeHTML;
        }
        iframeObj = document.getElementById(iframeName);
    }
    if (iframeObj && typeof iframeObj.nodeType == "undefined") {
        iframeObj = null;
    } else {
		getWindowHandle(iframeObj).location.href = "about:blank";
	    iframeObj.onload = function () { document.getElementById('lwbformiframe').onload = iframeloaded};	
	}
    return iframeObj;
}

function iframeloaded () {
	var iframe = document.getElementById("lwbformiframe");
	var iframewin = getWindowHandle(iframe);
	if (iframewin.location.href != 'about:blank') {
		var pagehtml = extractIFrameBody(iframe);
		loadpage(pagehtml,"content");
		window.document.title = iframe.title;
	} else {
		if (String(hashListener.getHash()).match(/^#LWB:/)) {
			hashListener.onHashChanged();
		} else {
			go_to(location.pathname,true);	
		}
	}
	iframe.onload = iframeloaded;
}
function formsupdate () {
	var formsarr = document.getElementsByTagName('form');
	for (var i=0;i<formsarr.length;i++) {
		if (!formsarr[i].ajaxform && lwbpageajax) {
			formsarr[i].origtarget = formsarr[i].target;
			formsarr[i].target = "lwbformiframe";
		} else if (!formsarr[i].ajaxform && !lwbpageajax) {
			if (formsarr[i].origtarget) formsarr[i].target = formsarr[i].origtarget;
		}
	}
}
function pageXY( el) {var XY={x:0, y:0};for( var node = el; node; node=node.offsetParent){ XY.x += node.offsetLeft;	XY.y += node.offsetTop;}return XY;}
function gotoanchor(name) {
	if (name=='') return;
	var anchors, anchor, XY;
	anchors=document.anchors;
	anchor=anchors[name];
	if(!anchor) {
		for( var i = 0; i < anchors.length; ++i){ if(anchors[i].name==name){ anchor = anchors[i];break;}}
	}
	if(!anchor)
		{ if( document.getElementById) anchor=document.getElementById(name);else if( document.all)anchor=document.all[name];}
	if(anchor)
	{ XY = pageXY(anchor);
	window.scrollTo(XY.x, XY.y);}
}

function lwbajaxon () {
	lwbpageajax = true;
	formsupdate();
}	
function lwbajaxoff () {
	lwbpageajax = false;
	 formsupdate(); 
}

function ajaxinit () {
	hashListener.init();
	if (String(hashListener.getHash()).match(/^#LWB:/)) {
		hashListener.onHashChanged();ajaxloadexec="";
	} else {
		convertlinkserial();
	}
	createIframe("lwbformiframe");formsupdate();
	showterms();
}
if (lwb) addEvent(window,"load",updatestats);
if (lwb) addEvent(window,"load",ajaxinit);
var overlib = nd = function() {};

//Highlight code
function doHighlight(bodyText, searchTerm, highlightStartTag, highlightEndTag) 
{
  if ((!highlightStartTag) || (!highlightEndTag)) {
    highlightStartTag = "<span class=showtermshighlight>";
    highlightEndTag = "</span>";
  }
  var newText = "";
  var i = -1;
  var lcSearchTerm = searchTerm.toLowerCase();
  var lcBodyText = bodyText.toLowerCase();
    
  while (bodyText.length > 0) {
    i = lcBodyText.indexOf(lcSearchTerm, i+1);
    if (i < 0) {
      newText += bodyText;
      bodyText = "";
    } else {
      if (bodyText.lastIndexOf(">", i) >= bodyText.lastIndexOf("<", i)) {
        if (lcBodyText.lastIndexOf("/script>", i) >= lcBodyText.lastIndexOf("<script", i)) {
          newText += bodyText.substring(0, i) + highlightStartTag + bodyText.substr(i, searchTerm.length) + highlightEndTag;
          bodyText = bodyText.substr(i + searchTerm.length);
          lcBodyText = bodyText.toLowerCase();
          i = -1;
        }
      }
    }
  }
  
  return newText;
}
window.size = function() {var w = 0;var h = 0;if(!window.innerWidth){if(!(document.documentElement.clientWidth==0)){w=document.documentElement.clientWidth;h = document.documentElement.clientHeight;}else{w = document.body.clientWidth;h = document.body.clientHeight;}}else{w=window.innerWidth;h=window.innerHeight;}return {width:w,height:h};}
function highlightSearchTerms(searchText, highlightStartTag, highlightEndTag)
{treatAsPhrase=false;
  if (treatAsPhrase) {
    searchArray = [searchText];
  } else {
    searchArray = searchText.split(" ");
  }
  if (!document.body || typeof(document.body.innerHTML) == "undefined") {
    return false;
  }
  var bodyText = document.body.innerHTML;
  for (var i = 0; i < searchArray.length; i++) {
    bodyText = doHighlight(bodyText, searchArray[i], highlightStartTag, highlightEndTag);
  }
  document.body.innerHTML = bodyText;
  return true;
}
function showterms () {
	showtermsregex = /showterms=([^&]+)/i
	if (String(window.location.search).match(showtermsregex)) {
		showtermsregex = /showterms=([^&]+)/i
		var showtermsmatch = showtermsregex.exec(window.location.search);
		var showterms_str = decodeURIComponent(String(showtermsmatch[1]).replace("+"," "));
		highlightSearchTerms(showterms_str);
	}
}
