var RecommendedBlock = new Class({

    Implements: Options,
	
    options: {
        container_id: 	'recommended-container',
        object_id:		'recommended-object',
        buttons_id:		'recommended-buttons',
        preloader_id:	'recommended-preloader',
        category_pfx:	'recommended-category-',
        button_pfx:		'recommended-button-',
		
        timeout_length: 8,		// in seconds
		
        ajax_url:		null,
        tab : 0
    },
	
    timeout: null,
    categories: null,
    objects: null,
    cache: null,
    flower: null,
    active_category_idx: 0,
    active_object_idx: 0,


    initialize: function(options) {
        this.cache = new Array();
        if (!options.tab) {
            options.tab = 0;
        }

        if (options.objects_json) {
            this.cache[options.tab] = JSON.decode(options.objects_json);
            this.objects = this.cache[options.tab];
        }

        this.setOptions(options);
        this.options.timeout_length = parseInt(this.options.timeout_length * 1000);
        this.active_category_idx = this.options.tab;
        this.loadCategoryList();
    },


    loadCategoryList: function() {
        this.observeTabs();
        if (this.categories[this.active_category_idx] === undefined) {
            this.active_category_idx = 1;
        }

        this.setCategoryActive(this.categories[this.active_category_idx]);
        clearTimeout(this.timeout);
        this.timeout = setTimeout(this.autoChange.bind(this), this.options.timeout_length);
    },


    autoChange: function() {
        var index = (this.active_object_idx + 1);
        if(index >= this.objects.length) {
            index = 0;
        }
		
        this.setObjectActive(index);
        clearTimeout(this.timeout);
        this.timeout = setTimeout(this.autoChange.bind(this), this.options.timeout_length);
    },


    /**
     * Grąžina kategorijos id iš elemento id su prefixu.
     */
    getCategoryIdFromId: function(element_id) {
        //return element_id.substr(this.options.category_pfx.length - element_id.length);
        var pre_l = this.options.category_pfx.length;
        return element_id.substr(pre_l, element_id.length - pre_l);
    },


    observeTabs: function() {
        this.categories = Array();
        var container = $('sub_menu');
        var tabs = container.getChildren();
        for (var i = 0; i < tabs.length; i++) {
            var id = this.getCategoryIdFromId(tabs[i].id);
            tabs[i].addEvent('click', this.setCategoryActive.bind(this, id));
            this.categories[i] = id;
            var a = tabs[i].getChildren('a');
            if (a.length > 0) {
                a[0].addEvent('click', this.setCategoryActive.bind(this, id));
            }
        }
    },

		
    setCategoryActive: function(category_id) {
        var listItem = $(this.options.category_pfx + category_id);
        if (listItem == null) {
            return false;
        }
        this.setCategoryInactive(this.categories[this.active_category_idx]);
		
        for(var i = 0; i < this.categories.length; i++) {
            if(this.categories[i] == category_id) {
                this.active_category_idx = i;
            }
        }
        this.active_object_idx = 0;
		
        var links = listItem.getElements('a');
        links[0].className = 'act';
		
        var spans = listItem.getElements('span');
        spans[0].className = 'act';
		
        this.loadCategoryObjects();

        clearTimeout(this.timeout);
        this.timeout = setTimeout(this.autoChange.bind(this), this.options.timeout_length);
        return false;
    },
	
    setCategoryInactive: function(category_id) {
        var listItem = $(this.options.category_pfx + category_id);
        if(listItem == null) {
            return false;
        }
		
        var links = listItem.getElements('a');
        links[0].className = 'simple';
		
        var spans = listItem.getElements('span');
        spans[0].className = 'simple';
    },

    
    loadCategoryObjects: function() {
        $(this.options.container_id).className = "hide";
        $(this.options.preloader_id).className = "show";
        if(this.cache[this.active_category_idx] != null) {
            this.objects = this.cache[this.active_category_idx];
            this.showObjectList();
            this.setObjectActive(this.active_object_idx);
			
            $(this.options.preloader_id).className = "hide";
            $(this.options.container_id).className = "show";
            return;
        }
		
        var request = new Request.JSON({
            url: this.options.ajax_url,
            async: true,
            secure: false,
            data: {
                action: 'loadCategoryObjects',
                category_id: this.categories[this.active_category_idx]
            },
            onSuccess: function(result, text) {
                this.cache[this.active_category_idx] = result;
                this.objects = this.cache[this.active_category_idx];
                this.showObjectList();
                this.setObjectActive(this.active_object_idx);
				
                $(this.options.preloader_id).className = "hide";
                $(this.options.container_id).className = "show";
            }.bind(this)
        }).send();
    },
	
    showObjectList: function() {
        var buttonsContainer = $(this.options.buttons_id);
        var i = 0;
        var buttons = buttonsContainer.getElements('a');
        for(i = 0; i < buttons.length; i++) {
            buttons[i].dispose();
        }

        var inner = new Element('div', {
            'class' : 'inner'
        });
        inner.inject(buttonsContainer);

        for(i = 0; i < this.objects.length; i++) {
            var link = new Element('a', {
                'href': 'javascript:void(0);'
            });
            link.addEvent('click', this.setObjectActive.bind(this, [i, true]));
            link.appendText(' ' + parseInt(i + 1) + ' ');
            link.inject(inner);
        }
    },
	
    setObjectActive: function(object_idx, stop) {
        this.setObjectInactive(this.active_object_idx);
        this.active_object_idx = object_idx;
		
        this.showObjectData();
		
        var buttonsContainer = $(this.options.buttons_id);
        var links = buttonsContainer.getElements('a');
        var active = links[object_idx];

		for(i = 0; i < links.length; i++) {
            links[i].removeClass('active');
        }

		
        var link = new Element('a', {
            'href': 'javascript:void(0);',
            'class' : 'active clearfix'
        });
        link.addEvent('click', this.setObjectActive.bind(this, [object_idx, true]));

/*
        var img = this.flower;
        if(img == null) {
            img = new Element('img', {
                'src': 'images/icon_4.gif',
                'width': "14",
                'height': "14"
            });
        }
						
        img.inject(link);*/
        link.replaces(active);
		
        if(stop == true) {
            clearTimeout(this.timeout);
        }
		
        return false;
    },
	
    setObjectInactive: function(object_idx) {
        var buttonsContainer = $(this.options.buttons_id);
		
        var links = buttonsContainer.getElements('a');
        var active = links[object_idx];
		
        if(!active) {
            return;
        }
		
        var img = active.getElements('img');
        if(img.length != 0) {
            this.flower = img[0];
        }
		
        active.appendText(' ' + parseInt(object_idx + 1) + ' ');
    },
	
    showObjectData: function() {
        var data = this.objects[this.active_object_idx];
        var currObject = $(this.options.object_id);
        currObject.dispose();
		
        var newObject = new Element('div', {
            'id': this.options.object_id
        });
    
        var node = new Element('table', {
            cellspacing : 0,
            cellpadding : 0
        });
        var node_tbody = new Element('tbody', {});
        var node_tr = new Element('tr', {});
    
        node.inject(newObject);
        node_tbody.inject(node);
        node_tr.inject(node_tbody);
    
        var newImg = null;
        var newImgLink = null;
        if(data.image != '' && !data.image.src) {
            newImg = new Element('img', {
                'src': data.image,
                'class' : "img"
            });
            this.objects[this.active_object_idx].image = newImg;
            newImgLink = new Element('a', {
                'href': data.url
            });
        } else if(data.image.src != null && data.image.src != '') {
            newImg = data.image;
            newImgLink = new Element('a', {
                'href': data.url
            });
        }

        if (newImgLink !== null) {
            var node_td = new Element('td', {
                align : "center",
                valign : "middle",
                width: 100
            });
            node_td.inject(node_tr);
            newImg.inject(newImgLink);
            newImgLink.inject(node_td);
        }
    
        node_td = new Element('td', {
            valign : "top"
        });
        node_td.inject(node_tr);
		
        var span = new Element('span', {});
        span.appendText(data.title);
        span.inject(node_td);
		
        var desc = new Element('p', {
            'class': 'p-b-2'
        });
        desc.innerHTML = data.description + ' ';
        desc.inject(node_td);
		
        var link = new Element('a', {
            'href': data.url,
            'class': 'default_link nostat'
        });
    
        link.addEvent('click', function() {
            $('recommended-form').action = this.href;
            $('recommended-form').submit();
            return false;
        });    
        link.appendText('Pla\u010diau...');
        link.inject(desc);
		
        var buttonsContainer = $(this.options.buttons_id);
        newObject.inject($(this.options.container_id), 'top');
    }

});