base_url = "/";

function addslashes(str) {
	str=str.replace(/\'/g,'\\\'');
	str=str.replace(/\"/g,'\\"');
	str=str.replace(/\\/g,'\\\\');
	str=str.replace(/\0/g,'\\0');
	return str;
}
function stripslashes(str) {
	str=str.replace(/\\'/g,'\'');
	str=str.replace(/\\"/g,'"');
	str=str.replace(/\\\\/g,'\\');
	str=str.replace(/\\0/g,'\0');
	return str;
}

genTopTags = function(array, start, cutoff) {
		count = 0;
		threshold = false;
		//cutoff = 2; // Should also be even
		
		for (var i=start;i<array.length;i++)
		{
			count++;
			if (count > cutoff) {
				threshold = true;
				break;
			}
			document.write('<span class="tag">');
			document.write('<a href="' + base_url + 'tags/tag/' + array[i].value + '" title="\'' + array[i].value + '\' tag is attached to ' + array[i].count + ' stax">' + array[i].value + ' <span class="count">(' + array[i].count + ')</span>' + '</a>');
			//document.write(array[i].value);
			document.write('</span>');

		}
		return;
}

genTopLists = function(array, start, cutoff) {
		count = 0;
		threshold = false;
		//cutoff = 2; // Should also be even
		for (var i=start;i<array.length;i++)
		{
			count++;
			if (count > cutoff) {
				threshold = true;
				break;
			}
			document.write('<div class="item" id="index' + count + '">');
			document.write('<a href="create/' + array[i].id + '" title="Topic \'' + array[i].value + '\' has ' + array[i].count + ' stax">' + array[i].value + ' <span class="count">(' + array[i].count + ')</span>' + '</a>');
			//document.write('<a href="create/' + array[i].id + '">' + array[i].value + '</a>');
			//document.write(array[i].value);
			document.write('</div>');

		}
		return;
}

genTopItems_iPhone = function(array, start, cutoff, uid) {

		count = 0;
		threshold = false;
		//cutoff = 2; // Should also be even
		document.write('<option value="">Touch to choose a thing</option>');
		for (var i=start;i<array.length;i++)
		{
			count++;
			if (count > cutoff) {
				threshold = true;
				break;
			}

			if (array[i].value) {
				document.write('<option value="' + array[i].value + '">' + array[i].value + ' <span class="count">(' + array[i].count + ')</span>' + '</option>');
			}
		}
		return;
}

genTopItems = function(array, start, cutoff, uid) {
		count = 0;
		threshold = false;
		//cutoff = 2; // Should also be even
		for (var i=start;i<array.length;i++)
		{
			count++;
			if (count > cutoff) {
				threshold = true;
				break;
			}

			if (array[i].value) {
				document.write('<div class="itemdrop" id="add' + count + '"><a href="javascript:toggleLayer2(\'index' + count + '\')"></a></div>');
				document.write('<div id="item' + count + '" class="itempop"><a href="javascript:popfield(\'' + array[i].value + '\')" title="\'' + array[i].value + '\' is found in ' + array[i].count + ' stax">' + array[i].value + '<span class="count"> (' + array[i].count + ')</span> ' + '</a></div><div class="context" id="index' + count + '"><div class="contextlink3">');
				if (array[i].link1) {
					document.write('<a href="http://maps.google.com/' + array[i].link1 + '" target="_blank"><img src="' + base_url + 'includes/images/icons/maps.gif" title="Show this location on Google Maps" /></a>');
				}
				if (array[i].link2) {
					document.write('<a href="http://en.wikipedia.org/' + array[i].link2 + '" target="_blank"><img src="' + base_url + 'includes/images/icons/wikipedia.gif" title="Show Wikipedia entry" /></a>');
				}
				if (array[i].link3) {
					document.write('<a href="http://www.amazon.com/' + array[i].link3 + '" target="_blank"><img src="' + base_url + 'includes/images/icons/amazon.gif" title="Show Amazon product page" /></a>');
				}
				if (array[i].link4) {
					document.write('<a href="http://www.imdb.com/' + array[i].link4 + '" target="_blank"><img src="' + base_url + 'includes/images/icons/imdb.gif" title="Show IMDB movie entry" /></a>');
				}
				if (array[i].link5) {
					document.write('<a href="http://www.youtube.com/' + array[i].link5 + '" target="_blank"><img src="' + base_url + 'includes/images/icons/youtube.gif" title="Show Youtube Video" /></a>');
				}
				if(array[i].link1 == "" && array[i].link2  == "" && array[i].link3  == "" && array[i].link4  == "" && array[i].link5 == "" ) {
					document.write('<div class="dark">No links found. <a href="javascript:toggleMenu(\'addwindow\',' + count + ',' + array[i].id + ',\'' + array[i].value + '\');"><span class="orange">Add one!</span></a></div>');	
				
				}
				document.write('</div><div class="contextlink4"><img src="' + base_url + 'includes/images/icons/div.gif" />');
				if (uid) {
					document.write('<a href="javascript:toggleMenu(\'addwindow\',' + count + ',' + array[i].id + ',\'' + array[i].value + '\');"><img src="' + base_url + 'includes/images/icons/addone.gif" title="Add/Edit a context link" /></a>');
					document.write('<a href="javascript:toggleInappropriate(\'addwindow\',' + count + ',' + array[i].id + ',\'' + array[i].value + '\');"><img src="' + base_url + 'includes/images/icons/flag.gif" title="Flag as Inappropriate" /></a>');
				} else {
					document.write('<a href="' + base_url + 'login"><img src="' + base_url + 'includes/images/icons/addone.gif" title="Sign-in to add/edit a context link" /></a>');
				}
				document.write('</div></div><div class="clear"></div>');
			}
		}
		return;
		
		

		
		
}



function submitsearch(test)
{
  //document.searchform.submit();
  //alert(document.forms.searchform.searcha.value);
  jah('' + base_url + 'temp.php?searchtext=' + document.forms.searchform.searcha.value,'jah');
  
}


function clearfield(itemnum) {
//alert ("You clicked OK"); 
//document.getElementById(x).style.color="#999999";
		temp = document.getElementById("entry"+itemnum);
		temp.value = '';
}

function clearall() {
//alert ("You clicked OK"); 
//document.getElementById(x).style.color="#999999";
	var i;
	for (i=1;i<=6;i++) {
		temp = document.getElementById("entry"+i);
		temp.value = '';
	}
}


function popfield(description) {
	marker = 0;
	var i;
	for (i=1;i<=6;i++)  {
		temp = document.getElementById("entry"+i);
		if (temp.value == description) {
			marker = 1;
			break;
		}
	}
	for (i=1;i<=6;i++)  {
		temp = document.getElementById("entry"+i);
		if (temp.value == '') {
			if (marker == 0) {
				temp.value = description;
				break;
			}
		}
	}
}



function readCookie(name) {

var cookiename = name + "=", ca = document.cookie.split(';'), i;

for(i=0;i < ca.length;i++) {

while (ca[i].charAt(0)==' ') ca[i] = ca[i].substring(1,ca[i].length);

if (ca[i].indexOf(cookiename) == 0) return ca[i].substring(cookiename.length,ca[i].length);

}

return null;
}



function urldecode( str ) {
	var ret;
    if (str) {
    ret = str;
       
    ret = ret.replace(/\+/g, '%20');
    ret = decodeURIComponent(ret);
    ret = ret.toString();
	} else {
		ret = '';
	}
    return ret;
}



function toggleLayer( whichLayer )
{
  var elem, vis;
  if( document.getElementById ) // this is the way the standards work
    elem = document.getElementById( whichLayer );
  else if( document.all ) // this is the way old msie versions work
      elem = document.all[whichLayer];
  else if( document.layers ) // this is the way nn4 works
    elem = document.layers[whichLayer];
  vis = elem.style;
  // if the style.display value is blank we try to figure it out here
  if(vis.display==''&&elem.offsetWidth!=undefined&&elem.offsetHeight!=undefined)
    vis.display = (elem.offsetWidth!=0&&elem.offsetHeight!=0)?'block':'none';
  vis.display = (vis.display==''||vis.display=='block')?'none':'block';
	
}

function toggleLayer2( whichLayer )
{
  var elem, vis, element = document.getElementById("scrollerrec"), itemid = document.getElementById("item" + whichLayer.substr(5));
  if( document.getElementById ) // this is the way the standards work
    elem = document.getElementById( whichLayer );
  else if( document.all ) // this is the way old msie versions work
      elem = document.all[whichLayer];
  else if( document.layers ) // this is the way nn4 works
    elem = document.layers[whichLayer];
  vis = elem.style;
  // if the style.display value is blank we try to figure it out here
  if(vis.display==''&&elem.offsetWidth!=undefined&&elem.offsetHeight!=undefined)
    vis.display = (elem.offsetWidth!=0&&elem.offsetHeight!=0)?'block':'none';
  vis.display = (vis.display==''||vis.display=='block')?'none':'block';
	//element.scrollTop = elem.style.top;
	//alert (elem.offsetTop - itemid.scrollTop);
	
	//alert(itemid.offsetTop - element.scrollTop);
	if (itemid.offsetTop - element.scrollTop > 215) { // 175 is the total highet of the div (currently 325) minus the hieght of the context box (150px)
	element.scrollTop = itemid.offsetTop - (265 - 60); // 150 is height of context box.
	}
	
}


function toggleMenu( whichLayer, index, itemid, description)
{
  index = index;
  itemid = itemid;
  var elem, vis;
  if( document.getElementById ) // this is the way the standards work
    elem = document.getElementById( whichLayer );
  else if( document.all ) // this is the way old msie versions work
      elem = document.all[whichLayer];
  else if( document.layers ) // this is the way nn4 works
    elem = document.layers[whichLayer];
  vis = elem.style;
  // if the style.display value is blank we try to figure it out here
  if(vis.display==''&&elem.offsetWidth!=undefined&&elem.offsetHeight!=undefined)
    vis.display = (elem.offsetWidth!=0&&elem.offsetHeight!=0)?'block':'none';
  vis.display = (vis.display==''||vis.display=='block')?'none':'block';
  document.getElementById(whichLayer).innerHTML = '\
      <div id="window">\
        <div class="xclose"><a href="javascript:toggleLayer(\'addwindow\');">\
            <img src="' + base_url + 'includes/images/x3.gif" /></a>\
        </div>\
        <div class="titletext">\
		add/update a context link to\
		</div>\
        <div class="clear"></div>\
        <div class="listtitle">\
        ' + description + '\
        </div>\
        <div class="spacer"></div>\
        <div class="menutext">\
        What kind link or location would you like to add/update?\
        </div>\
      <form name="contextform" action="' + base_url + 'addcontext" method="post">\
	    <input name="indexnum" id="indexnum" type="hidden" value="' + index + '" />\
	    <input name="itemid" id="itemid" type="hidden" value="' + itemid + '" />\
		<input name="description" id="description" type="hidden" value="' + description + '" />\
        <select name="type" id="typebox"  tabindex="1">\
          <option value="1" selected="selected">Google Maps Location</option>\
          <option value="2">Wikipedia Entry</option>\
          <option value="3">Amazon Product Page</option>\
          <option value="4">IMDB Entry</option>\
		  <option value="5">YouTube Video</option>\
        </select>\
        <br/>\
        Paste Link:\
        <br/>\
        <input name="linkaddy" id="linkaddy" class="thing" type="text"  tabindex="2"/>\
        <br/>\
         <div class="notetext">note: link must originate from selected service or it will be ignored. Example: a Google Map must start with URL "http://maps.google.com/"</div>\
	 </form>\
        <a href="javascript: SubmitContext(\'index' + index + '\');"><span class="button">submit</span></a>&nbsp;\
    </div>';
}


function toggleAddTag( whichLayer, index, tid, description)
{
  index = index;
  tid = tid
  var elem, vis;
  if( document.getElementById ) // this is the way the standards work
    elem = document.getElementById( whichLayer );
  else if( document.all ) // this is the way old msie versions work
      elem = document.all[whichLayer];
  else if( document.layers ) // this is the way nn4 works
    elem = document.layers[whichLayer];
  vis = elem.style;
  // if the style.display value is blank we try to figure it out here
  if(vis.display==''&&elem.offsetWidth!=undefined&&elem.offsetHeight!=undefined)
    vis.display = (elem.offsetWidth!=0&&elem.offsetHeight!=0)?'block':'none';
  vis.display = (vis.display==''||vis.display=='block')?'none':'block';
  document.getElementById(whichLayer).innerHTML = '\
      <div id="window">\
        <div class="xclose"><a href="javascript:toggleLayer(\'addwindow\');">\
            <img src="' + base_url + 'includes/images/x3.gif" /></a>\
        </div>\
        <div class="titletext">\
		add a tag to\
		</div>\
        <div class="clear"></div>\
        <div class="listtitle">\
        ' + description + '\
        </div>\
        <div class="spacer"></div>\
        <div class="menutext">\
        \
        </div>\
      <form name="addtagform" action="' + base_url + 'addtag" method="post">\
	    <input name="indexnum" id="indexnum" type="hidden" value="' + index + '" />\
	    <input name="tid" id="tid" type="hidden" value="' + tid + '" />\
		<input name="description" id="description" type="hidden" value="' + description + '" />\
        type in a new tag:\
        <br/>\
        <input name="tagname" id="tagname" class="thing" type="text"  tabindex="1"/>\
        <br/>\
         <div class="notetext">note: will ignore tags with weird characters</div>\
	 </form>\
        <a href="javascript: SubmitTag(\'' + index + '\');"><span class="button">submit</span></a>&nbsp;\
    </div>';
}



function toggleInappropriate( whichLayer, index, itemid, description)
{
  index = index;
  itemid = itemid;
  var elem, vis;
  if( document.getElementById ) // this is the way the standards work
    elem = document.getElementById( whichLayer );
  else if( document.all ) // this is the way old msie versions work
      elem = document.all[whichLayer];
  else if( document.layers ) // this is the way nn4 works
    elem = document.layers[whichLayer];
  vis = elem.style;
  // if the style.display value is blank we try to figure it out here
  if(vis.display==''&&elem.offsetWidth!=undefined&&elem.offsetHeight!=undefined)
    vis.display = (elem.offsetWidth!=0&&elem.offsetHeight!=0)?'block':'none';
  vis.display = (vis.display==''||vis.display=='block')?'none':'block';
  document.getElementById(whichLayer).innerHTML = '\
      <div id="window">\
        <div class="xclose"><a href="javascript:toggleLayer(\'addwindow\');">\
            <img src="' + base_url + 'includes/images/x3.gif" /></a>\
        </div>\
        <div class="titletext">\
		Flag as inappropriate\
		</div>\
        <div class="clear"></div>\
        <div class="listtitle">\
        ' + description + '\
        </div>\
        <div class="spacer"></div>\
        <div class="menutext">\
        When this has item has been tagged enough times it will be removed. \
        </div>\
      <form name="inappropriateform" action="' + base_url + 'inappropriate" method="post">\
	    <input name="indexnum" id="indexnum" type="hidden" value="' + index + '" />\
	    <input name="itemid" id="itemid" type="hidden" value="' + itemid + '" />\
		<input name="description" id="description" type="hidden" value="' + description + '" />\
         <div class="notetext">note: Your decision will be recorded and could be grounds for banning if the item is really not inappropriate, so don\'t do this willy nilly. Yes, willy nilly.</div>\
	 </form>\
        <a href="javascript: SubmitInappropriate(\'index' + index + '\');"><span class="button">submit as inappropriate</span></a>&nbsp;\
    </div>';
}

function toggleInappropriateTopic( whichLayer, tid, description)
{
  tid = tid;
  var elem, vis;
  if( document.getElementById ) // this is the way the standards work
    elem = document.getElementById( whichLayer );
  else if( document.all ) // this is the way old msie versions work
      elem = document.all[whichLayer];
  else if( document.layers ) // this is the way nn4 works
    elem = document.layers[whichLayer];
  vis = elem.style;
  // if the style.display value is blank we try to figure it out here
  if(vis.display==''&&elem.offsetWidth!=undefined&&elem.offsetHeight!=undefined)
    vis.display = (elem.offsetWidth!=0&&elem.offsetHeight!=0)?'block':'none';
  vis.display = (vis.display==''||vis.display=='block')?'none':'block';
  document.getElementById(whichLayer).innerHTML = '\
      <div id="window">\
        <div class="xclose"><a href="javascript:toggleLayer(\'addwindow\');">\
            <img src="' + base_url + 'includes/images/x3.gif" /></a>\
        </div>\
        <div class="titletext">\
		Flag this topic as inappropriate\
		</div>\
        <div class="clear"></div>\
        <div class="listtitle">\
        ' + description + '\
        </div>\
        <div class="spacer"></div>\
        <div class="menutext">\
        When this has topic has been tagged enough times it will be removed. \
        </div>\
      <form name="inappropriateform" action="' + base_url + 'inappropriatetopic" method="post">\
	    <input name="itemid" id="tid" type="hidden" value="' + tid + '" />\
		<input name="description" id="description" type="hidden" value="' + description + '" />\
         <div class="notetext">note: Your decision will be recorded and could be grounds for banning if the item is really not inappropriate, so don\'t do this willy nilly. Yes, willy nilly.</div>\
	 </form>\
        <a href="javascript: SubmitInappropriateTopic(\'flagtopic' + '\');"><span class="button">submit as inappropriate</span></a>&nbsp;\
    </div>';
}



// Ajax form submission stuff. Next three functions.

function makePOSTRequest(url, parameters, divid2) {
  http_request = false;
 //http_request = false;
  if (window.XMLHttpRequest) { // Mozilla, Safari,...
	 http_request = new XMLHttpRequest();
	 if (http_request.overrideMimeType) {
		// set type accordingly to anticipated content type
		//http_request.overrideMimeType('text/xml');
		http_request.overrideMimeType('text/html');
	 }
  } else if (window.ActiveXObject) { // IE
	 try {
		http_request = new ActiveXObject("Msxml2.XMLHTTP");
	 } catch (e) {
		try {
		   http_request = new ActiveXObject("Microsoft.XMLHTTP");
		} catch (e) {}
	 }
  }
  if (!http_request) {
	 alert('Cannot create XMLHTTP instance');
	 return false;
  }
  masterdivid = divid2; //kind of a hack
  http_request.onreadystatechange = alertContents;
  http_request.open('POST', url, true);
  http_request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
  http_request.setRequestHeader("Content-length", parameters.length);
  http_request.setRequestHeader("Connection", "close");
  http_request.send(parameters);
}

function alertContents() {
  if (http_request.readyState == 4) {
	 if (http_request.status == 200) {
		//alert(http_request.responseText);
		result = http_request.responseText;
		document.getElementById(masterdivid).innerHTML = result;            
	 } else {
		alert('There was a problem with the request.');
	 }
  }
}

function get(obj, divid1) {
  var poststr = "typebox=" + encodeURI( document.getElementById("typebox").value ) +
				"&linkaddy=" + encodeURIComponent( document.getElementById("linkaddy").value ) +
				"&itemid=" + encodeURI( document.getElementById("itemid").value ) +
				"&indexnum=" + encodeURI( document.getElementById("indexnum").value ) +
				"&description=" + encodeURIComponent( document.getElementById("description").value );
  makePOSTRequest(base_url + 'addcontext', poststr, divid1);
}

function get2(obj, divid1) {
  var poststr = "tid=" + encodeURI( document.getElementById("tid").value ) +
 				"&indexnum=" + encodeURI( document.getElementById("indexnum").value ) +
				"&tagname=" + encodeURIComponent( document.getElementById("tagname").value );
  makePOSTRequest(base_url + 'addtag', poststr, divid1);
}

function get3(obj, divid1) {
  var poststr = "itemid=" + encodeURI( document.getElementById("itemid").value ) +
				"&indexnum=" + encodeURI( document.getElementById("indexnum").value ) +
				"&description=" + encodeURIComponent( document.getElementById("description").value );
  makePOSTRequest(base_url + 'inappropriate', poststr, divid1);
}

function get4(obj, divid1) {
  var poststr = "pmid=" + encodeURI( document.getElementById("pmid").value );
  makePOSTRequest(base_url + 'deletepm', poststr, divid1);
}

function get5(obj, divid1) {
  var poststr = "tid=" + encodeURI( document.getElementById("tid").value ) +
				"&description=" + encodeURIComponent( document.getElementById("description").value );
  makePOSTRequest(base_url + 'inappropriatetopic', poststr, divid1);
}




function SubmitContext(indexnum) {
	// do validation here
	toggleLayer('addwindow');
	get(document.getElementById('contextform'), indexnum);

}


function SubmitTag(indexnum) {
	// do validation here
	toggleLayer('addwindow');
	get2(document.getElementById('addtagform'), indexnum);

}


function SubmitInappropriate(indexnum) {
	// do validation here
	toggleLayer('addwindow');
	get3(document.getElementById('inappropriateform'), indexnum);

}

function SubmitInappropriateTopic(tid) {
	// do validation here
	toggleLayer('addwindow');
	get5(document.getElementById('inappropriateform'), 'flagtopic');

}

function DeletePM(indexnum) {
	// do validation here
	get4(document.getElementById('deletepmform'), indexnum);

}


function jah(url,target) {
    // native XMLHttpRequest object
	//var req;
    document.getElementById(target).innerHTML = '<div class="titletext">loading...</div>';
    if (window.XMLHttpRequest) {
        req = new XMLHttpRequest();
        req.onreadystatechange = function() {jahDone(target);};
        req.open("GET", url, true);
        req.send(null);
    // IE/Windows ActiveX version
    } else if (window.ActiveXObject) {
        req = new ActiveXObject("Microsoft.XMLHTTP");
        if (req) {
            req.onreadystatechange = function() {jahDone(target);};
            req.open("GET", url, true);
            req.send();
        }
    }
}    

function jahDone(target) {
    // only if req is "loaded"
	//var req;
    if (req.readyState == 4) {
        // only if "OK"
        if (req.status == 200) {
            results = req.responseText;
            document.getElementById(target).innerHTML = results;
        } else {
            document.getElementById(target).innerHTML="jah error:\n" +
                req.statusText;
        }
    }
}



// Suggestion Code


if (typeof(stax) == "undefined") {
	var _b;
	_b = stax = {};
}

if (typeof(_b.suggest) == "undefined")
	_b.suggest = {};
else
	alert("suggest is already set!");


_b.suggest = function (id, param)
{
	// no DOM - give up!
	//
	if (!document.getElementById)
		return 0;
	
	
	
	
	// get field via DOM
	//
	this.fld = _b.DOM.gE(id);

	if (!this.fld)
		return 0;
	
	
	
	
	// init variables
	//
	this.sInp 	= "";
	this.nInpC 	= 0;
	this.aSug 	= [];
	this.iHigh 	= 0;
	
	
	
	
	// parameters object
	//
	this.oP = param ? param : {};
	
	// defaults	
	//
	var k, p = this, def = {minchars:3, meth:"get", varname:"input", className:"suggest", timeout:2500, delay:500, offsety:-5, shownoresults: true, noresults: "No results!", maxheight: 250, cache: true, maxentries: 15, dosearch: false};
	for (k in def)
	{
		if (typeof(this.oP[k]) != typeof(def[k]))
			this.oP[k] = def[k];
	}
	
	// p = this;
	// set keyup handler for field
	// and prevent autocomplete from client
	//
	
	// NOTE: not using addEventListener because UpArrow fired twice in Safari
	//_b.DOM.addEvent( this.fld, 'keyup', function(ev){ return pointer.onKeyPress(ev); } );
	
	this.fld.onkeypress 	= function(ev){ return p.onKeyPress(ev); };
	this.fld.onkeyup 		= function(ev){ return p.onKeyUp(ev); };
	
	this.fld.setAttribute("autocomplete","off");
};


_b.suggest.prototype.onKeyPress = function(ev)
{
	
	var key = (window.event) ? window.event.keyCode : ev.keyCode, RETURN = 13, TAB = 9,	ESC = 27, bubble = 1;

	switch(key)
	{
		case RETURN:
			this.setHighlightedValue();
			this.clearSuggestions();	
			bubble = 0;
			if (this.oP.dosearch == false) {
			stopBubble(ev);
			}
			break;
		case TAB:
			this.setHighlightedValue();
			this.clearSuggestions();
			bubble = 0;
			break;

		case ESC:
			this.clearSuggestions();
			bubble = 0;
			break;
	}

	return bubble;
};


_b.suggest.prototype.onKeyUp = function(ev)
{
	var key = (window.event) ? window.event.keyCode : ev.keyCode, ARRUP = 38, ARRDN = 40, bubble = 1;

	switch(key)
	{


		case ARRUP:
			this.changeHighlight(key);
			bubble = 0;
			break;


		case ARRDN:
			this.changeHighlight(key);
			bubble = 0;
			break;
		
		
		default:
			this.getSuggestions(this.fld.value);
	}

	return bubble;
	

};


_b.suggest.prototype.getSuggestions = function (val)
{
	
	// if input stays the same, do nothing
	//
	if (val == this.sInp)
		return 0;
	
	
	// kill list
	//
	_b.DOM.remE(this.idAs);
	
	
	this.sInp = val;
	
	
	// input length is less than the min required to trigger a request
	// do nothing
	//
	if (val.length < this.oP.minchars)
	{
		this.aSug = [];
		this.nInpC = val.length;
		return 0;
	}
	
	
	
	
	var ol = this.nInpC, l = this.aSug.length, arr = [], pointer = this, input = this.sInp, i; // old length
	this.nInpC = val.length ? val.length : 0;
	
	
	
	// if caching enabled, and user is typing (ie. length of input is increasing)
	// filter results out of aSuggestions from last request
	//
	//var l = this.aSug.length;
	if (this.nInpC > ol && l && l<this.oP.maxentries && this.oP.cache)
	{
		//var arr = [];
		for (i=0;i<l;i++)
		{
			// This is the old method of just testing first characters
			
			//if (this.aSug[i].value.substr(0,val.length).toLowerCase() == val.toLowerCase())
			//	arr.push( this.aSug[i] );
			
			// This method tests all characters
			if (this.aSug[i].value.toLowerCase().indexOf(val.toLowerCase()) > -1) {
				arr.push( this.aSug[i] )
			}
		}
		this.aSug = arr;
		
		this.createList(this.aSug);
		
		
		
		return false;
	}
	else
	// do new request
	//
	{
		//var pointer = this;
		//var input = this.sInp;
		clearTimeout(this.ajID);
		//this.ajID = setTimeout( function() { pointer.doAjaxRequest(input) }, this.oP.delay );
		this.ajID = setTimeout( function() { pointer.setResults(input) }, this.oP.delay );
	}

	return false;
};

// s6 function

_b.suggest.prototype.setResults = function (input) {

	this.aSug = [];

	// Set a limit here based on count. Right now its everything
	for (var i=0;i<aSugt.length;i++) {
		// This is the old method of just testing first characters
		
		//if (aSugt[i].value.substr(0,input.length).toLowerCase() == input.toLowerCase()) {
		//	this.aSug.push( aSugt[i] );
		//}
		
		// This method tests all characters
		if (aSugt[i].value.toLowerCase().indexOf(input.toLowerCase()) > -1) {
			this.aSug.push( aSugt[i] );
		}
		if (this.oP.maxresults <= i) {
			break;	
		}
	}
	this.idAs = "as_"+this.fld.id;
	this.createList(this.aSug);
	
}







_b.suggest.prototype.createList = function(arr)
{
	
	var div = _b.DOM.cE("div", {id:this.idAs, className:this.oP.className}), hcorner = _b.DOM.cE("div", {className:"as_corner"}), hbar = _b.DOM.cE("div", {className:"as_bar"}), header = _b.DOM.cE("div", {className:"as_header"}), ul = _b.DOM.cE("ul", {id:"as_ul"}), i, val, st, output, span, a, tl, tr, li, fcorner, fbar, footer, pos, pointer = this, br, small;
	
	
	
	
	// get rid of old list
	// and clear the list removal timeout
	//
	_b.DOM.remE(this.idAs);
	this.killTimeout();
	
	
	// if no results, and shownoresults is false, do nothing
	//
	if (arr.length == 0 && !this.oP.shownoresults)
		return false;
	
	
	// create holding div
	//

	
	//var hcorner = _b.DOM.cE("div", {className:"as_corner"});
	//var hbar = _b.DOM.cE("div", {className:"as_bar"});
	//var header = _b.DOM.cE("div", {className:"as_header"});
	header.appendChild(hcorner);
	header.appendChild(hbar);
	div.appendChild(header);
	
	
	
	
	// create and populate ul
	//
	//var ul = _b.DOM.cE("ul", {id:"as_ul"});
	
	
	
	
	// loop throught arr of suggestions
	// creating an LI element for each suggestion
	//
	for (i=0;i<arr.length;i++)
	{
		// format output with the input enclosed in a EM element
		// (as HTML, not DOM)
		//
		val = arr[i].value;
		st = val.toLowerCase().indexOf( this.sInp.toLowerCase() );
		output = val.substring(0,st) + "<em>" + val.substring(st, st+this.sInp.length) + "</em>" + val.substring(st+this.sInp.length);
		
		
		span 		= _b.DOM.cE("span", {}, output, true);
		if (arr[i].info != "")
		{
			br			= _b.DOM.cE("br", {});
			span.appendChild(br);
			small		= _b.DOM.cE("small", {}, arr[i].info);
			span.appendChild(small);
		}
		
		a 			= _b.DOM.cE("a", { href:"#" });
		
		tl 		= _b.DOM.cE("span", {className:"tl"}, " ");
		tr 		= _b.DOM.cE("span", {className:"tr"}, " ");
		a.appendChild(tl);
		a.appendChild(tr);
		
		a.appendChild(span);
		
		a.name = i+1;
		a.onclick = function () { pointer.setHighlightedValue(); return false; };
		a.onmouseover = function () { pointer.setHighlight(this.name); };
		
		li = _b.DOM.cE(  "li", {}, a  );
		
		ul.appendChild( li );
	}
	
	
	// no results
	//
	if (arr.length == 0 && this.oP.shownoresults)
	{
		li = _b.DOM.cE(  "li", {className:"as_warning"}, this.oP.noresults  );
		ul.appendChild( li );
	}
	
	
	div.appendChild( ul );
	
	
	fcorner = _b.DOM.cE("div", {className:"as_corner"});
	fbar = _b.DOM.cE("div", {className:"as_bar"});
	footer = _b.DOM.cE("div", {className:"as_footer"});
	footer.appendChild(fcorner);
	footer.appendChild(fbar);
	div.appendChild(footer);
	
	
	
	// get position of target textfield
	// position holding div below it
	// set width of holding div to width of field
	//
	pos = _b.DOM.getPos(this.fld);
	
	div.style.left 		= pos.x + "px";
	div.style.top 		= ( pos.y + this.fld.offsetHeight + this.oP.offsety ) + "px";
	div.style.width 	= this.fld.offsetWidth + "px";
	
	
	
	// set mouseover functions for div
	// when mouse pointer leaves div, set a timeout to remove the list after an interval
	// when mouse enters div, kill the timeout so the list won't be removed
	//
	div.onmouseover 	= function(){ pointer.killTimeout() };
	div.onmouseout 		= function(){ pointer.resetTimeout() };


	// add DIV to document
	//
	document.getElementsByTagName("body")[0].appendChild(div);
	
	
	
	// currently no item is highlighted
	//
	this.iHigh = 0;
	
	
	
	
	
	
	// remove list after an interval
	//
	pointer = this;
	this.toID = setTimeout(function () { pointer.clearSuggestions() }, this.oP.timeout);
};















_b.suggest.prototype.changeHighlight = function(key)
{	
	var list = _b.DOM.gE("as_ul"), n;
	if (!list)
		return false;

	if (key == 40)
		n = this.iHigh + 1;
	else if (key == 38)
		n = this.iHigh - 1;
	
	
	if (n > list.childNodes.length)
		n = list.childNodes.length;
	if (n < 1)
		n = 1;
	
	
	this.setHighlight(n);
};



_b.suggest.prototype.setHighlight = function(n)
{
	var list = _b.DOM.gE("as_ul");
	if (!list)
		return false;
	
	if (this.iHigh > 0)
		this.clearHighlight();
	
	this.iHigh = Number(n);
	
	list.childNodes[this.iHigh-1].className = "as_highlight";


	this.killTimeout();
};


_b.suggest.prototype.clearHighlight = function()
{
	var list = _b.DOM.gE("as_ul");
	if (!list)
		return false;
	
	if (this.iHigh > 0)
	{
		list.childNodes[this.iHigh-1].className = "";
		this.iHigh = 0;
	}
};


_b.suggest.prototype.setHighlightedValue = function ()
{
	if (this.iHigh)
	{
		this.sInp = this.fld.value = this.aSug[ this.iHigh-1 ].value;
		
		// move cursor to end of input (safari)
		//
		this.fld.focus();
		if (this.fld.selectionStart)
			this.fld.setSelectionRange(this.sInp.length, this.sInp.length);
		

		this.clearSuggestions();
		
		// pass selected object to callback function, if exists
		//
		if (typeof(this.oP.callback) == "function")
			this.oP.callback( this.aSug[this.iHigh-1] );
	}
};













_b.suggest.prototype.killTimeout = function()
{
	clearTimeout(this.toID);
};

_b.suggest.prototype.resetTimeout = function()
{
	clearTimeout(this.toID);
	var pointer = this;
	this.toID = setTimeout(function () { pointer.clearSuggestions() }, 1000);
};







_b.suggest.prototype.clearSuggestions = function ()
{
	
	this.killTimeout();
	
	var ele = _b.DOM.gE(this.idAs), pointer = this, fade;
	if (ele)
	{
		fade = new _b.Fader(ele,1,0,250,function () { _b.DOM.remE(pointer.idAs) });
	}
};










// AJAX PROTOTYPE _____________________________________________


if (typeof(_b.Ajax) == "undefined")
	_b.Ajax = {};



_b.Ajax = function ()
{
	this.req = {};
	this.isIE = false;
};



_b.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();
		}
	}
};


_b.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 );
		}
	}
};










// DOM PROTOTYPE _____________________________________________


if (typeof(_b.DOM) == "undefined")
	_b.DOM = {};



/* create element */
_b.DOM.cE = function ( type, attr, cont, html )
{
	var ne = document.createElement( type ), t, a;
	if (!ne)
		return 0;
		
	for (a in attr)
		ne[a] = attr[a];
	
	t = typeof(cont);
	
	if (t == "string" && !html)
		ne.appendChild( document.createTextNode(cont) );
	else if (t == "string" && html)
		ne.innerHTML = cont;
	else if (t == "object")
		ne.appendChild( cont );

	return ne;
};



/* get element */
_b.DOM.gE = function ( e )
{
	var t=typeof(e), re;
	if (t == "undefined")
		return 0;
	else if (t == "string")
	{
		re = document.getElementById( e );
		if (!re)
			return 0;
		else if (typeof(re.appendChild) != "undefined" )
			return re;
		else
			return 0;
	}
	else if (typeof(e.appendChild) != "undefined")
		return e;
	else
		return 0;
};



/* remove element */
_b.DOM.remE = function ( ele )
{
	var e = this.gE(ele);
	
	if (!e)
		return 0;
	else if (e.parentNode.removeChild(e))
		return true;
	else
		return 0;
};



/* get position */
_b.DOM.getPos = function ( e )
{
	var e2 = this.gE(e), obj = e2, curleft = 0, curtop;
	if (obj.offsetParent)
	{
		while (obj.offsetParent)
		{
			curleft += obj.offsetLeft;
			obj = obj.offsetParent;
		}
	}
	else if (obj.x)
		curleft += obj.x;
	
	obj = e2;
	
	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};
};


// Extra s6 stuff

function stopBubble(e)
	{
		bubble = 0;
	if (e.preventDefault) {
		e.preventDefault();
		e.stopPropagation();
	} else {
		e.returnValue = false;
		e.cancelBubble = true;
	}
}







// FADER PROTOTYPE _____________________________________________



if (typeof(_b.Fader) == "undefined")
	_b.Fader = {};





_b.Fader = function (ele, from, to, fadetime, callback)
{	
	if (!ele)
		return 0;
	
	this.e = ele;
	
	this.from = from;
	this.to = to;
	
	this.cb = callback;
	
	this.nDur = fadetime;
		
	this.nInt = 50;
	this.nTime = 0;
	
	var p = this;
	this.nID = setInterval(function() { p._fade() }, this.nInt);
};




_b.Fader.prototype._fade = function()
{
	this.nTime += this.nInt;
	
	var ieop = Math.round( this._tween(this.nTime, this.from, this.to, this.nDur) * 100 ), op;
	op = ieop / 100;
	
	if (this.e.filters) // internet explorer
	{
		try
		{
			this.e.filters.item("DXImageTransform.Microsoft.Alpha").opacity = ieop;
		} catch (e) { 
			// If it is not set initially, the browser will throw an error.  This will set it if it is not set yet.
			this.e.style.filter = 'progid:DXImageTransform.Microsoft.Alpha(opacity='+ieop+')';
		}
	}
	else // other browsers
	{
		this.e.style.opacity = op;
	}
	
	
	if (this.nTime == this.nDur)
	{
		clearInterval( this.nID );
		if (this.cb != undefined)
			this.cb();
	}
};



_b.Fader.prototype._tween = function(t,b,c,d)
{
	return b + ( (c-b) * (t/d) );
};


var DDSPEED = 5;
var DDTIMER = 25;

// main function to handle the mouse events //
function ddMenu(id,d){
  var h = document.getElementById(id + '-ddheader');
  var c = document.getElementById(id + '-ddcontent');
  clearInterval(c.timer);
  if(d == 1){
    clearTimeout(h.timer);
    if(c.maxh && c.maxh <= c.offsetHeight){return}
    else if(!c.maxh){
      c.style.display = 'block';
      c.style.height = 'auto';
      c.maxh = c.offsetHeight;
      c.style.height = '0px';
    }
    c.timer = setInterval(function(){ddSlide(c,1)},DDTIMER);
  }else{
    h.timer = setTimeout(function(){ddCollapse(c)},50);
  }
}

// collapse the menu //
function ddCollapse(c){
  c.timer = setInterval(function(){ddSlide(c,-1)},DDTIMER);
}

// cancel the collapse if a user rolls over the dropdown //
function cancelHide(id){
  var h = document.getElementById(id + '-ddheader');
  var c = document.getElementById(id + '-ddcontent');
  clearTimeout(h.timer);
  clearInterval(c.timer);
  if(c.offsetHeight < c.maxh){
    c.timer = setInterval(function(){ddSlide(c,1)},DDTIMER);
  }
}

// incrementally expand/contract the dropdown and change the opacity //
function ddSlide(c,d){
  var currh = c.offsetHeight;
  var dist;
  if(d == 1){
    dist = (Math.round((c.maxh - currh) / DDSPEED));
  }else{
    dist = (Math.round(currh / DDSPEED));
  }
  if(dist <= 1 && d == 1){
    dist = 1;
  }
  c.style.height = currh + (dist * d) + 'px';
  c.style.opacity = currh / c.maxh - .1;
  c.style.filter = 'alpha(opacity=' + ((currh * 100 / c.maxh) - .1) + ')';
  if((currh < 2 && d != 1) || (currh > (c.maxh - 2) && d == 1)){
    clearInterval(c.timer);
  }
}

function gotomystax() {
	window.location = base_url + "mystax";

}
