var lasttarget    = '';
var currhighlight = '';
var NO_FOCUS_TEXT = 'Search';

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 clearAllHighlights() {
    var tot = $('search_results').childNodes.length;
    for (i=0; i<tot; i++) {
        var name = 'resultnum-' + i;
        $(name).removeClassName('highlight');    
    }
}

function changeHighlight(delta) {
    if (currhighlight == '') {
        var i = '-1';
    } else {
        var i = currhighlight.substring(10, currhighlight.length);
        clearAllHighlights();
    }
    
    var tot = $('search_results').childNodes.length;
    i       = parseInt(i);
    i       = i + delta;
    if (i < 0) {
        i = tot - 1;
    } else if (i>=tot) {
        i = 0;
    }
    currhighlight = 'resultnum-' + i;
    $(currhighlight).addClassName('highlight');
    
    $('searchbox').value = $(currhighlight).dbrow.name;

}

function docKeyPress(ev) {
    var code    = ev.keyCode;    
    if (code == Event.KEY_ESC) {
        $('sboxttip').hide();
        $('search_results').hide();
    }
}

function onKeyPress(ev) {
    var code    = ev.keyCode;
    if (code == Event.KEY_ESC) {
        $('sboxttip').hide();
        $('search_results').hide();
        return;
    }

    if (code == Event.KEY_UP) {
        $('search_results').show();
        $('sboxttip').hide();
        changeHighlight(-1);
        return;
    }

    if (code == Event.KEY_DOWN) {
        $('search_results').show();
        $('sboxttip').hide();
        changeHighlight(1);
        return;
    }
    

    var target = $F('searchbox').trim();
    target     = target.toLowerCase();

    if (target == '') {
        $('imgSboxRight').src = '/searchbox/sboxright.png'; 
        $('imgSboxRight').style.cursor = 'default';
        $('search_results').hide();
        $('sboxttip').hide();
        delChildren('search_results');
        return;
    }

    $('imgSboxRight').style.cursor = 'pointer';
    $('imgSboxRight').src = '/searchbox/sboxrightdel.png';
    if (target == lasttarget) {
        var keychar = String.fromCharCode(code).toLowerCase();
        var x = ("abcdefghijklmnopqrstuvwxyz0123456789").indexOf(keychar);
        if (x == -1) {
            return;
        }
        $('search_results').show();
        return;
    }

    lasttarget = target;
    setTTipPos(ev);
//    mouseMovementRow(ev);
    // $('search_results').show();
/*

    var tov    = setTimeout(maybeSendAjax,500);
}

function maybeSendAjax() {
    var target = $F('searchbox').trim();
    target     = target.toLowerCase();
    if (target != lasttarget) {
        return;
    }
*/
    
	var pars   = 't=' + target;
	var url    = '/cgi-bin/search.py';
	var myAjax = new Ajax.Request(
		url, 
		{
			method: 'get', 
			parameters: pars, 
			onComplete: sboxResults
		}
    );
}

function delChildren(pnode) {
    var pnode = $(pnode);
    if (!pnode) {
        return;
    }
    while (pnode.childNodes.length > 0) {
        pnode.removeChild( pnode.firstChild );           
    }
}

function insertBoldTags(txt) {
    var i = txt.toLowerCase().indexOf(lasttarget);
    var o = i+lasttarget.length;
    var r = txt.substring(0, i);
    r = r + '<b>' + txt.substring(i,o) + '</b>';
    r = r + txt.substring(o, txt.length);
    return r;
}

function showDesc(dbrow, content) {
    var h = '<table style="padding:0; margin:0; border-collapse: collapse;">';
    h = h + '<tr>';
    
    h = h + '<td valign="top" style="text-align:right; ';
    h = h + 'padding:25px 10px 25px 30px; '; 
    h = h + ' background:transparent ';
    h = h + 'url(/searchbox/ttipbg.png) top left no-repeat;">';
    
    if (content) {
        h = h + '</td>';
    } else {
        // Content
        h = h + '<img style="border:1px #444 solid; " '
        if (dbrow.path) {
            h = h + 'src="http://geraniaceae.com/images/thumbs/';
            h = h + dbrow.path + '"'
        } else {
            h = h + 'src="/searchbox/missing.png"';
        }
        
        h = h + '>';
        h = h + '</td>';
    }
    h = h + '<td ';
    h = h + 'style="padding:25px 60px 0 0; color:#444;';
    h = h + 'background:transparent url(/searchbox/ttipbg.png) top right no-repeat;">';
    if (content) {
        h = h + content;
    } else {
        h = h + '<span class="ttipttl">' + dbrow.name + '</span><BR>';
        h = h + dbrow.category + ' // ' + dbrow.subcat + '<BR>';
        h = h + '<span class="ttipdesc"><BR>' + dbrow.description + '</span><BR><BR>';
        if (dbrow.zone) {
            h = h + 'zone: ' + dbrow.zone + ' // ';
        }
        if (dbrow.season) {
            h = h + 'season: ' + dbrow.season + ' // ';
        }
        if (dbrow.plantsize) {
            h = h + 'size: ' + dbrow.plantsize;
        }
    }
    h = h + '</td>';
    h = h + '</tr>';
    h = h + '<tr>';
    h = h + '<td style="height:50px; background:transparent url(/searchbox/ttipbg.png) bottom left no-repeat;">';
    h = h + '</td>';
    h = h + '<td style="height:50px; background:transparent url(/searchbox/ttipbg.png) bottom right no-repeat;">';
    h = h + '</td>';
    h = h + '</tr>';
    h = h + '</table>';
    $('sboxttip').innerHTML = h;
}

function overThumbCB(imgpath, plantname, photographer, cat, subcat) {
    var html = '<div style="min-height:350px; min-width:400px;">'
    html = html + '<div class="thumbOverTitle">';
    html = html + plantname;
    html = html + '    <div class="thumbOverSubtitle">';
    html = html + cat + ' (' + subcat + ')';
    html = html + '    </div>';
    html = html + '</div>'
    html = html + '<img style="border:1px #000 solid; max-height:300px;" src="/images/full/' + imgpath + '"><BR>';
    html = html + '<div class="photocap">Photo by ' + photographer + '</div>';
    html = html + '</div>';
    showDesc('', html);
    
}

function textTTipCB(txt, img) {
    var showme = '';
    if (img) {
        img = '/images/thumbs/' + img;
    } else {
        img = '/searchbox/missing.png';
    }
    showme = '<img style=" margin:20px 20px 20px 0; float:left;" src="' + img + '">';
    showme = showme +  '<div style="max-width:150px; float:left; margin:10px 0;">'+txt+'</div>'
    showDesc('', showme);
}

function setTTipPos(e) {

    var offs      = document.viewport.getScrollOffsets();
    
    //-------- Left Coord --------//
    var x         = Event.pointerX(e);
    var ttipWidth = $('sboxttip').getWidth();
    ttipWidth = ttipWidth + (ttipWidth/4);
    var winWidth  = document.viewport.getWidth();

    if (x+ttipWidth > winWidth) {
         // The tooltip extends off the edge of the screen.
         x = x - ttipWidth + 70;
    } else {
         x = x + 30;
    }

    //x = x - winWidth;


    $('sboxttip').style.left = x + 'px';

    //-------- Top Coord --------//
    var absY       = Event.pointerY(e);
    var relY       = absY - offs.top;
    var ttipHeight = $('sboxttip').getHeight();
    var winHeight  = document.viewport.getHeight();
    

    if ((relY + ttipHeight) < winHeight) {
        var t = absY - 30; //30
    } else {
        var t = offs.top + winHeight - ttipHeight;
    }
    
    $('sboxttip').style.top  = t + 'px';    

//    $('coords').innerHTML = deltaY + ', ' +relY + ', ' + ttipHeight + ', '+  winHeight;
}

function imageElemLoaded(img_elem) {
    img_elem.observe('mousemove', mouseMovementRow);    
}

function imageExited() {
    $('sboxttip').hide();
}

function mouseMovementRow(e) {
    setTTipPos(e);
    $('sboxttip').show();    
}

function mouseEnteredRow(ev) {
    clearAllHighlights();
    currhighlight = this.id;
    this.addClassName('highlight');
    showDesc(this.dbrow);
}

function mouseExitedRow(ev) {
  this.removeClassName('highlight');
  $('sboxttip').hide();
}

function openDetails(plantid) {
    var url ='http://geraniaceae.com/cgi-bin/detail.py?id=' + plantid;
    document.location = url;
}

function onBlurCB() {
    $('sboxttip').hide();
    $('search_results').hide();
    if ($F('searchbox').trim() == '') {
        $('searchbox').value = NO_FOCUS_TEXT;
        $('searchbox').style.color = '#999';
    }

}

function onFocusCB() {
    if ($('searchbox').value == NO_FOCUS_TEXT) {
        $('searchbox').value = '';
        $('searchbox').style.color = '#333';
    }
}

function sboxResults(originalRequest) {


	var results = originalRequest.responseText;
	results     = results.evalJSON();
	var n       = '';
	delChildren('search_results');
	$('sboxttip').hide();

	for (var i=0; i<results.length; i++) {

	    var dbrow          = results[i];
        var my_div         = document.createElement('div');
        my_div             = Element.extend(my_div);
        my_div.className   = 'searchresult';
        my_div.dbrow       = dbrow;
        my_div.id          = 'resultnum-' + i;
        
        my_div.observe('mousemove', mouseMovementRow);
        my_div.observe('mouseover', mouseEnteredRow);
        my_div.observe('mouseout', mouseExitedRow);
    	my_div.observe('mousedown', function() {openDetails(this.dbrow.plantid);});

        var img = document.createElement('img');
        img.className      = 'searchresultimg';
        if (dbrow.path) {
            img.src = 'http://geraniaceae.com/images/thumbs/'+dbrow.path;
        } else {
            img.src = '/searchbox/missing.png';
        }
        my_div.appendChild(img);

        var stxt_div       = document.createElement('div');
        stxt_div.className = 'searchresulttxt';

        var ttl            = document.createElement('div');
        ttl.className      = 'searchpname';
        var hiname         = insertBoldTags(dbrow.name);
        ttl.innerHTML      = hiname + '<BR>';
        my_div.appendChild(stxt_div);
        stxt_div.appendChild(ttl);

        var ttl = document.createElement('span');
        ttl.className      = 'searchpnamesub';
        ttl.innerHTML      = dbrow.category + ' // ' + dbrow.subcat;
        stxt_div.appendChild(ttl);
        
        var cdiv           = document.createElement('div');
        cdiv.className     = 'clear';
        my_div.appendChild(cdiv);
        
        // insert it in the document
        $('search_results').appendChild(my_div);
	}
    $('search_results').show();
}

function setSboxCoords(ev) {
	var l    = $('searchbox').viewportOffset().left;
    var winWidth = document.viewport.getWidth();

    if (winWidth-l < 500) {
        l = winWidth - 550;
    } else {
        l = l - 50;
    }

    //l = l - winWidth;
	$('search_results').style.left = l + 'px';
}

function clearSBoxCB() {
    $('searchbox').value = '';
    $('sboxttip').hide();
    $('search_results').hide();    
    $('imgSboxRight').src = '/searchbox/sboxright.png';
    $('searchbox').focus();
    $('imgSboxRight').style.cursor = 'default';
}

function startup() {
	$('sboxttip').hide();
	$('sboxttip').innerHTML = '<img src="/searchbox/ttipbg.png">';
/* 	$('searchbox').focus(); */
	$('searchbox').observe('keyup', this.onKeyPress);
    $('searchbox').observe('blur', this.onBlurCB);
    $('searchbox').observe('focus', this.onFocusCB);


	document.observe('keyup', this.docKeyPress);

    Event.observe(window, 'resize', this.setSboxCoords.bind(this));
    setSboxCoords();
}
	

