﻿/**
 * Контрол для показа списка городов на главной странице
 * (Использует паттерн MS Ajax Component. Будет доступен через $find)
 */
function CitiesControl()
{
	//Стандартный интерфейс для компонента
	CitiesControl.initializeBase(this);
	//ID элемента, в котором находится данный контрол
	this.containerElementID = null;
	/**
	 * Cookie, хранящий информацию о выбранном городе
	 */
	this.cookieName = null;
	/**
	 * ID comboBox-a, в котором находится список городов 
	 */
	this.comboCitiesID = null;
	/**
	 * Список городов, которые отображаем (с дополнительной информацией)
	 */
	this.citiesList = null;
	/**
	 * Это кол-во часов нужно прибавить к локальному времени
	 */
	this.localTimeHourOffset = 0;
};
CitiesControl.prototype =
{
    /**
    * Вызывается автоматически после регистрации всех свойств
    */
    initialize: function()
    {
        var that = this;
        var comboCities = $("#" + this.comboCitiesID);
        comboCities.change(function() { that.comboCitiesValueChanged(this); });
        var selectedCity = this.citiesList[comboCities.get(0).selectedIndex];
        //Нужно отрисовать данные по городу только если они есть
        if (typeof (selectedCity) != "undefined")
        {
            this.renderCityTemperature(selectedCity);
            //Время
            this.updateLocalTimeHourOffset(selectedCity);
            this.renderTime();
            this.renderDate();
            window.setInterval(function() { that.renderTime(); }, 1000);
            window.setInterval(function() { that.renderDate(); }, 60 * 1000);
        }
    },
    /**
    * Общий обработчик изменения города в combobox-е
    * @param {Object} comboBox
    */
    comboCitiesValueChanged: function(comboBox)
    {
        var selectedIndex = comboBox.selectedIndex;
        if (selectedIndex >= 0)
        {
            var selectedValue = comboBox[selectedIndex].value;
            this.saveValueToCookie(selectedValue);
            //Города идут в том же порядке на сервере и на клиенте
            var selectedCity = this.citiesList[selectedIndex];
            this.renderCityTemperature(selectedCity);
            this.updateLocalTimeHourOffset(selectedCity);
            this.renderTime();
            this.renderDate();
        }
    },
    saveValueToCookie: function(value)
    {
        //$.cookie('the_cookie', 'the_value', { expires: 7, path: '/', domain: 'jquery.com', secure: true });
        $.cookie(this.cookieName, value, { expires: 30 });
    },
    renderCityTemperature: function(selectedCity)
    {
        var container = $("#" + this.containerElementID);
        if (selectedCity.Temperature)
        {
            var value = selectedCity.Temperature.toFixed(0);
            var stringValue = value > 0 ? "+" + value : value.toString();
            $("#tempSpan", container).text(stringValue);
        }
        else
        {
            $("#tempSpan", container).text("-");
        }
    },
    /**
    * Обновляет смещение времени в зависимости от города
    */
    updateLocalTimeHourOffset: function(selectedCity)
    {
        var now = new Date();
        this.localTimeHourOffset = selectedCity.UTCOffset + now.getTimezoneOffset() / 60;
    },
    /**
    * отображает время (должен вызываться раз в секунду)
    */
    renderTime: function()
    {
        var now = new Date();
        now.setHours(now.getHours() + this.localTimeHourOffset);
        if (now.getSeconds() % 2 == 0)
            $("#timeSpan").html(now.format("HH:mm"));
        else
            $("#timeSpan").html(now.format("HH mm"));
    },
    /**
    * Отрисовывает дату в нужном формате
    */
    renderDate: function()
    {
        var now = new Date();
        now.setHours(now.getHours() + this.localTimeHourOffset);
        var dayOfWeek = this.getDayOfWeekName(now.getDay());
        var month = this.getMonthName(now.getMonth());

        $("#dateSpan").html(now.getDate() + " " + month + " " + now.getFullYear() + "г., <br />" + dayOfWeek);
    },
    /**
    * Выдает название дня недели по его номеру (от 1 до 7)
    * @param {Object} intdayNumber
    */
    getDayOfWeekName: function(dayNumber)
    {
        switch (dayNumber)
        {
            case 1: return "понедельник";
            case 2: return "вторник";
            case 3: return "среда";
            case 4: return "четверг";
            case 5: return "пятница";
            case 6: return "суббота";
            case 0: return "воскресенье";
        }
    },
    /**
    * Выдает название месяца
    * @param {Object} monthNumber
    */
    getMonthName: function(monthNumber)
    {
        switch (monthNumber)
        {
            case 0: return "января";
            case 1: return "февраля";
            case 2: return "марта";
            case 3: return "апреля";
            case 4: return "мая";
            case 5: return "июня";
            case 6: return "июля";
            case 7: return "августа";
            case 8: return "сентября";
            case 9: return "октября";
            case 10: return "ноября";
            case 11: return "декабря";
        }
    },
    //Properties
    get_containerElementID: function()
    {
        return this.containerElementID;
    },
    set_containerElementID: function(value)
    {
        this.containerElementID = value;
    },
    get_cookieName: function()
    {
        return this.cookieName;
    },
    set_cookieName: function(value)
    {
        this.cookieName = value;
    },
    get_comboCitiesID: function()
    {
        return this.comboCitiesID;
    },
    set_comboCitiesID: function(value)
    {
        this.comboCitiesID = value;
    },
    get_citiesList: function()
    {
        return this.citiesList;
    },
    set_citiesList: function(value)
    {
        this.citiesList = value;
    }
    //End of Properties
};

// JSON object that describes all properties, events, and methods of this component that should
// be addressable through the Sys.TypeDescriptor methods, and addressable via xml-script.
CitiesControl.descriptor = {
properties: [
	{ name: 'containerElementID', type: String },
	{ name: 'cookieName', type: String },
	{ name: 'comboCitiesID', type: String },
	{ name: 'citiesList', type: Object }
]
};
CitiesControl.registerClass('CitiesControl', Sys.Component);

// Since this script is not loaded by System.Web.Handlers.ScriptResourceHandler
// invoke Sys.Application.notifyScriptLoaded to notify ScriptManager 
// that this is the end of the script.
if (typeof(Sys) !== 'undefined') Sys.Application.notifyScriptLoaded();

