var searchPoint, searchUrl;

$(document).ready(function(){

    searchUrl = window.location.protocol + "//" + window.location.host + window.location.pathname;
    searchUrl = searchUrl.replace(/\/?$/, '');
    searchUrl += '/search/';

    $('.selector a').click(function(){
        $('.selector a').removeClass('selected');
        $(this).addClass('selected');
        $('.filter').hide();
        $('#' + $(this).attr('id') + '_container').show();
    });

    $('#SearchKeywords').bind('keyup', function (e) {
      if (e.keyCode == 13) {
        var q = $('#SearchKeywords').val();
        if (q)
        {
            $('#SearchMapResultsKW').html('<img src="/img/loading.gif" width="16" height="16" alt="" class="loading">').load(searchUrl, { 'q': q }, function(){ initResultLinks(); });
        }
      }
    });

    $('#SearchKeywordsButton').click(function(){
        var q = $('#SearchKeywords').val();
        if (q)
        {
            $('#SearchMapResultsKW').html('<img src="/img/loading.gif" width="16" height="16" alt="" class="loading">').load(searchUrl, { 'q': q }, function(){ initResultLinks(); });
        }
    });

});

function initResultLinks()
{
    $('#SearchMapResultsKW a.clear2').click(function(){
        $('#SearchKeywords').val('');
        $('#SearchMapResultsKW').html('');
        return false;
    });

    $('#SearchMapResultsKW a.search_point').click(function(){
        if (!$('#layer_' + $(this).attr('layer_id')).attr('checked'))
        {
            $('#layer_' + $(this).attr('layer_id')).attr('checked', true);
            map.addOverlay(mapLayers['layer' + $(this).attr('layer_id')]);
        }

        if (mapLayers['layer' + $(this).attr('layer_id')])
        {
            var objId = 'geo_object_' + $(this).attr('item_id');
            var t = mapLayers['layer' + $(this).attr('layer_id')].filter(function(obj) { return obj.id == objId });
            if (t.length > 0)
            {
                t[0].openBalloon();
                map.setCenter(t[0].getBalloon().getGeoPoint(), 15);
            }
        }

        $('#SearchMapResultsKW li').removeClass('current');
        $(this).parent().addClass('current');

        return false;
    });

    if ($('#SearchMapResultsKW a.search_point').length == 1)
    {
        $('#SearchMapResultsKW a.search_point').click();
    }

    $('#SearchMapResultsKW a.search_page').click(function(){
        $('#SearchMapResultsKW').html('<img src="/img/loading.gif" width="16" height="16" alt="" class="loading">').load($(this).attr('url'), null, function(){ initResultLinks(); });
        return false;
    });

}
