function get_form_fields(form) {
    var ii = {};
    var inputs = form.getElementsByTagName('INPUT');
    for (var j=0; j<inputs.length; j++) {
        ii[inputs[j].className] = inputs[j];
    }
    var selects = form.getElementsByTagName('SELECT');
    for (var j=0; j<selects.length; j++) {
        ii[selects[j].className] = selects[j];
    }
    return ii;
}


function min_length(i, len) {
  var s = "" + i;
  while (s.length < len) {
    s = "0" + s;
  }
  return s;
}


function submit_calendar(event) {
    var form = (event.target) ? event.target : window.event.srcElement;
    if (form.className == 'calendar') {
        var ii = get_form_fields(form);
        if (ii['datefrom'] && ii['fromday'] && ii['frommon'] && ii['fromyear']) {
            ii['datefrom'].value = ii['fromyear'].value + '/' +
                                   min_length(ii['frommon'].value, 2) + '/' +
                                   min_length(ii['fromday'].value, 2);
        }
        if (ii['dateto'] && ii['today'] && ii['tomon'] && ii['toyear']) {
            ii['dateto'].value = ii['toyear'].value + '/' +
                                 min_length(ii['tomon'].value, 2) + '/' +
                                 min_length(ii['today'].value, 2);
        } else if (ii['datefrom']) {
            ii['dateto'].value = ii['datefrom'].value;
        }
    }
    return true;
}

function init_calendar() {
    var now = new Date();
    var forms = document.getElementsByTagName('FORM');
    for (var i=0; i<forms.length; i++) {
        if (forms[i].className == 'calendar') {
            addEvent(forms[i], 'submit', submit_calendar, false);
            var ii = get_form_fields(forms[i]);
            if (ii['fromday'] && ii['frommon'] && ii['fromyear']) {
                ii['fromyear'].value = now.getFullYear();
                ii['frommon'].value = now.getMonth() + 1;
                ii['fromday'].value = now.getDate();
            }
            if (ii['today'] && ii['tomon'] && ii['toyear']) {
                ii['toyear'].value = now.getFullYear();
                ii['tomon'].value = now.getMonth() + 1;
                ii['today'].value = now.getDate();
            }
        }
    }
}

addEvent(window, 'load', init_calendar, false);