$(document).ready(function() {
    var curDateInput;
    var curMonth;
    var numMonths = $('#dateSelector table').size();
    var selector = $('#dateSelector');
    selector.css('position', 'absolute');
    var remain_open;

    $('input.date, .iField.date input').bind('focus click', function() {
        remain_open = false;
        curDateInput = $(this);

        $('#dateSelector table').hide();
        var matchdate = $('#dateSelector a[href$=#' + curDateInput.val() + ']');
        if (matchdate.size() > 0)
            curMonth = 1*matchdate.parent().parent().parent().parent().attr('id').substring(6);
        else
            curMonth = 0;
        $('#dateSelector #month-'+curMonth).show();

        var pos = curDateInput.position();
        selector.css('left', pos.left).css('top', pos.top);
        selector.show();
    }).attr('readonly', true)

    $('input.date, .iField.date input').bind('blur', function(e) {
        if (!remain_open) {
            selector.hide();
        }
        remain_open = false;
    })

    /* This is mousedown because it happens before blur; if it was click it
     * would happen after blur, so the above binding would prevent the click
     * from happening */
    $('#dateSelector .ds_close').bind('mousedown', function() {
        curDateInput = false;
        selector.hide();
        return false;
    })

    $('#dateSelector td a').bind('mousedown', function() {
        if (curDateInput)
            curDateInput.val(this.href.substring(this.href.length-10));
        selector.hide();
        return false;
    })

    $('#dateSelector .ds_prev').bind('mousedown', function() {
        remain_open = true;
        if (curMonth == 0)
            return false;
        $('#dateSelector #month-'+curMonth).hide();
        curMonth--;
        $('#dateSelector #month-'+curMonth).show();
        return false;
    })

    $('#dateSelector .ds_next').bind('mousedown', function() {
        remain_open = true;
        if (curMonth >= numMonths-1)
            return false;
        $('#dateSelector #month-'+curMonth).hide();
        curMonth++;
        $('#dateSelector #month-'+curMonth).show();
        return false;
    })

    $('#searchFormLong #unit').bind('change', function() {
         if ($('#searchFormLong #unit').val()) {
            $('#searchFormLong').submit();
         }
    })

})
