var currentDate, currentYear;

function weekOfYear(d)
{
    var year = d.getYear()
    if (year < 1900) {
        year += 1900;
    }
    var firstday = new Date(year, 0, 1);
    var firstwday = 8 - firstday.getDay();
    if (firstwday == 8) {
        firstwday = 1;
    } else if (firstwday > 4) {
        firstwday -= 7;
    }

    var dayofyear = (d - firstday.getTime() + 86400000) / 86400000;
    if (dayofyear < firstwday) {
        return weekOfYear(new Date(year - 1, 12, 31));
    } else {
        return Math.floor((dayofyear - firstwday) / 7) + 1;
    }
}

function openCalendar(imgId, target)
{
    var d = new Date(document.getElementById(target + '[year]').value,
                     document.getElementById(target + '[month]').value - 1,
                     document.getElementById(target + '[day]').value);

    if (target == 'end') {
        var e = new Date(document.getElementById('start[year]').value,
                         document.getElementById('start[month]').value - 1,
                         document.getElementById('start[day]').value);
    } else {
        var e = new Date(2002, 1, 1);
    }    
    openGoto(d.getTime(), imgId, target, e.getTime());
}

function openGoto(timestamp, imgId, target, earliestTimestamp)
{
    var row, cell, img, link, days;

    earliestTimestamp = new Date(earliestTimestamp);
    var d = new Date(timestamp);
    currentDate = d;
    var month = d.getMonth();
    var year = d.getYear();
    if (year < 1900) {
        year += 1900;
    }
    currentYear = year;
    var firstOfMonth = new Date(year, month, 1);
    var diff = firstOfMonth.getDay() - 1;
    if (diff == -1) {
        diff = 6;
    }
    switch (month) {
        case 3:
        case 5:
        case 8:
        case 10:
            days = 30;
            break;
        case 1:
            if (year % 4 == 0 && (year % 100 != 0 || year % 400 == 0)) {
                days = 29;
            } else {
                days = 28;
            }
            break;
        default:
            days = 31;
            break;
    }

    var wdays = [
        '<?php echo _("Mo") ?>',
        '<?php echo _("Tu") ?>',
        '<?php echo _("We") ?>',
        '<?php echo _("Th") ?>',
        '<?php echo _("Fr") ?>',
        '<?php echo _("Sa") ?>',
        '<?php echo _("Su") ?>'
    ];
    var months = [
        '<?php echo _("January") ?>',
        '<?php echo _("February") ?>',
        '<?php echo _("March") ?>',
        '<?php echo _("April") ?>',
        '<?php echo _("May") ?>',
        '<?php echo _("June") ?>',
        '<?php echo _("July") ?>',
        '<?php echo _("August") ?>',
        '<?php echo _("September") ?>',
        '<?php echo _("October") ?>',
        '<?php echo _("November") ?>',
        '<?php echo _("December") ?>'
    ];

    var lay = document.getElementById('goto');
    if (lay.firstChild) {
        lay.removeChild(lay.firstChild);
    }

    var table = document.createElement('TABLE');
    var tbody = document.createElement('TBODY');
    table.appendChild(tbody);
    table.cellSpacing = 1;

    // title bar
    row = document.createElement('TR');
    cell = document.createElement('TD');
    cell.colSpan = 8;
    cell.align = 'right';
    cell.className = 'header';
    link = document.createElement('A');
    link.href = '#';
    link.onclick = function() {
        document.getElementById('goto').style.visibility = 'hidden';
        return false;
    }
    link.className = 'menuitem';
    var x = document.createTextNode('x');
    link.appendChild(x);
    cell.appendChild(link);
    row.appendChild(cell);
    tbody.appendChild(row);

    // year
    row = document.createElement('TR');
    cell = document.createElement('TD');
    cell.colSpan = 8;
    cell.align = 'center';
    link = document.createElement('A');
    link.href = '#';
    link.onclick = function() {
        newDate = new Date(currentYear - 1, currentDate.getMonth(), currentDate.getDate());
        openGoto(newDate.getTime(), imgId, target, earliestTimestamp);
    }
    cell.appendChild(link);
    img = document.createElement('IMG')
    img.src = '<?php echo $GLOBALS['registry']->getParam('graphics', 'horde') ?>/nav/left.gif';
    img.align = 'middle';
    img.border = 0;
    link.appendChild(img);
    var y = document.createTextNode(year);
    cell.appendChild(y);
    link = document.createElement('A');
    link.href = '#';
    link.onclick = function() {
        newDate = new Date(currentYear + 1, currentDate.getMonth(), currentDate.getDate());
        openGoto(newDate.getTime(), imgId, target, earliestTimestamp);
    }
    cell.appendChild(link);
    img = document.createElement('IMG')
    img.src = '<?php echo $GLOBALS['registry']->getParam('graphics', 'horde') ?>/nav/right.gif';
    img.align = 'middle';
    img.border = 0;
    link.appendChild(img);
    row.appendChild(cell);
    tbody.appendChild(row);

    // month name
    row = document.createElement('TR');
    cell = document.createElement('TD');
    cell.colSpan = 8;
    cell.align = 'center';
    link = document.createElement('A');
    link.href = '#';
    link.onclick = function() {
        newDate = new Date(currentYear, currentDate.getMonth() - 1, currentDate.getDate());
        openGoto(newDate.getTime(), imgId, target, earliestTimestamp);
    }
    cell.appendChild(link);
    img = document.createElement('IMG')
    img.src = '<?php echo $GLOBALS['registry']->getParam('graphics', 'horde') ?>/nav/left.gif';
    img.align = 'middle';
    img.border = 0;
    link.appendChild(img);

    var m = document.createTextNode(months[month]);
    cell.appendChild(m);

    link = document.createElement('A');
    link.href = '#';
    link.onclick = function() {
        newDate = new Date(currentYear, currentDate.getMonth() + 1, currentDate.getDate());
        openGoto(newDate.getTime(), imgId, target, earliestTimestamp);
    }
    cell.appendChild(link);
    img = document.createElement('IMG')
    img.src = '<?php echo $GLOBALS['registry']->getParam('graphics', 'horde') ?>/nav/right.gif';
    img.align = 'middle';
    img.border = 0;
    link.appendChild(img);
    row.appendChild(cell);
    tbody.appendChild(row);

    // weekdays
    row = document.createElement('TR');
    for (var i = 0; i < 7; i++) {
        cell = document.createElement('TD');
        weekday = document.createTextNode(wdays[i]);
        cell.appendChild(weekday);
        row.appendChild(cell);
    }
    tbody.appendChild(row);

    // rows
    var week, italic;
    var count = 1;
    var today = new Date();
    var thisYear = today.getYear();
    if (thisYear < 1900) {
        thisYear += 1900;
    }
    var earliestYear = earliestTimestamp.getYear();
    if (earliestYear < 1900) {
        earliestYear += 1900;
    }
    
    var odd = true;
    for (var i = 1; i <= days; i++) {
        if (count == 1) {
            row = document.createElement('TR');
            row.align = 'right';
            if (odd) {
                row.className = 'item0';
            } else {
                row.className = 'item1';
            }
            odd = !odd;
        }
        if (i == 1) {
            for (var j = 0; j < diff; j++) {
                cell = document.createElement('TD');
                row.appendChild(cell);
                count++;
            }
        }
        cell = document.createElement('TD');
        if (thisYear == year &&
            today.getMonth() == month &&
            today.getDate() == i) {
            cell.style.border = '1px solid red';
        }
        
        if (year < earliestYear ||
                year == earliestYear && month < earliestTimestamp.getMonth() ||
                year == earliestYear && month == earliestTimestamp.getMonth() && i < earliestTimestamp.getDate()) {
            day = document.createTextNode(i);
            cell.appendChild(day);
        } else {
            link = document.createElement('A');
            cell.appendChild(link);
            
            link.href  = i;
            link.onclick = function() {
                var day = this.href;
                while (day.indexOf('/') != -1) {
                    day = day.substring(day.indexOf('/') +1);
                }

                document.getElementById(target +'[day]').value = day;
                document.getElementById(target +'[year]').value = year;
                document.getElementById(target +'[month]').value = (month + 1);
                document.getElementById('goto').style.visibility = 'hidden';

                return false;
            }    

            day = document.createTextNode(i);
            link.appendChild(day);
        }    

        row.appendChild(cell);
        if (count == 7) {
            tbody.appendChild(row);
            count = 0;
        }
        count++;
    }
    if (count > 1) {
        for (i = count; i <= 7; i++) {
            cell = document.createElement('TD');
            row.appendChild(cell);
        }
        tbody.appendChild(row);
    }

    // Try to set the position of the layer to next to the image
    // anchor.
    var el = document.getElementById(imgId);
    var p = getAbsolutePosition(el);

    lay.style.left = p.x + "px";
    lay.style.top = p.y + "px";

    // Show the layer.
    lay.appendChild(table);
    lay.style.display = 'block';
    lay.style.visibility = 'visible'; 
}

function getAbsolutePosition(el)
{
    var r = { x: el.offsetLeft, y: el.offsetTop };
    if (el.offsetParent) {
        var tmp = getAbsolutePosition(el.offsetParent);
        r.x += tmp.x;
        r.y += tmp.y;
    }
    return r;
}
