$(document).ready(function()
{    
    popularOffersRender.init({'popular_offers': popular_offers, 'start_index': 4});
    
    $('#popular-offers-up').click(
        function(e) {
            e.preventDefault();
            popularOffersRender.up();
        }
    );
});

var popularOffersRender = {        
    _step: null,
    _current_index: null,
    _popular_offers: null,
    _module: null,
    _cache_img: null,
            
    init: function(params)
    {       
        if (!params) {
            throw new Exception('Params for init() is empty');
        } else if (!params['popular_offers']) {
            throw new Exception('Popular offers is empty');
        }
        
        this._step = params['step'] ? params['step'] : 4;
        
        this._popular_offers = params['popular_offers'];
        this._module         = this._popular_offers.length;
        
        this._current_index = params['start_index'] ? params['start_index'] : 0;
        this._current_index = this._current_index % this._module;
        
        this._cache_img = [];
        for (var i = 0; i < this._popular_offers.length; i++) {
            this._cache_img[i] = new Image();
            this._cache_img[i].src = img_path + this._popular_offers[i]['img_filename'] + '_prosto_featured.jpg';
        }
    },
    
    up: function()
    {
        this._draw();
    },

    _draw: function()
    {
        for (var j = 1; (j <= this._step); j++) {
            this._change_item_info(this._current_index, j);
            this._current_index = (this._current_index + 1) % this._module;
        }        
    },
    
    _change_item_info: function(index, id)
    {   
        var data = this._popular_offers[index];
        
        var $item = $('#popular-offer-' + id);
        var $a_title = null;
        var $a_image = null;
        var $image   = null;
        
        var $div_adress   = null;
        var $div_district = null;
        var $div_price    = null;
        
        $item.hide();
        
        $image = $item.find('#special-offer-image-' + id);
        $image.attr('src', this._cache_img[index].src);
        
        $a_title = $item.find('#special-offer-title-' + id);
        $a_title.text(data['realty_type_name']);
        $a_title.attr('href', script_url + '?rm=prosto_offer_details&realty_id=' + data['realty_id']);
        
        $a_image = $item.find('#image-container-' + id);
        $a_image.attr('href', script_url + '?rm=prosto_offer_details&realty_id=' + data['realty_id']);
        
        $div_adress = $item.find('#special-offer-adress-' + id);
        $div_adress.text(data['prepared_realty_address']);
        
        $div_district = $item.find('#special-offer-district-' + id);
        $div_district.text(data['prepared_region_name']);
        
        $div_price = $item.find('#special-offer-price-' + id);
        $div_price.text(data['cost'] + ' р.');
        
        $item.fadeIn(1000);
    }
}
