// JAVASCRIPT for JAbbr 2.0
// by Keith Jenkins
// last updated 2009-05-20


$(document).ready(function(){
    $('#main').data('orig', $('#main').html());
    $('#q').data('lastq', $('#q').val());
    $('#q').keyup(think).click(think).focus();
    $('#search').submit(function(){
        $('#thinking').html('Thinking...');
    });
    if ('#main ol') trackClicks('search');
});

timeoutID = '';
function think() {
    clearTimeout(timeoutID);
    timeoutID = setTimeout("getTitles()", 500);
}

function getTitles() {
    var lastq = $('#q').data('lastq');
    var q = $('#q').val();
    if (q==lastq) return false; // q hasn't changed
    $('#q').data('lastq', q);
    if (q.length>1) { // don't send queries unless string is longer than one character
        $('#thinking').html('Thinking...');
        $.getJSON("json", { q:q, max:20, origin:'preview' }, gotTitles);
    }
    else {
        $('#main').html('<p>Type an abbreviation to find possible matches from the Cornell University Library catalog.</p>');
    }
}

function gotTitles(d) {
    if ($('#q').val()!=d.q) return; // don't display results if q has already changed
    $('#thinking').html('');
    $('#main').html("<p>Quick search results for <span class='q'>"+d.q+"</span> : "+d.count+" titles found</p>");
    if (d.matches) {
        var ol = $("<ol></ol>");
        $.each(d.matches, function(i, m){
            var title = m.title;
            var alt = m.altTitle;
            var qurl = alt ? alt : title;
            qurl = qurl.replace(/ [:\/=] .*$/, ''); // remove 245b or stmtresp
            qurl = encodeURIComponent(qurl).replace(/'/, "%27");
            if (m.exact) title = "<b>" + title + "</b>";
            var li = "<li><a href='http://cornell.worldcat.org/search?fq=dt:ser&amp;q=ti:%22" + qurl + "%22&amp;scope=2'>" + htmlSpecialChars(title) + "</a>";
            if (alt) li += " <span class='alt'>[&#xa0;" + htmlSpecialChars(alt) + "&#xa0;]</span>";
            li += "</li>\n";
            ol.append(li);
        });
        $('#main').append(ol);
        if (d.count>d.max) {
            $('#main').append("<p><a href='?q="+encodeURIComponent(d.q)+"'>More matches...</a></p>");
        }
    }
    if (d.count<=d.max) {
        $('#main').append("<div class='tip'>Didn't find it?  Try a <a href='?q="+encodeURIComponent(d.q)+"&amp;deep=1'>deep search</a></div>");
    }
    trackClicks('preview');
}

function trackClicks(origin) {
    $('#main ol a').click(function(){
        $.post('click', { origin:origin, q:$('#q').val(), title:$(this).text() });
    });
}

function htmlSpecialChars(s) {
    if (s) return s.replace(/&/, "&amp;");
}

function htmlSpecialChars_decode(s) {
    if (s) return s.replace(/&amp;/, "&");
}

