$(function() {
		  
    InitStructure();
    ProcessQuerySearch();
    $('#query').bind('focus', ResetQueryField)
});

RegExp.escape = function(text) {
    if (!arguments.callee.sRE) {
        var specials = [
            '+', '-', '&&', '|', '!', '(', ')', '{', '}', '[', ']', '^', '~', '*', '?', ':', '<', '>', '\''
        ];
        arguments.callee.sRE = new RegExp(
            '(\\' + specials.join('|\\') + ')', 'g'
        );
    }
    return text.replace(arguments.callee.sRE, '\\$1');
}

function ResetQueryField() {
    if ($(this).attr('value') == 'Find...') {
        $(this).attr('value','');
    }
}

function InitStructure() {
    $('.search-content').html(SearchHeader() + '<div id="search-info"></div><div class="pager"></div><div id="search-results"></div><div class="pager"></div>');
    return false;
}

function DateFormat(str, format) {
    var newDate = new Date(('' + str).replace(/-/g, "/").replace(/[TZ]/g, " ").replace(/\.\d+/,''));
    return newDate.toString();
}

function urldecode(str) {
	
    var histogram = {}, histogram_r = {}, code = 0, str_tmp = [];
    var ret = str.toString();
    var replacer = function(search, replace, str) {
        var tmp_arr = [];
        tmp_arr = str.split(search);
        return tmp_arr.join(replace);
    };

	 //var histo1 = histogram['!'];
	 
	//if(histo1 != undefined){
	
       histogram['!']   = '%21';
       histogram['%20'] = '+';
	//}
    for (replace in histogram) {
        search = histogram[replace];
        ret = replacer(search, replace, ret);
    }
    ret = decodeURIComponent(ret);
    return ret;
}

function ProcessQuerySearch() {
	
    var q = $.jqURL.get('q');
    if (typeof(q) != 'undefined') {
        $('#query').attr('value', urldecode(q));
        SearchSubmit(null);
    }
    return false;
}

function SearchHeader() {
    var searchHeader = '';
    searchHeader =  '<div id="search-header" class="clearfix">';
    searchHeader +=  '<div id="search_adv" class="clearfix"></div>';
    searchHeader +=  '   <h1>Search for:</h1>';
    searchHeader +=  '   <div id="search-form-container">';
    searchHeader += '       ' + SearchForm();
    searchHeader +=  '   </div>';
    searchHeader +=  '</div>';
    return searchHeader;
}

function SearchForm() {
    var searchForm = '';
    searchForm += '<form id="search-form" method="post" onsubmit="SearchSubmit(null); return false;">';
    searchForm += '    <input type="text" name="query" id="query" value="Find..." />';
    searchForm += '    <input type="submit" name="submit" id="submit" value="Search" />';
    searchForm += '</form>';
    return searchForm;
}

function SearchResults(results) {
    var content = '';
    if (results.response.docs.length > 0) {
        var start = results.response.start + 1;
        content += '<ol start="' + start + '">';
        for (var i = 0; i < results.response.docs.length; i++) {
            var fulldate = DateFormat(results.response.docs[i].updated);
            fulldate = fulldate.replace("00:00:00 GMT-0600 (CST)", "");
            content += '<li>';
            content += '    <a href="' + results.response.docs[i].link + '">' + results.response.docs[i].title + '</a>';
            content += '    <p class="summary">' + SanitizeString(results.response.docs[i].summary) + '</p>';
            content += '    <p class="url">' + results.response.docs[i].link + '</p>';
            //content += '    <p class="timestamp">' + DateFormat(results.response.docs[i].updated) + '</p>';
            content += '    <p class="timestamp">' + fulldate + '</p>';
            content += '</li>';
        }
        content += '</ul>';
        if (results.response.numFound < 20) {
            var endCount = results.response.numFound;
            var next_20 = '';
        }
        else {
            var endCount = start + 19;
            var next_20 = '<a href="#" onclick="SearchSubmit(null, ' + endCount + '); return false;" class="next">Next 20 &gt;</a>';
        }
        $('#search-info').html('Results ' + start + '-' + endCount + ' of ' + results.response.numFound);
        
        if (start == 1) {
            var first_20 = '';
            var previous_20 = '';
        } else {
            var previous_num = start - 21;
            var first_20 = '<a href="#" onclick="SearchSubmit(null, 0); return false;" class="previous">&lt; First 20</a>';
            var previous_20 = '<a href="#" onclick="SearchSubmit(null, ' + previous_num + '); return false;" class="previous">&lt; Previous 20</a>';
        }
        $.each($('.pager'), function() {$(this).html('' +
            '<div class="page-links clearfix">' +
            '    ' + first_20 +
            '    ' + previous_20 +
            '    ' + next_20 +
            '</div>')});
    }
    else {
        content = '<div class="idle">Your search returned no results.</div>'
        $('#search-info').html('');
    }
    return content;
}

function SearchSubmit(q, s) {
    if (q == null) {
        q = $('#query').attr('value');
    }
    if (s == null) {
        s = 0;
    }
    if (q != '' &&  q != 'Find...') {
        q = RegExp.escape(q);
        $('#search-results').html('<div class="idle">Loading...</div>');
        $.ajax({
            type: "GET",
            url: "/!/searching/",
            dataType: 'json',
            data: {
                'q': '(content:(' + q + ') OR title:(' + q + ')) AND siteid:' + site_id + '',
                //'q': '(content:(' + q + ') OR title:(' + q + ')) AND siteid:' + site_id + ' AND (content_type:(Story) OR content_type:(ContentSet))',
                'rows': 20,
                'start': s
            },
            success: function(msg) {$('#search-results').html(SearchResults(msg))},
            error: function(msg) {$('#search-results').html(SearchResults(msg))}
        });
    }
    else {
        $('#search-results').html('<div class="idle">Enter a search term.</div>');
        $('#search-info').html('');
    }
    return false;
}

function SanitizeString(str) {
    var str = str + '';
    return str.replace(/<p><\/p>/,'').replace(/<p>&nbsp;<\/p>/ig,'').replace(/&lt;\/?[a-zA-Z] ?.*?&gt;/ig,'').substring(0, 400).replace(/\w+$/, '');
	//replace(/\<\/?[^>]*?>/ig,'').
}
