// -*- mode: javascript; coding: utf-8 -*-
//
// Copyright 2011 Andrej A Antonov <polymorphm@gmail.com>.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with this program.  If not, see <http://www.gnu.org/licenses/>.

(function ($) {
    'use strict'
    
    var GET_TIME_URL = '/get-time.php'
    var SERVER_TIME_DELTA = 0
    
    function get_browser_time () {
        var date_obj = new Date()
        var time = date_obj.getTime() / 1000.0
        
        return time
    }
    
    function get_server_time (callback) {
        $.post(GET_TIME_URL, {}, (function (data) {
            if (!data.errors) {
                var time = data.time + SERVER_TIME_DELTA
                
                callback(time)
            }
        }))
    }
    
    function format_day (num) {
        var table = {
            0: 'Воскресенье',
            1: 'Понедельник',
            2: 'Вторник',
            3: 'Среда',
            4: 'Четверг',
            5: 'Пятница',
            6: 'Суббота',
        }
        
        return table[num]
    }
    
    function format_month (num) {
        var table = {
            0: 'Января',
            1: 'Февраля',
            2: 'Марта',
            3: 'Апреля',
            4: 'Мая',
            5: 'Июня',
            6: 'Июля',
            7: 'Августа',
            8: 'Сентября',
            9: 'Октября',
            10: 'Ноября',
            11: 'Декабря',
        }
        
        return table[num]
    }
    
    function format_num (num, size) {
        var num_str = new String(num)
        
        while (num_str.length < size) {
            num_str = '0' + num_str
        }
        
        return num_str
    }
    
    function MoscowTime () {}
    
    function new_moscow_time(root_elem) {
        var moscow_time = new MoscowTime
        moscow_time.init(root_elem)
        return moscow_time
    }
    
    MoscowTime.prototype._ROOT_TEMPLATE =
        '<div>' +
            '<p style="margin-top: 0">В Москве:<br /><span class="ClockStub"></span></p>' +
            '<div class="LightNightStub"></div>' +
        '</div>'
    MoscowTime.prototype._LIGHT_TEMPLATE = ''
    MoscowTime.prototype._NIGHT_TEMPLATE =
        '<div>' +
            '<p>' +
                '<a class="NewMiniWindowLink" href="/cgi-bin/static-html/feedback">' +
                    '<img src="/img/moscow-time-night--w180.jpg" alt="(Ночь)" style="border: 1px solid white" />' +
                '</a>' +
            '</p>' +
            '<p>Вы можете <a class="NewMiniWindowLink" href="/cgi-bin/static-html/feedback">ОСТАВИТЬ СООБЩЕНИЕ</a> '+
                    'и мы свяжемся с Вами в ближайшее рабочее время. Спасибо!</p>' +
        '</div>'
    MoscowTime.prototype._LOCALE_TIME_DELTA = 4*60*60
    MoscowTime.prototype._TIMEOUT_DELAY = 500
    
    MoscowTime.prototype.init = function (root_elem) {
        this._clock_elem = $('<span>...</span>').css({
            font: '1.0em monospace',
        })
        this._light_elem = $(this._LIGHT_TEMPLATE)
        this._night_elem = $(this._NIGHT_TEMPLATE)
        this._light_night_elem = $('<div>...</div>')
        
        var new_root_elem = $(this._ROOT_TEMPLATE)
        new_root_elem.find('.ClockStub').replaceWith(this._clock_elem)
        new_root_elem.find('.LightNightStub').replaceWith(this._light_night_elem)
        root_elem.replaceWith(new_root_elem)
        this._root_elem = root_elem
        
        this._active = false
    }
    
    MoscowTime.prototype._get_now = function () {
        var browser_time = get_browser_time()
        var time = browser_time + this._time_delta
        var locale_time = time + this._LOCALE_TIME_DELTA
        var date_obj = new Date(locale_time * 1000.0)
        
        return {
            day: date_obj.getUTCDay(),
            date: date_obj.getUTCDate(),
            month: date_obj.getUTCMonth(),
            year: date_obj.getUTCFullYear(),
            hours: date_obj.getUTCHours(),
            minutes: date_obj.getUTCMinutes(),
            seconds: date_obj.getUTCSeconds(),
        }
    }
    
    MoscowTime.prototype._is_light = function (now) {
        if (now.day >= 1 && now.day < 6) {
            // с Понедельника до Субботы
            
            if (now.hours >= 11 && now.hours < 20) {
                // с 11 до 20
                
                return true
            }
        } else if (now.day == 6) {
            // в Субботу
            
            if (now.hours >= 12 && now.hours < 18) {
                // с 12 до 18
                
                return true
            }
        }
        
        return false
    }
    
    MoscowTime.prototype._update = function (now) {
        var time_str =
                format_day(now.day) + ', ' +
                now.date + ' ' +
                format_month(now.month) + ' ' +
                now.year + ' ' +
                format_num(now.hours, 2) + ':' +
                format_num(now.minutes, 2) + ':' +
                format_num(now.seconds, 2)
        
        this._clock_elem.text(time_str)
        
        if (this._is_light(now)) {
            if (this._light_night_elem != this._light_elem) {
                this._light_night_elem.replaceWith(this._light_elem)
                this._light_night_elem = this._light_elem
            }
        } else {
            if (this._light_night_elem != this._night_elem) {
                this._light_night_elem.replaceWith(this._night_elem)
                this._light_night_elem = this._night_elem
            }
        }
    }
    
    MoscowTime.prototype._timeout = function () {
        if (this._active) {
            var now = this._get_now()
            this._update(now)
            setTimeout($.proxy(this._timeout, this), this._TIMEOUT_DELAY)
        }
    }
    
    MoscowTime.prototype.start = function (server_time) {
        this._active = true
        
        var browser_time = get_browser_time()
        this._time_delta = server_time - browser_time
        
        var now = this._get_now()
        this._update(now)
        setTimeout($.proxy(this._timeout, this), this._TIMEOUT_DELAY)
    }
    
    MoscowTime.prototype.stop = function () {
        this._active = false
    }
    
    $(function () {
        var moscow_time = new_moscow_time($(".MoscowTimeObject"))
        
        get_server_time(function (time) {
            moscow_time.start(time)
        })
    })
})(jQuery)

