

var Clock = { hours: 0, minutes: 0, seconds: 0, date: 0, month: 0, year: 0 }

var Months = { 1:'Jan', 2:'Feb', 3:'Mar', 4:'Apr', 5:'May', 6:'Jun', 7:'Jul', 8:'Aug', 9:'Sep', 10:'Oct', 11:'Nov', 12:'Dec' };
var Days = { 1:"Mon", 2:"Tue", 3:"Wed", 4:"Thu", 5:"Fri", 6:'Sat', 7:"Sun" };

var ClockTickTimerId = null;
var ClockBlinkTimerId = null;
var ClockTuneTimerID = null;

var UTCTimeDiff = null;
var OptTimeDiff = null;

var hours = new Array();
var chart = null;


window.onload = function()
{
    init_clock();
    chart = document.getElementById( 'chart' );
};


function init_clock()
{
    clock_set( false );
}


/* ===[ autonomous clock ]=================================================== */


function clock_set()
{
    var utd = get_cookie( 'utc_time_diff' );
    var otd = get_cookie( 'opt_time_diff' );

    if( utd == null )
    {
        var now = new Date();
        server_time_diff( now.getFullYear(), now.getMonth() + 1, now.getDate(),
                          now.getHours(), now.getMinutes(), now.getSeconds() );
    }
    else
    {
        UTCTimeDiff = parseInt( utd );
    }

    if( otd != null )
    {
        OptTimeDiff = parseInt( otd );
        var now_tmp = new Date();
        var now = new Date( now_tmp.getYear(),
                            now_tmp.getMonth(),
                            now_tmp.getDate(),
                            now_tmp.getHours(),
                            now_tmp.getMinutes() + OptTimeDiff,
                            now_tmp.getSeconds() );
    } else {
        var now = new Date();
        OptTimeDiff = 0;
        set_cookie( 'opt_time_diff', OptTimeDiff );
    }

    var d = { hours:   now.getHours(),
              minutes: now.getMinutes(),
              seconds: now.getSeconds(),
              date:    now.getDate(),
              month:   now.getMonth() + 1,
              year:    now.getFullYear()
            }

    ClockTickTimerId = setInterval( 'clock_tick()', 1000 );
    ClockBlinkTimerId = setInterval( 'clock_blink()', 500 );

    Clock.hours = d.hours;
    Clock.minutes = d.minutes;
    Clock.seconds = d.seconds;

    Clock.date = d.date;
    Clock.month = d.month;
    Clock.year = d.year;

    clock_refresh( Clock.date, Clock.month, Clock.hours, Clock.minutes );

    chart = document.getElementById( 'chart' );
    if( chart ) init_chart();
}


function clock_tick()
{
    Clock.seconds = Clock.seconds + 1;
    if( Clock.seconds > 59 ) {
        Clock.seconds = 0;
        Clock.minutes = Clock.minutes + 1;
    }
    if( Clock.minutes > 59 ) {
        Clock.minutes = 0;
        Clock.hours = Clock.hours + 1;
    }
    if( Clock.hours > 23 ) {
        Clock.hours = 0;
        Clock.date = Clock.date + 1;
    }
    if( Clock.date > days_in_month( Clock.month, Clock.year ) ) {
        Clock.date = 1;
        Clock.month = Clock.month + 1;
    }
    if( Clock.month > 12 ) {
        Clock.month = 1;
        Clock.year = Clock.year + 1;
    }

    clock_refresh( Clock.date, Clock.month, Clock.hours, Clock.minutes );
}


function clock_refresh( date, month, hour, mins )
{
    set_innerHTML( 'current-date-value', date + '<span>' + Months[ month ] + '</span>' );
    set_innerHTML( 'current-hour-value', leading_zero( hour ) );
    set_innerHTML( 'current-mins-value', leading_zero( mins ) );
}


function clock_blink()
{
    e = document.getElementById( 'time-separator' );
    if( e ) { e.className = ( e.className == '' ) ? 'hidden' : ''; }
}


function clock_tune( what, offset )
{
    if( ClockTuneTimerID ) clearTimeout( ClockTuneTimerID );

    switch( what )
    {
        case 'date':
            Clock.date = Clock.date + offset;
            OptTimeDiff += 24 * 60 * offset;
            break;
        case 'hours':
            Clock.hours = Clock.hours + offset;
            OptTimeDiff += 60 * offset;
            break;
        case 'minutes':
            Clock.minutes = Clock.minutes + offset;
            OptTimeDiff += offset;
            break;
    }

    if( Clock.minutes < 0 ) { Clock.minutes = 59; Clock.hours = Clock.hours - 1; }
    if( Clock.minutes > 59 ) { Clock.minutes = 0; Clock.hours = Clock.hours + 1; }
    if( Clock.hours < 0 ) { Clock.hours = 23; Clock.date = Clock.date - 1; }
    if( Clock.hours > 23 ) { Clock.hours = 0; Clock.date = Clock.date + 1; }
    if( Clock.date < 1 ) { Clock.month = Clock.month - 1; Clock.date = days_in_month( Clock.month, Clock.year ); }
    if( Clock.date > days_in_month( Clock.month, Clock.year ) ) { Clock.date = 1; Clock.month = Clock.month + 1; }

    set_cookie( 'opt_time_diff', OptTimeDiff );
    clock_refresh( Clock.date, Clock.month, Clock.hours, Clock.minutes );
    init_chart();
}


/* ===[ chart ]============================================================== */


function init_chart( change_mode )
{
    if( !change_mode ) var change_mode = false; else var change_mode = true;

    // waiting for time initialization
    if( UTCTimeDiff == null || OptTimeDiff == null )
    {
        setTimeout( 'init_chart()', 50 );
        return;
    }

    uid = gup( 'c' );
    if( uid )
    {
        JsHttpRequest.query
        (
            'ajax_chart',
            {
                'action': 'chart_view',
                'time_diff': ( UTCTimeDiff + OptTimeDiff ),
                'uid': uid,
                'chmode': change_mode
            },

            function(result, errors)
            {
                document.getElementById("debug").innerHTML = errors;
                if (result) {
                    chart.innerHTML = result[ 'html' ];
                }
            },
            true  // do not disable caching
        );
    } else {
        JsHttpRequest.query
        (
            'ajax_chart',
            {
                'action': 'chart_edit',
                'time_diff': ( UTCTimeDiff + OptTimeDiff ),
                'chmode': change_mode
            },

            function(result, errors)
            {
                document.getElementById("debug").innerHTML = errors;
                if (result) {
                    chart.innerHTML = result[ 'html' ];
                    for( var id in hours ) {
                        cell = document.getElementById( id );
                        if( !cell ) continue;
                        cell.className = hours[id];
                    }
                }
            },
            true  // do not disable caching
        );
    }

}


function chart_cell_click( year, month, date, hour )
{
    id = 'cell_' + year + '_' + month + '_' + date + '_' + hour;
    cell = document.getElementById( id );
    if( !cell ) return false;

    switch( cell.className )
    {
        case 'unavail':
            cell.className = 'avail';
            break;
        case 'avail':
            cell.className = 'maybe';
            break;
        case 'maybe':
            cell.className = 'busy';
            break;
        case 'busy':
            cell.className = 'unavail';
            break;
    }

    hours[id] = cell.className;
    if( hours[id] == 'unavail' ) delete hours[id];
}

function chart_save()
{
    f = document.getElementById( 'save_hours_form' );
    if( !f ) return;

    f.innerHTML = '';
    f.innerHTML += '<input type="hidden" name="time_diff" value="' + ( UTCTimeDiff + OptTimeDiff ) + '">';
    for( var id in hours ) {
        f.innerHTML += '<input type="hidden" name="' + id + '" value="' + hours[id] + '">';
    }

    document.forms['save_hours'].submit();
}


/* ===[ common ]============================================================= */


function set_innerHTML( id, s )
{
    e = document.getElementById( id );
    if( e ) e.innerHTML = s;
}


function leading_zero( num )
{
	if( num < 10 ) num = '0' + num;
	return num;
}


function days_in_month( month, year )
{
    month = month - 1;  // transfer month to [0,1,2,3...]
	return ( 32 - new Date( year, month, 32 ).getDate() );
}


function gup( name )
{
    name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
    var regexS = "[\\?&]"+name+"=([^&#]*)";
    var regex = new RegExp( regexS );
    var results = regex.exec( window.location.href );
    if( results == null )
        return "";
    else
        return results[1];
}


/*------------------------------------*/
/* cookies */


function set_cookie( cookieName, cookieString )
{
   var expires = "; expires=Monday, 31-Dec-12 23:59:59 GMT";
   document.cookie = cookieName + "=" + cookieString + expires;
}


function get_cookie( cookieName )
{
    var cookieString = document.cookie;
    var startLoc = cookieString.indexOf(cookieName);
    if (startLoc == -1)  return null;
    var sepLoc = cookieString.indexOf("=", startLoc);
    var endLoc = cookieString.indexOf(";", startLoc);
    if (endLoc == -1)  endLoc = cookieString.length;
    return(cookieString.substring(sepLoc+1, endLoc));
}


function server_time_diff( year, month, date, hours, minutes, seconds )
{
    JsHttpRequest.query
    (
        'ajax_time',
        { 'action': 'time_diff',
          'year': year, 'month': month, 'date': date,
          'hours': hours, 'minutes': minutes, 'seconds': seconds },
        function(result, errors) {
            document.getElementById("debug").innerHTML = errors;
            if (result) {
                UTCTimeDiff = parseInt( result[ 'time_diff' ] );
// alert( result['dump'] );
// alert( UTCTimeDiff );
                set_cookie( 'utc_time_diff', UTCTimeDiff );
            }
        },
        true  // do not disable caching
    );
}

