var processing = false;
var processing_val = '';
var tout_hideresults = null;

function quickSearch(elem, event, url)
{
	var loading = '<div style="text-align:center; padding:15px;"><img src="/images/loading.gif" width="32" height="32" /></div>';

        //Escape key, clears results and slides
        if(event && event.keyCode == 27) {
            $('#findpeople').html("");
            $('#results').slideUp();
            $(elem).val('');
            $(elem).blur();
            return;
        }

        if ($(elem).val() != '' && $(elem).val() != $(elem).attr('title') && processing != true) {

           if ($(elem).val().length >= 3) {
               $('#findpeople').html(loading);
               $('#results').slideDown();
               processing = true;
               processing_val = $(elem).val();
               $.get(url, {
                   s:processing_val
               }, function(data) {
                   $('#findpeople').html(data);
                   $('#results').slideDown();
                   processing = false;
                   if ($('#search-holder .search .field').val() != processing_val) {
                       $('#search-holder .search .field').keyup();
                   }
               });
           }
        } else if (processing != true) {
            $('#findpeople').html("");
            $('#results').slideUp();
        }

}
$(function() {
    // search
    $('#top-search').keyup(function (event) {
        quickSearch(this, event, '/public/search/ajax-find-people');
    });

    $('#home-search').keyup(function (event) {
        quickSearch(this, event, '/public/search/ajax-find-people');
    });

    // results
    $('#results .row').live('mouseover', function () {
        $(this).addClass('row-h');
    });

    $('#results .row').live('mouseout', function () {
        $(this).removeClass('row-h');
    });

    $('#results .row .connect').live('mousedown', function() {
        location.href = $(this).attr('href');
        $('.blink').blur();
    });

    // focus/blur
    $('#search-holder .blink')
    .focus(function(){
        if( $(this).val() == $(this).attr('title') ) {
            $(this).val('');
        }
    })
    .blur(function(){
        tout_hideresults = setTimeout(function() {
            $(this).val( $(this).attr('title') );
            $('#results').slideUp();
        }, 400);
    });
 
   $('#search-holder .search .button').focus(function(){
        if( tout_hideresults ) {
            clearTimeout(tout_hideresults);
            $('.search .blink').focus();
        }
        tout_hideresults = null;
    });
});

