$(document).ready(function(){		
	jQuery.fn.exists = function(){return jQuery(this).length>0;}
	jQuery.expr[':'].focus = function( elem ) {
	  return elem === document.activeElement && ( elem.type || elem.href );
	};
	
	$.saytns = { 
		id : 0,
		keyed: ''
	};
	
	//if focus leaves the text box
	$("#sayt_frm input[type='text'], #sayt_frm2 input[type='text']").blur(function(){
			$().mousemove(function(e){
				if( $.trim($("#sayt_box").html()) != '' ){
					var left   = $('#sayt_box').offset().left;
					var right = left + $('#sayt_box').width() + 8;
					var top = $('#sayt_box').offset().top;
					var bottom = top + $('#sayt_box').height() + 8;
					/* console.log("left: " + left + ", width: " + $('#sayt_box').width() + ", top: " + top + 
							    ", height: " + $('#sayt_box').height() +
								", padding: " + ($("#sayt_box").css('padding').replace('px','') * 2));
					console.log("left: " + left + ", right: " + right + ", top: " + top + ", bottom: " + bottom);
					console.log(e.pageX + ", " + e.pageY); */
					if( e.pageX < left || e.pageX > right || e.pageY < top || e.pageY > bottom ){
						if( !($("#sayt_frm input[type='text']").is(":focus")) && 
							!($("#sayt_frm2 input[type='text']").is(":focus")) ){
							$("#sayt_box").hide();
							$("#sayt_box").html('');
						}
					}
				}
			});
	});
	
	/*$("#sayt_box").mouseout(function(e){
		var left   = $('#sayt_box').offset().left;
		var right = $('#sayt_box').offset().left + $('#sayt_box').width();
		var top = $('#sayt_box').offset().top;
		var bottom = $('#sayt_box').offset().top + $('#sayt_box').height();
		//console.log("left: " + left + ", right: " + right + ", top: " + top + ", bottom: " + bottom);
		//console.log(e.pageX + ", " + e.pageY);
		if( e.pageX < left || e.pageX > right || e.pageY < top || e.pageY > bottom ){
			if( !($("#sayt_frm input[type='text']").is(":focus")) && !($("#sayt_frm2 input[type='text']").is(":focus")) ){
				$("#sayt_box").hide();
				$("#sayt_box").html('');
			}
		}
	});*/
	
	//on keyup display 'search as you type'
	$("#sayt_frm input[type='text'], #sayt_frm2 input[type='text']").keyup(function(e){
		var q = $(this);
		var code = (e.keyCode ? e.keyCode : e.which);
		//check which key was pressed
		if( e.keyCode == 40 ){
			//if tab or arrow down was pressed, scroll through suggestions
			$.saytns.id++;
			if( !($("#sayt"+$.saytns.id).exists()) ){
				$.saytns.id=0;
				q.val($.saytns.keyed);
				$("#sayt_box a").css({'background-color' : 'transparent'});
			}
			else{
				$("#sayt_box a").css({'background-color' : 'transparent'});
				$("#sayt"+$.saytns.id).css({'background-color' : '#E4EDFA'});
				q.val($("#sayt"+$.saytns.id).html());
			}
			
		}
		else if( e.keyCode == 38 ){
			//if arrow up with pressed move up on suggestion
			$.saytns.id--;
			if( $.saytns.id == 0 ){
				q.val($.saytns.keyed);
				$("#sayt_box a").css({'background-color' : 'transparent'});
			}
			else if( $.saytns.id < 0 ){
				$.saytns.id = 5;
				while( !($("#sayt"+$.saytns.id).exists()) ){
					$.saytns.id--;
				}
			}
			if( $("#sayt"+$.saytns.id).exists() ){
				$("#sayt_box a").css({'background-color' : 'transparent'});
				$("#sayt"+$.saytns.id).css({'background-color' : '#E4EDFA'});
				q.val( $("#sayt"+$.saytns.id).html() );
			}
		}
		else{
			//grab search suggestions and reset selected suggestion
			$.saytns.id = 0;
			$("#sayt_box a").css({'background-color' : 'transparent'});
			$.saytns.keyed = q.val();
			
			//use ajax post to grab suggestions
			$.post("/post/sayt.cfm", {
				q: q.val(),
				wtd: 'sayt'
			}, function(data){
				if($.trim(data) != ''){
					//determine if browser is IE, set width of sayt_box
					if( navigator.appName == 'Microsoft Internet Explorer' )
						var wdth = q.width();
					else
						var wdth = q.width() - $("#sayt_box").css('padding').replace('px','');
					$("#sayt_box").width(wdth);
					//position sayt_box under current text box, gather location info
					pos   = q.offset();
					width = q.width();					
					$("#sayt_box").css({ "left" : pos.left + "px", "top" : (pos.top+30) + "px" }).show();
					$("#sayt_box").html(data);
				} else{
					$("#sayt_box").hide();
					$("#sayt_box").html('');
				}
			}, "html"); //close $.post(..
		}
	});	
	
	/*on submit update the click count of the selected query
	$("#sayt_frm").submit(function(){
		var q = $("#sayt_frm input[type='text']");
		$.post("sayt_post.cfm", {
			q: q.val(),
			wtd: 'plusone'
		}, function(data){
			$("#plusone_dump").show();
			$("#plusone_dump").html(data);
			return true;
		}, "html"); //close $.post(..
	});*/
});
	
function findAndReplace(searchText, replacement, searchNode) {
    if (!searchText || typeof replacement === 'undefined') {
        // Throw error here if you want...
        return;
    }
    var regex = typeof searchText === 'string' ?
                new RegExp(searchText, 'g') : searchText,
        childNodes = (searchNode || document.body).childNodes,
        cnLength = childNodes.length,
        excludes = 'html,head,style,title,link,meta,script,object,iframe';
    while (cnLength--) {
        var currentNode = childNodes[cnLength];
        if (currentNode.nodeType === 1 &&
            (excludes + ',').indexOf(currentNode.nodeName.toLowerCase() + ',') === -1) {
            arguments.callee(searchText, replacement, currentNode);
        }
        if (currentNode.nodeType !== 3 || !regex.test(currentNode.data) ) {
            continue;
        }
        var parent = currentNode.parentNode,
            frag = (function(){
                var html = currentNode.data.replace(regex, replacement),
                    wrap = document.createElement('div'),
                    frag = document.createDocumentFragment();
                wrap.innerHTML = html;
                while (wrap.firstChild) {
                    frag.appendChild(wrap.firstChild);
                }
                return frag;
            })();
        parent.insertBefore(frag, currentNode);
        parent.removeChild(currentNode);
    }
}
