/*@cc_on
document.execCommand("BackgroundImageCache", false ,true);
@*/

String.prototype.trim = function(){ return this.replace(/^\s+|\s+$/g,'') }

var offsetfrommouse=[15,15]; //image x,y offsets from cursor position in pixels. Enter 0,0 for no offset
var displayduration=0; //duration in seconds image should remain visible. 0 for always.
var currentimageheight = 167;	// maximum image size.

if (document.getElementById || document.all){
	document.write('<div id="hoverimageid">');
	document.write('</div>');
}

function gettrailobj(){
if (document.getElementById)
return document.getElementById("hoverimageid").style
else if (document.all)
return document.all.trailimagid.style
}

function gettrailobjnostyle(){
if (document.getElementById)
return document.getElementById("hoverimageid")
else if (document.all)
return document.all.trailimagid
}


function truebody(){
return (!window.opera && document.compatMode && document.compatMode!="BackCompat")? document.documentElement : document.body
}

function showtrail(imagename,title,ratingaverage,gain,description,showthumb,height){

	if (height > 0){
		currentimageheight = height;
	}

	document.onmousemove=followmouse;
	
	popHTML = '';
	gainHTML = '';

	if (ratingaverage == 0)
	{
		popHTML = "(No weekly data yet)";
		gainHTML = "";
	}
	else
	{
		for(x = 1; x <= 5; x++){
	
			if (ratingaverage >= 1){
				popHTML = popHTML + '<img style="padding-right:3px" src="/_images/pop-10.gif" align="top">';
			} else if (ratingaverage >= 0.5){
				popHTML = popHTML + '<img style="padding-right:3px" src="/_images/pop-05.gif" align="top">';
			} else {
				popHTML = popHTML + '<img style="padding-right:3px" src="/_images/pop-00.gif" align="top">';
			}
		
			ratingaverage = ratingaverage - 1;
	
		}
		
		if (gain == -999999)
			tmpstr = '(New)';
		else {
			if (gain == 0)
				tmpstr = 'N/C';
			else if (gain > 0)
				tmpstr = '<img src="/_images/popgainup.gif" align="top">';
			else
				tmpstr = '<img src="/_images/popgaindown.gif" align="top">';
		}

		gainHTML = '&nbsp;<b>' + tmpstr + '</b>';
	}

	popHTML = '<b>Popularity:</b> ' + popHTML;

	newHTML = '<div id="hoverimg">';
	newHTML = newHTML + '<h2 class="portraitTitle" align="center" style="text-align:center">' + title + '</h2>';

	if (showthumb > 0){
		newHTML = newHTML + '<div align="center" style="padding: 8px 2px 8px 2px;"><img src="' + imagename + '" border="0"></div>';
	}
	
	//newHTML = newHTML + popHTML + gainHTML + '<br/><span style="line-height:3px"><br/></span>';
	
	//newHTML = newHTML + description + '<br/>';

	newHTML = newHTML + '</div>';

	gettrailobjnostyle().innerHTML = newHTML;

	gettrailobj().visibility="visible";

}


function hidetrail(){
	gettrailobj().visibility="hidden"
	document.onmousemove=""
	gettrailobj().left="-500px"

}

function followmouse(e){

	var xcoord=offsetfrommouse[0]
	var ycoord=offsetfrommouse[1]

	var docwidth=document.all? truebody().scrollLeft+truebody().clientWidth : pageXOffset+window.innerWidth-15
	var docheight=document.all? Math.min(truebody().scrollHeight, truebody().clientHeight) : Math.min(window.innerHeight)

	//if (document.all){
	//	gettrailobjnostyle().innerHTML = 'A = ' + truebody().scrollHeight + '<br>B = ' + truebody().clientHeight;
	//} else {
	//	gettrailobjnostyle().innerHTML = 'C = ' + document.body.offsetHeight + '<br>D = ' + window.innerHeight;
	//}

	if (typeof e != "undefined"){
		if (docwidth - e.pageX < 239){
			xcoord = e.pageX - xcoord - 200; // Move to the left side of the cursor
		} else {
			xcoord += e.pageX;
		}
		if (docheight - e.pageY < (currentimageheight + 110)){
			ycoord += e.pageY - Math.max(0,(110 + currentimageheight + e.pageY - docheight - truebody().scrollTop));
		} else {
			ycoord += e.pageY;
		}

	} else if (typeof window.event != "undefined"){
		if (docwidth - event.clientX < 300){
			xcoord = event.clientX + truebody().scrollLeft - xcoord - 286; // Move to the left side of the cursor
		} else {
			xcoord += truebody().scrollLeft+event.clientX
		}
		if (docheight - event.clientY < (currentimageheight + 110)){
			ycoord += event.clientY + truebody().scrollTop - Math.max(0,(110 + currentimageheight + event.clientY - docheight));
		} else {
			ycoord += truebody().scrollTop + event.clientY;
		}
	}

	var docwidth=document.all? truebody().scrollLeft+truebody().clientWidth : pageXOffset+window.innerWidth-15
	var docheight=document.all? Math.max(truebody().scrollHeight, truebody().clientHeight) : Math.max(document.body.offsetHeight, window.innerHeight)
		if(ycoord < 0) { ycoord = ycoord*-1; }
	gettrailobj().left=xcoord+"px"
	gettrailobj().top=ycoord+"px"

}

//function trim (str)
  // return str.replace(/^\s*|\s*$/g,"");

/********** POPUP *************/

// store variables to control where the popup will appear relative to the cursor position
// positive numbers are below and to the right of the cursor, negative numbers are above and to the left
var xOffset = -85;
var yOffset = 15;

function showPopup (targetObjectId, eventObj) {
    if(eventObj) {
	// hide any currently-visible popups
	hideCurrentPopup();
	// stop event from bubbling up any farther
	eventObj.cancelBubble = true;
	// move popup div to current cursor position 
	// (add scrollTop to account for scrolling for IE)
	var newXCoordinate = (eventObj.pageX)?eventObj.pageX + xOffset:eventObj.x + xOffset + ((document.body.scrollLeft)?document.body.scrollLeft:0);
	var newYCoordinate = (eventObj.pageY)?eventObj.pageY + yOffset:eventObj.y + yOffset + ((document.body.scrollTop)?document.body.scrollTop:0);

	moveObject(targetObjectId, newXCoordinate, newYCoordinate);
	// and make it visible
	if( changeObjectVisibility(targetObjectId, 'visible') ) {
	    // if we successfully showed the popup
	    // store its Id on a globally-accessible object
	    window.currentlyVisiblePopup = targetObjectId;
	    return true;
	} else {
	    // we couldn't show the popup, boo hoo!
	    return false;
	}
    } else {
	// there was no event object, so we won't be able to position anything, so give up
	return false;
    }
} // showPopup

function togglePopup(targetObjectId, eventObj) {
	if(window.currentlyVisiblePopup)
	{
		hideCurrentPopup();
		document.getElementById(targetObjectId).style.display = "none";
	}
	else
	{
		showPopup (targetObjectId, eventObj);
		document.getElementById(targetObjectId).style.display = "block";
	}
}

function hideCurrentPopup() {
    // note: we've stored the currently-visible popup on the global object window.currentlyVisiblePopup
    if(window.currentlyVisiblePopup) {
	changeObjectVisibility(window.currentlyVisiblePopup, 'hidden');
	window.currentlyVisiblePopup = false;
    }
} // hideCurrentPopup



// ***********************
// hacks and workarounds *
// ***********************

// initialize hacks whenever the page loads
window.onload = initializeHacks;

// setup an event handler to hide popups for generic clicks on the document
document.onclick = hideCurrentPopup;

function initializeHacks() {
    // this ugly little hack resizes a blank div to make sure you can click
    // anywhere in the window for Mac MSIE 5
    if ((navigator.appVersion.indexOf('MSIE 5') != -1) 
	&& (navigator.platform.indexOf('Mac') != -1)
	&& getStyleObject('blankDiv')) {
	window.onresize = explorerMacResizeFix;
    }
    resizeBlankDiv();
    // this next function creates a placeholder object for older browsers
    createFakeEventObj();
}

function createFakeEventObj() {
    // create a fake event object for older browsers to avoid errors in function call
    // when we need to pass the event object to functions
    if (!window.event) {
	window.event = false;
    }
} // createFakeEventObj

function resizeBlankDiv() {
    // resize blank placeholder div so IE 5 on mac will get all clicks in window
    if ((navigator.appVersion.indexOf('MSIE 5') != -1) 
	&& (navigator.platform.indexOf('Mac') != -1)
	&& getStyleObject('blankDiv')) {
	getStyleObject('blankDiv').width = document.body.clientWidth - 20;
	getStyleObject('blankDiv').height = document.body.clientHeight - 20;
    }
}

function explorerMacResizeFix () {
    location.reload(false);
}

function getStyleObject(objectId) {
    // cross-browser function to get an object's style object given its id
    if(document.getElementById && document.getElementById(objectId)) {
	// W3C DOM
	return document.getElementById(objectId).style;
    } else if (document.all && document.all(objectId)) {
	// MSIE 4 DOM
	return document.all(objectId).style;
    } else if (document.layers && document.layers[objectId]) {
	// NN 4 DOM.. note: this won't find nested layers
	return document.layers[objectId];
    } else {
	return false;
    }
} // getStyleObject

function changeObjectVisibility(objectId, newVisibility) {
    // get a reference to the cross-browser style object and make sure the object exists
    var styleObject = getStyleObject(objectId);
    if(styleObject) {
	styleObject.visibility = newVisibility;
	return true;
    } else {
	// we couldn't find the object, so we can't change its visibility
	return false;
    }
} // changeObjectVisibility

function moveObject(objectId, newXCoordinate, newYCoordinate) {
    // get a reference to the cross-browser style object and make sure the object exists
    var styleObject = getStyleObject(objectId);
    if(styleObject) {
	styleObject.left = newXCoordinate;
	styleObject.top = newYCoordinate;
	return true;
    } else {
	// we couldn't find the object, so we can't very well move it
	return false;
    }
} // moveObject

/******** MISC JS **********/

function getCookie(name) {
    var dc = document.cookie;
    var prefix = name + "=";
    var begin = dc.indexOf("; " + prefix);
    if (begin == -1) {
        begin = dc.indexOf(prefix);
        if (begin != 0) return null;
    } else {
        begin += 2;
    }
    var end = document.cookie.indexOf(";", begin);
    if (end == -1) {
        end = dc.length;
    }
    return unescape(dc.substring(begin + prefix.length, end));
}

function html2entities(){
var re=/[(<>"'&]/g
var str = "";
for (i=0; i < arguments.length; i++)
str +=arguments[i].value.replace(re, function(m){return replacechar(m)});
return str;
}

function replacechar(match){
if (match=="<")
return "&lt;"
else if (match==">")
return "&gt;"
else if (match=="\"")
return "&quot;"
else if (match=="'")
return "&#039;"
else if (match=="&")
return "&amp;"
}

function divToggle(divid)
{
	if (document.getElementById(divid).style.display == 'none')
		document.getElementById(divid).style.display = 'inline';
	else
		document.getElementById(divid).style.display = 'none';
}

function opacity(id, opacStart, opacEnd, millisec) {
    //speed for each frame
    var speed = Math.round(millisec / 100);
    var timer = 0;

    //determine the direction for the blending, if start and end are the same nothing happens
    if(opacStart > opacEnd) {
        for(i = opacStart; i >= opacEnd; i--) {
            setTimeout("changeOpac(" + i + ",'" + id + "')",(timer * speed));
            timer++;
        }
    } else if(opacStart < opacEnd) {
        for(i = opacStart; i <= opacEnd; i++)
            {
            setTimeout("changeOpac(" + i + ",'" + id + "')",(timer * speed));
            timer++;
        }
    }
}

//change the opacity for different browsers
function changeOpac(opacity, id) {
    var object = document.getElementById(id).style;
    object.opacity = (opacity / 101);
    object.MozOpacity = (opacity / 101);
    object.KhtmlOpacity = (opacity / 100);
    object.filter = "alpha(opacity=" + opacity + ")";
} 

function toggleDivs(div1, div2, alink, cmsg, omsg)
{
	if (document.getElementById(div1).style.display == 'none') {
		document.getElementById(div1).style.display = 'block';
		document.getElementById(div2).style.display = 'none';
		document.getElementById(alink).innerHTML = '<a class="redLink3" style="cursor:pointer" onclick="javascript:toggleDivs(\''+div1+'\',\''+div2+'\',\''+alink+'\',\''+cmsg+'\',\''+omsg+'\');">'+omsg+'</a>';
	}
	else
	{
		document.getElementById(div1).style.display = 'none';
		document.getElementById(div2).style.display = 'block';
		document.getElementById(alink).innerHTML = '<a class="redLink3" style="cursor:pointer" onclick="javascript:toggleDivs(\''+div1+'\',\''+div2+'\',\''+alink+'\',\''+cmsg+'\',\''+omsg+'\');">'+cmsg+'</a>';
	}	
}

/* ac */

var useAJns;

if (useAJns)
{
	if (typeof(aj) == "undefined")
		aj = {}
	_aj = aj;
}
else
{
	_aj = this;
}

_aj.Ajax = function ()
{
	this.req = {};
	this.isIE = false;
}

_aj.Ajax.prototype.makeRequest = function (url, meth, onComp, onErr)
{
	
	if (meth != "POST")
		meth = "GET";
	
	this.onComplete = onComp;
	this.onError = onErr;
	
	var pointer = this;
	
	// branch for native XMLHttpRequest object
	if (window.XMLHttpRequest)
	{
		this.req = new XMLHttpRequest();
		this.req.onreadystatechange = function () { pointer.processReqChange() };
		this.req.open("GET", url, true); //
		this.req.send(null);
	// branch for IE/Windows ActiveX version
	}
	else if (window.ActiveXObject)
	{
		this.req = new ActiveXObject("Microsoft.XMLHTTP");
		if (this.req)
		{
			this.req.onreadystatechange = function () { pointer.processReqChange() };
			this.req.open(meth, url, true);
			this.req.send();
		}
	}
}

_aj.Ajax.prototype.processReqChange = function()
{
	
	// only if req shows "loaded"
	if (this.req.readyState == 4) {
		// only if "OK"
		if (this.req.status == 200)
		{
			this.onComplete( this.req );
		} else {
			this.onError( this.req.status );
		}
	}
}

if (typeof(_aj.DOM) == "undefined")
	_aj.DOM = {}

_aj.DOM.createElement = function ( type, attr, cont, html )
{
	var ne = document.createElement( type );
	if (!ne)
		return false;
		
	for (var a in attr)
		ne[a] = attr[a];
		
	if (typeof(cont) == "string" && !html)
		ne.appendChild( document.createTextNode(cont) );
	else if (typeof(cont) == "string" && html)
		ne.innerHTML = cont;
	else if (typeof(cont) == "object")
		ne.appendChild( cont );

	return ne;
}

_aj.DOM.clearElement = function ( id )
{
	var ele = this.getElement( id );
	
	if (!ele)
		return false;
	
	while (ele.childNodes.length)
		ele.removeChild( ele.childNodes[0] );
	
	return true;
}

_aj.DOM.removeElement = function ( ele )
{
	var e = this.getElement(ele);
	
	if (!e)
		return false;
	else if (e.parentNode.removeChild(e))
		return true;
	else
		return false;
}

_aj.DOM.replaceContent = function ( id, cont, html )
{
	var ele = this.getElement( id );
	
	if (!ele)
		return false;
	
	this.clearElement( ele );
	
	if (typeof(cont) == "string" && !html)
		ele.appendChild( document.createTextNode(cont) );
	else if (typeof(cont) == "string" && html)
		ele.innerHTML = cont;
	else if (typeof(cont) == "object")
		ele.appendChild( cont );
}

_aj.DOM.getElement = function ( ele )
{
	if (typeof(ele) == "undefined")
	{
		return false;
	}
	else if (typeof(ele) == "string")
	{
		var re = document.getElementById( ele );
		if (!re)
			return false;
		else if (typeof(re.appendChild) != "undefined" ) {
			return re;
		} else {
			return false;
		}
	}
	else if (typeof(ele.appendChild) != "undefined")
		return ele;
	else
		return false;
}

_aj.DOM.appendChildren = function ( id, arr )
{
	var ele = this.getElement( id );
	
	if (!ele)
		return false;
	
	
	if (typeof(arr) != "object")
		return false;
		
	for (var i=0;i<arr.length;i++)
	{
		var cont = arr[i];
		if (typeof(cont) == "string")
			ele.appendChild( document.createTextNode(cont) );
		else if (typeof(cont) == "object")
			ele.appendChild( cont );
	}
}

//	var opt = new Array( '1'=>'lorem', '2'=>'ipsum' );
// var sel = '2';

_aj.DOM.createSelect = function ( attr, opt, sel )
{
	var select = this.createElement( 'select', attr );
	for (var a in opt)
	{
	
		var o = {id:a};
		if (a == sel)	o.selected = "selected";
		select.appendChild( this.createElement( 'option', o, opt[a] ) );
		
	}
	
	return select;
}

_aj.DOM.getPos = function ( ele )
{
	var ele = this.getElement(ele);

	var obj = ele;

	var curleft = 0;
	if (obj.offsetParent)
	{
		while (obj.offsetParent)
		{
			curleft += obj.offsetLeft
			obj = obj.offsetParent;
		}
	}
	else if (obj.x)
		curleft += obj.x;

	var obj = ele;
	
	var curtop = 0;
	if (obj.offsetParent)
	{
		while (obj.offsetParent)
		{
			curtop += obj.offsetTop
			obj = obj.offsetParent;
		}
	}
	else if (obj.y)
		curtop += obj.y;

	return {x:curleft, y:curtop}
}

_aj.AutoSuggest = function (fldID, param)
{
	if (!document.getElementById)
		return false;
	
	this.fld = _aj.DOM.getElement(fldID);

	if (!this.fld)
		return false;
		
		
	this.nInputChars = 0;
	this.aSuggestions = [];
	this.iHighlighted = 0;
	
	
	// parameters object
	this.oP = (param) ? param : {};
	// defaults	
	if (!this.oP.minchars)		this.oP.minchars = 1;
	if (!this.oP.method)		this.oP.meth = "get";
	if (!this.oP.varname)		this.oP.varname = "input";
	if (!this.oP.className)		this.oP.className = "autosuggest";
	if (!this.oP.timeout)		this.oP.timeout = 2500;
	if (!this.oP.delay)			this.oP.delay = 500;
	if (!this.oP.maxheight && this.oP.maxheight !== 0)		this.oP.maxheight = 250;
	if (!this.oP.cache)			this.oP.cache = true;
	
	var pointer = this;
	
	this.fld.onkeyup = function () { 
		var str;
	
		var strarr = new Array()
		strarr = this.value.trim().split(' ');
		if (strarr.length > 1)
			str = strarr[strarr.length - 1];
		else 
			str = this.value;
			
		//if (confirm('sdaf')) 
		//{
			pointer.getSuggestions( str ); 
			return false;
		//} 
	};
	this.fld.setAttribute("autocomplete","off");
}

_aj.AutoSuggest.prototype.getSuggestions = function (val)
{
	//document.write(val);
	if (val.length == this.nInputChars)
		return false;
	
	if (val.length < this.oP.minchars)
	{
		this.nInputChars = val.length;
		this.aSuggestions = [];
		this.clearSuggestions();
		return false;
	}
	
	if (val.length>this.nInputChars && this.aSuggestions.length && this.oP.cache)
	{
		// get from cache
		var arr = [];
		for (var i=0;i<this.aSuggestions.length;i++)
		{
			if (this.aSuggestions[i].substr(0,val.length).toLowerCase() == val.toLowerCase())
				arr.push( this.aSuggestions[i] );
		}
		
		this.nInputChars = val.length;
		this.aSuggestions = arr;
		
		
		this.createList( this.aSuggestions );
		
		return false;
	}
	
	this.nInputChars = val.length;
	
	var pointer = this;
	clearTimeout(this.ajID);
	this.ajID = setTimeout( function() { pointer.doAjaxRequest(val) }, this.oP.delay );

	return false;
}

_aj.AutoSuggest.prototype.doAjaxRequest = function (val)
{
	var pointer = this;
	
	// create ajax request
	var url = this.oP.script+this.oP.varname+"="+escape(val);
	var meth = this.oP.meth;
	
	var onSuccessFunc = function (req) { pointer.setSuggestions(req) };
	var onErrorFunc = function (status) { alert("AJAX error: "+status); };

	var myAjax = new _aj.Ajax;
	myAjax.makeRequest( url, meth, onSuccessFunc, onErrorFunc );
}

_aj.AutoSuggest.prototype.setSuggestions = function (req)
{
	var xml = req.responseXML;
	// traverse xml
	//
	this.aSuggestions = [];
	var results = xml.getElementsByTagName('results')[0].childNodes;

	for (var i=0;i<results.length;i++)
	{
		if (results[i].hasChildNodes())
			this.aSuggestions.push( results[i].childNodes[0].nodeValue );
	}

	this.idAs = "as_"+this.fld.id;
	sug = this.idAs;
	this.createList(this.aSuggestions);
}

_aj.AutoSuggest.prototype.createList = function(arr)
{
	// clear previous list
	//
	this.clearSuggestions();

	// create and populate ul
	//
	var ul = _aj.DOM.createElement("ul", {id:this.idAs, className:this.oP.className});
	
	
	var pointer = this;
	for (var i=0;i<arr.length;i++)
	{
		var a = _aj.DOM.createElement("a", { href:"#" }, arr[i]);
		a.onclick = function () { pointer.setValue( this.childNodes[0].nodeValue ); return false; }
		var li = _aj.DOM.createElement(  "li", {}, a  );
		ul.appendChild(  li  );
	}
	
	var pos = _aj.DOM.getPos(this.fld);
	
	ul.style.left = pos.x + "px";
	ul.style.top = ( pos.y + this.fld.offsetHeight ) + "px";
	ul.style.width = this.fld.offsetWidth + "px";
	ul.onmouseover = function(){ pointer.killTimeout() }
	ul.onmouseout = function(){ pointer.resetTimeout() }


	document.getElementsByTagName("body")[0].appendChild(ul);
	
	if (ul.offsetHeight > this.oP.maxheight && this.oP.maxheight != 0)
	{
		ul.style['height'] = this.oP.maxheight + "px";
	}

	var TAB = 9;
	var ESC = 27;
	var KEYUP = 38;
	var KEYDN = 40;
	var RETURN = 13;
	
	this.fld.onkeydown = function(ev)
	{
		var key = (window.event) ? window.event.keyCode : ev.keyCode;

		switch(key)
		{
			case TAB:
			pointer.setHighlightedValue();
			break;

			case ESC:
			pointer.clearSuggestions();
			break;

			case KEYUP:
			pointer.changeHighlight(key);
			return false;
			break;

			case KEYDN:
			pointer.changeHighlight(key);
			return false;
			break;
		}

	};

	this.iHighlighted = 0;
	
	// remove autosuggest after an interval
	//
	clearTimeout(this.toID);
	var pointer = this;
	this.toID = setTimeout(function () { pointer.clearSuggestions() }, this.oP.timeout);
}

_aj.AutoSuggest.prototype.changeHighlight = function(key)
{
	var list = _aj.DOM.getElement(this.idAs);
	if (!list)
		return false;
	
	
	if (this.iHighlighted > 0)
		list.childNodes[this.iHighlighted-1].className = "";
	
	if (key == 40)
		this.iHighlighted ++;
	else if (key = 38)
		this.iHighlighted --;
	
	
	if (this.iHighlighted > list.childNodes.length)
		this.iHighlighted = list.childNodes.length;
	if (this.iHighlighted < 1)
		this.iHighlighted = 1;
	
	list.childNodes[this.iHighlighted-1].className = "highlight";
	
	//alert( list.childNodes[this.iHighlighted-1].firstChild.firstChild.nodeValue );
	
	this.killTimeout();
}

_aj.AutoSuggest.prototype.killTimeout = function()
{
	clearTimeout(this.toID);
}

_aj.AutoSuggest.prototype.resetTimeout = function()
{
	clearTimeout(this.toID);
	var pointer = this;
	this.toID = setTimeout(function () { pointer.clearSuggestions() }, 0);
}

_aj.AutoSuggest.prototype.clearSuggestions = function ()
{
	if (document.getElementById(this.idAs))
	{
		//opacity(this.idAs, 100, 0, 100);
		//setTimeout("_aj.DOM.removeElement('"+this.idAs+"');", 101);
		_aj.DOM.removeElement(this.idAs);
	}
	this.fld.onkeydown = null;
}

_aj.AutoSuggest.prototype.setHighlightedValue = function ()
{
	if (this.iHighlighted)
	{
		var str;
	
		var strarr = new Array()
		strarr = this.fld.value.trim().split(' ');
		strarr[strarr.length-1] = document.getElementById(this.idAs).childNodes[this.iHighlighted-1].firstChild.firstChild.nodeValue;
		str = strarr.join(" ") + ' ';
			
		this.fld.value = str;
		//this.fld.value = document.getElementById(this.idAs).childNodes[this.iHighlighted-1].firstChild.firstChild.nodeValue;
		this.killTimeout();
		this.clearSuggestions();
		setTimeout("document.getElementById('"+this.fld.id+"').focus();", 150);
	}
}

_aj.AutoSuggest.prototype.setValue = function (val)
{
	var str;
	
	var strarr = new Array()
	strarr = this.fld.value.trim().split(' ');
	strarr[strarr.length-1] = val;
	str = strarr.join(" ") + ' ';
	
	//this.fld.value = val;
	this.fld.value = str;
	this.resetTimeout();
}

var saja = {
	procOn:0,
	history:[],
	historyIndex:0,
	updateIndicator: function(){
		var s = document.getElementById('sajaStatus');
		if(s)
			s.style.visibility = saja.procOn ? 'visible' : 'hidden';
	},
	getReq: function(){
		if(window.XMLHttpRequest)
			try{return new XMLHttpRequest();}catch(e){}
		else if(window.ActiveXObject)
			try{return new ActiveXObject("Microsoft.XMLHTTP");}catch(e){
				try{return new ActiveXObject("Msxml2.XMLHTTP");}catch(e){}}
	},
	run: function(php, id, act, property, session_id, request_id, use_history){
		saja.procOn++;
		var requestString = 'req=' + (SAJA_HTTP_KEY ? encodeURIComponent(saja.rc4(SAJA_HTTP_KEY, php)) : php) + '<!SAJA!>' + session_id + '<!SAJA!>' + (request_id || '');
		requestString += '&rnd=' + Math.random();
		if(use_history){
			saja.addHistory(function(){
				saja.procOn++;
				saja.SendRequest(id, act, property, requestString);
			});
		}
		saja.SendRequest(id, act, property, requestString);
	},
	SendRequest: function(id, act, property, requestString){
		var req = saja.getReq();
		saja.updateIndicator();
		req.open('POST',SAJA_PATH + 'sajaproc.php',true);
		req.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
		req.send(requestString);
		req.onreadystatechange=function(){
			if (req.readyState==4 && req.status==200){	
				actions = req.responseText.split('<saja_split>');
				if(id)
					saja.Put(actions[0], id, act, property)
				if(actions[1])
					eval(actions[1]);
				saja.procOn--;
				saja.updateIndicator();
			}
		}
	},
	Put: function(content, id, act, property){
		if(!id) return;
		if(property){
			try{var ob = document.getElementById(id);}catch(e){}
			if(act=='p')
				ob[property] = content + ob[property];
			else if(act=='a')
				ob[property] += content;
			else if(property.split('.')[0]=='style')
				ob.style[property.split('.')[1]] = content;
			else if(ob)
				ob[property] = content;
		}
		else
			window[id] = content;
	},
	Get: function(id, property){
		if(!property)
			return saja.phpSerialize(id);
		return saja.phpSerialize(document.getElementById(id)[property]);
	},
	phpSerialize: function(v){
		var ret = '';
		if(typeof(v)=='object'){
			var len = v.length;
			if(len){
				ret = 'a:' + len + ':{';
				for(var i=0; i<len; i++){
					ret += 'i:' + i +';'
					ret += 's:' + (v[i]+'').length + ':"' + encodeURIComponent(v[i]) +'";'
				}
				ret += '}';
			} else {
				len = 0;
				for(var i in v) len++;
				ret = 'a:' + len + ':{';
				for(var i in v){
					ret += 's:' + i.length + ':"' + i +'";'
					ret += 's:' + v[i].length + ':"' + encodeURIComponent(v[i]) +'";'
				}
				ret += '}';
			}
		} else {
			ret += 's:' + (v+'').length + ':"' + encodeURIComponent(v) +'";'
		}
		return ret;
	},
	SetStyle: function(ob, styleString){
		document.getElementById(ob).style.cssText = styleString;	
	},
	rc4: function(pwd, data){
		var pwd_length = pwd.length;
		var data_length = data.length;
		var key = []; var box = [];
		var cipher = '';
		var k;
		for (var i=0; i < 256; i++){
			key[i] = pwd.charCodeAt(i % pwd_length);
			box[i] = i;
		}
		for (var j = i = 0; i < 256; i++){
			j = (j + box[i] + key[i]) % 256;
			tmp = box[i];
			box[i] = box[j];
			box[j] = tmp;
		}
		for (var a = j = i = 0; i < data_length; i++){
			a = (a + 1) % 256;
			j = (j + box[a]) % 256;
			tmp = box[a];
			box[a] = box[j];
			box[j] = tmp;
			k = box[((box[a] + box[j]) % 256)];
			cipher += String.fromCharCode(data.charCodeAt(i) ^ k);
		}
		return cipher;
	},
	getForm: function(f){
		var vals = {};
		for(var i=0; i<f.length; i++)
			if(f[i].id)
				vals[f[i].id] = f[i].value;
		return vals;
	},
	addHistory: function(value){
		var historyURL1 = SAJA_PATH + 'sajax.php/1/';
		var historyURL2 = SAJA_PATH + 'sajax.php/2/';
		saja.historyValue = value;
		saja.lastHistoryURL = saja.lastHistoryURL==historyURL2 ? historyURL1 : historyURL2;
		saja.sajaHistory.location.href = saja.lastHistoryURL + '#' + (saja.historyIndex - 0 + 1);
	},
	monitorHistory: function(){
		saja.lastHistoryURL = saja.sajaHistory.location.pathname;
		var currentHash = saja.sajaHistory.location.hash;
		var index = currentHash.split('#')[1];
		if(saja.lastHash != currentHash){
			if(saja.historyValue == null && index < saja.history.length)
				saja.historyIndex = index;
			else{
				if(saja.historyIndex < saja.history.length-1)
					saja.history.splice(saja.historyIndex-0+1, saja.history.length-saja.historyIndex-1);
				saja.historyIndex = saja.history.length;
				saja.history[saja.historyIndex] = saja.historyValue;
			}
			if(!currentHash && saja.history.length && saja.onBackToStart) saja.onBackToStart();
			else if(saja.historyValue != saja.history[index]) saja.onHistoryChange(index);
			saja.lastHash = currentHash;
			saja.historyValue = null;
		}
		saja.historyInterval = window.setTimeout(saja.monitorHistory, 100);
	}
}

/* Timer */
var reqXML;
    
function LoadXMLDoc(url){ 
  if (window.XMLHttpRequest){ //Mozilla, Firefox, Opera 8.01, Safari
    reqXML = new XMLHttpRequest(); 
    reqXML.onreadystatechange = BuildXMLResults; 
    reqXML.open("GET", url, true); 
    reqXML.send(null); 
  }
  else if(window.ActiveXObject){ //IE
    reqXML = new ActiveXObject("Microsoft.XMLHTTP"); 
    if (reqXML) { 
      reqXML.onreadystatechange = BuildXMLResults; 
      reqXML.open("GET", url, true); 
      reqXML.send(); 
    } 
  }
  else{ //Older Browsers
    alert("Your Browser does not support Ajax!");
  }
} 

function BuildXMLResults(){
  if(reqXML.readyState == 4){ //completed state
    if(reqXML.status == 200){ //We got a sucess page back
         
      //Check to verify the message from the server 
      if(reqXML.responseText.indexOf("Session Updated - Server Time:") == 0){
        //window.status = reqXML.responseText; //display the message in the status bar
        SetTimer(); //restart timer
      }
      else{
        //display that that session expired
        //alert("Your session appears to have expired. You may loose your current data.");
      }
    } 
    else{
      //display server code not be accessed
      //alert("There was a problem retrieving the XML data:\n" + reqXML.statusText);
    }		
  }
}
      
function ConfirmUpdate(){
  //Ask them to extend
  //if(confirm("Your session is about to expire. Press 'OK' to renew your session.")){
    //load server side page if ok
    LoadXMLDoc('/_saja/sajaproc.php?s=1'); 
  //}
}      
      
var timerObj;
function SetTimer(){
  //How long before timeout (should be a few minutes before your server's timeout
  var dblMinutes = 5;
  //set timer to call function to confirm update 
  timerObj = setTimeout("ConfirmUpdate()",1000*60*dblMinutes);
}

/* Validation */
var formvalid = true;

function gem(id)
{
	return document.getElementById(id);	
}

function chkf(field)
{	
	if (gem(field).value.trim() == '')
	{
		gem(field).style.backgroundColor = '#fff8be';
		if (formvalid)
		{
			formvalid = false;;
			gem(field).focus();
		}
	}
	else
	{
		gem(field).style.backgroundColor = '';
	}
}
      
//start the timer
SetTimer();