var AR_yesterday = function () {
    var d = new Date((new Date()) - 86400000);
    return new Date(
        d.getFullYear()
        ,d.getMonth()
        ,d.getDate()
    );
}(); // executed immediately

function AR_setDate(selectNamePrefix, dateObj) {
    $('#' + selectNamePrefix + '_y').formVal(dateObj.getFullYear());
    $('#' + selectNamePrefix + '_m').formVal(dateObj.getMonth() + 1);
    $('#' + selectNamePrefix + '_d').formVal(dateObj.getDate());
}

function AR_getDate(selectNamePrefix) {
    return new Date(
        $('#' + selectNamePrefix + '_y').formVal()
        ,$('#' + selectNamePrefix + '_m').formVal()-1
        ,$('#' + selectNamePrefix + '_d').formVal()
    );
}

function AR_formToString() {
    var loc = '', tol = '';
    $('#thresholdReportForm input:checked').each(function () {
        if (this.id.indexOf('loc_') == 0) {
            loc = this.id.split('_')[1];
        } else if (this.id.indexOf('tol_') == 0) {
            tol = this.id.split('_')[1];
        } 
    });
    return 'loc=' + loc + '&tol=' + tol;
}

function AR_stringToForm(str) {
    var m;
    if (m = str.match(/\bloc=(\d+)/)) {
        $('#loc_' + m[1]).attr({checked: true});
    }
    if (m = str.match(/\btol=(\d+)/)) {
        $('#tol_' + m[1]).attr({checked: true});
    }
}

$(function () {
    // set ids of radios
    $('#set_Locations input').each(function () {
        this.id = 'loc_' + this.value;
    });
    $('#set_Tolerance input').each(function () {
        this.id = 'tol_' + this.value;
    });
    
    // submit handler
    $('#thresholdReportForm').submit(function (){
        // hide errors in case user returns via 'back'
        $('em.error').remove();
        if (AR_getDate('sprayDate') > AR_yesterday) {
            AR_setDate('sprayDate', AR_yesterday);
            alert('The spray must be yesterday or earier. The date has been'
                + ' changed to yestersday.');
            return false;
        }
        $.cookie('arSettings', AR_formToString(), {
            path: '/tools/disease_control/alter_rater/'
            ,expires: 365 // days
        });
        return true;
    });
    // restore settings from cookie
    var str = $.cookie('arSettings');
    str && AR_stringToForm(str);
    
    // disable
    $('#thresholdReportForm').fadeTo("slow", 0.33);
    $('#submitButtons input').attr('disabled', true);
});