﻿/**
 * Переключалка валют
 * Copyright Art. Lebedev | http://www.artlebedev.ru/
 * @requires jQuery, jQuery.cookie
 * @author vazzda
*/
var home_currencies = {
    init : function () {
        var currencies;

        this.currencies = currencies = jQuery('.home_currencies');
        this.labels_ = currencies.find('.home_currencies_labels')
                .data('labels');
        this.element_ = currencies.find('.home_currencies_content');
        this.block_ = currencies.find('.home_currencies_wrapper');
        this.loader_ = currencies.find('.home_currencies_loader');
        this.city_ = jQuery('#geolocate');

        this.city_.bind('update', jQuery.proxy(function (event, city) {
            this.onCityUpdate_(city.city_id);
        }, this));
    },

    /**
     * Выбор города
     * очищает блок, переключает лоадер, запрос к новым данным
     * @param id String Айди города
     * @private
    */
    onCityUpdate_ : function (id) {
        this.element_.find('.home_currencies_header_non_cash').unbind('click');
        this.element_.html('');
        this.loader_.show();
        var now = new Date();
        jQuery.ajax({
            url: '/currency_rates.ihtml?city=' + id + '&dt=' + now.toGMTString().replace(/:.*$/, ''),
            dataType: 'json',
            success: jQuery.proxy(function (data) {
                this.loader_.hide();
                this.updateCurrencies_(data);
            }, this)
        });
    },

    /**
     * Обновление валют по загрузке
     * @param data Object Данные о валютах
     * @private
    */
    updateCurrencies_ : function (data) {
        var cash, nonCash, element, labels;

        labels = this.labels_;
        cash = this.getCurrencies_(
                data.rates.cash, 'cash', labels.cashHeader);
        nonCash = this.getCurrencies_(
                data.rates.nonCash, 'non_cash', labels.nonCashHeader);
        element = jQuery(cash + nonCash);

        if (cash && nonCash) {
            this.hideNoneCash_(element);
        }

        this.element_.find('.home_currencies_header_non_cash').unbind('click');
        this.element_.html(element);
    },

    /**
     * Прячем вторую группу валют (если есть) под выпадалку
     * @param element jQuery Новый виртуальный элемент с валютами
     * @private
    */
    hideNoneCash_ : function (element) {
        var header, group;

        header = element.find('.home_currencies_header_non_cash');
        group = header.closest('.home_currencies_group')
            .find('.home_currencies_rates, .home_currencies_meanings')
        header.find('.home_currencies_header_content').addClass('pseudo_link');
        header.bind('click', function () {
            group.toggle();
        });
        group.hide();
    },

    /**
     * Возвращает строковое представление верстки группы валют
     * @param data Object Данные о валютах
     * @param type String Тип группы (нал, безнал)
     * @param header String Лэйбл заголовка
     * @return String Пустая строка
     * @return String Верстка валют
     * @private
    */
    getCurrencies_ : function (data, type, header) {
        var type, meanings, rates;

        if (data.length === 0) {
            return '';
        }

        type = this.getHeader_(type, header);
        meanings = this.getMeanings_();
        rates = this.getRates_(data);

        return '<div class="home_currencies_group">' +
                type + meanings + rates +
            '</div>';
    },

    /**
     * Возвращает строковое представление заголовка валют
     * @param type String Тип группы (нал, безнал)
     * @param header String Лэйбл заголовка
     * @return String Верстка
     * @private
    */
    getHeader_ : function (type, header) {
        return '<div class="home_currencies_header' +
            ' home_currencies_header_' + type + '">' +
                '<span class="home_currencies_header_content">' +
                    header +
                '</span>' +
            '</div>';
    },

    /**
     * Возвращает строковое представление верстки заголовков колонок
     * например: покупка, продажа
     * @return String Верстка
     * @private
    */
    getMeanings_ : function () {
        return '<div class="home_currencies_meanings">' +
            '<div class="section home_currencies_element' +
                    ' home_currencies_meaning_element">' +
                this.labels_.buy +
                '</div>' +
            '<div class="section home_currencies_element' +
                    ' home_currencies_meaning_element">' +
                this.labels_.sale +
            '</div>' +
        '</div>';
    },

    /**
     * Возвращает строковое представление верстки значений валют
     * @param data Object Данные о валютах
     * @return String Верстка
     * @private
    */
    getRates_ : function (data) {
        return '<div class="home_currencies_rates">' +
            jQuery.map(data, function (rate) {
                return '<div class="home_currencies_rate">' +
                    '<div class="section home_currencies_element' +
                            ' home_currencies_element_currency">' +
                        rate.currency +
                    '</div>' +
                    '<div class="section home_currencies_element">' +
                        rate.buy +
                    '</div>' +
                    '<div class="section home_currencies_element">' +
                        rate.sale +
                    '</div>' +
                '</div>'
            }).join('') +
        '</div>';
    }
}

jQuery(function () {
    home_currencies.init();
});

