﻿$(function(){
    if($('#searchKeyword').autocomplete){
        //自动提示
        $.getJSON('/ajax/SearchSuggest.aspx', function(json){
            if($.isArray(json)) {
                $('#searchKeyword').autocomplete(json, {
                    max:10,
                    minChars:0,
                    width:455,
                    scrollHeight:300,
                    autoFill:false,
                    matchContains:true,
                    delay:100,
                    selectFirst:false,
                    formatItem:function(item, i, max){
                        if(item.infoCount){
                            return item.name + ' <i>约有' + item.infoCount + '条信息<i>';
                        }
                        else{
                            return item.name;
                        }
                    },
                    formatMatch:function(item, i, max){
                        return item.name;
                    },
                    formatResult:function(item){
                        return item.name;
                    }
                }).result(function(event, item){
                    if(item && item.pageUrl){
                        location.href = item.pageUrl;
                    }
                });
            }
        });
    }
    
    $('#searchKeyword').keyup(function(event){
        if(event.keyCode == 13){
            setTimeout(search, 100);
            return false;
        }
    });

    $('#searchBtn').click(function(){
        search();
    });

    function search(){
        var keyword = $.trim($('#searchKeyword').val());
        if(keyword.length == 0){
            return;
        }
        
        var infoIdReg = /^\d{20}$/;
        if(infoIdReg.test(keyword)){
            location.href = '/' + keyword + '.html';
            return;
        }
        else{
            location.href = '/s/index.aspx?' + $.param({ "key":keyword });
        }
    }
});