Controller = new Class({
    initialize : function(searchBoxId, tagsDivId, itemsDivId) {
        this.suggests = [];
        
        this.searchBox = $(searchBoxId);
        this.tagsDiv = $(tagsDivId);
        this.itemsDiv = $(itemsDivId);
        
        this.items_in_row = 5;
        this.product = null;

        this.attribute_suggests_request = null;
        this.suggests_request = null;

        this.details_visible = null;

        this.searchBox.addEvent('keyup', function(event, withValue) {
            if (event) {
                event.stop();
            }
            if($defined(this.timer)) {
                $clear(this.timer);
            }
            if($defined(this.aTimer)) {
                $clear(this.aTimer);
            }

            if (withValue) {
                if (!this.sameQuery(withValue)) {
                    this.loadSuggests(withValue);
                }
            } else {
                query = event.target.get('value');
                if (!this.sameQuery(query)) {
                    if (event.key == 'space') {
                        //this.aTimer = (this.loadAttributeSuggests.bind(this, event.target.get('value'))).delay(100);
                        this.timer = (this.loadSuggests.bind(this, query)).delay(200);
                    } else {
                        this.aTimer = (this.loadAttributeSuggests.bind(this, query)).delay(100);
                        this.timer = (this.loadSuggests.bind(this, query)).delay(400);
                    }
                }
            }
        }.bind(this));
        
        this.searchBox.focus();
        

        this.previous_q = null;

        if( window.location.hash && window.location.hash.length > 1 ) {
            // Get initial page
            this.updateContent(window.location.hash);
        }
    },

    sameQuery : function(query) {
        if (query.match('^' + this.previous_q + '\s*$')) {
            return true;
        } else {
            this.previous_q = query;
            return false;
        }
    },

    updateContent : function(hash) {
        var h = hash.substr(1, hash.length);
        path_blocks = h.split(/[\/]/);
        if (path_blocks.length > 1) {
            this.product = path_blocks[1]
        }
        pairs = path_blocks[0].split(/[&;]/);
        attributes = {}
        pairs.each(function(pair) {
            parts = pair.split('=');
            if (parts.length != 2) {
                return;
            }
            attributes[parts[0]] = decodeURIComponent(parts[1]).replace(/\+/g, ' ');
        });
        if (attributes["q"]) {
            this.searchBox.set('value', attributes["q"] + ' ');
            this.searchBox.fireEvent('keyup', [null, this.searchBox.get('value')]);
            this.searchBox.focus();
        }
    },

    clickOnTag : function(ev) {
        var val = this.searchBox.get('value').trim();
        this.searchBox.set('value', val + ' ' + ev.target.get('text') + ' ');
        this.searchBox.fireEvent('keyup', [null, this.searchBox.get('value')]);
        this.searchBox.focus();
    },
    
    clickOnSuggest : function(ev) {
        var val = this.searchBox.get('value');

        var suggest = ev.target.get('text');
        var i = 0;
        for (i = 0; i < suggest.length; i++) {
            var part = suggest.substring(0, suggest.length - i)
            if (val.contains(part)) {
                indx = val.lastIndexOf(part);
                val = val.substring(0, indx) + suggest + val.substring(indx + part.length, val.length) + ' ';
                //val = val.replace(part, suggest);
                break;
            }
        }

        //window.location.hash = 'q=' + encodeURIComponent(val);
        this.searchBox.set('value', val);
        this.searchBox.fireEvent('keyup', [null, this.searchBox.get('value')]);
        this.searchBox.focus();
    },

    drawSuggestions : function(data) {
        this.tagsDiv.empty();
        this.suggests.clean();
        tagsDiv = this.tagsDiv;
        suggests = this.suggests;
        clickOnTag = this.clickOnTag.bind(this);

        function show_line(line) {
            if (line) {
                line.each(function(el) {
                    if (el && el != "") {
                        var suggest = new Element("span", {"class" : "tag", "text" : el});
                        tagsDiv.appendChild(suggest);
                        suggests.push(suggest);
                        suggest.addEvent('click', clickOnTag);
                    }
                });
            }
        }

        var hash = new Hash(data);
        hash.getKeys().sort().each(function(l) {
            tagsDiv.appendChild(new Element("br"));
            show_line(hash[l]);
        });
    },
    
    drawAttributeSuggestions : function(data) {
        this.tagsDiv.empty();
        this.suggests.clean();
        data.each(function(el) {
            var suggest = new Element("span", {"class" : "suggest", "text" : el});
            this.tagsDiv.appendChild(suggest);
            suggest.addEvent('click', this.clickOnSuggest.bind(this));
        }.bind(this));
    },
    
    redrawCart : function() {
        $('cart').load('/cart/view');
    },
    
    removeItemFromCart : function(id) {
        $('cart').load('/cart/delete', {
            "id" : id
        });
    },
    
    addItemToCart : function(id) {
        $('cart').load('/cart/add', {
            "id" : id
        });
    },

    getAddToCartButton : function(item) {
        var price = item.price + '';
        // pricebeautifier in js
        while (price.length < 3) price = '0' + price;
        var table = new Element('table');
        table.set('html',
        '<tr>' +
            '<td><big>' + price.substring(0, price.length - 2) + '<small>' + price.substring(price.length - 2) + '</small></big> грн</td>' + 
            '<td><div onClick="javascript:c.addItemToCart(' + item.id + ')" class="add_to_cart"/></td>' +
        '</tr>');
        return table;
    },
    
    drawItems : function(data) {
        this.itemsDiv.empty();
        var i = 0;
        data.each(function(el) {
            var item = new Element("div", {"class" : "item", "id" : el.id});
            item.appendChild(new Element("div", {"class" : "block_tovar", "id" : "details_" + el.id}));
            var img = 'http://labs.labelsdb.com/' + el.ean + '/main_image-s200x200';
            var prod_link = new Element("a", {"href" : window.location.hash.split('/')[0] + "/" + el.id});
            prod_link.appendChild(new Element("img", {"src" : img}));
            item.appendChild(prod_link);
            var name_block = new Element('div', {'text' : el.name, 'class' : 'label', 'id' : 'label_' + item.id})
            name_block.appendChild(new Element('div', {'class' : 'clear'}));
            name_block.appendChild(this.getAddToCartButton(el));
            item.appendChild(name_block);
            this.itemsDiv.appendChild(item);
        }.bind(this));
    },

    loadSuggests : function(query) {
        if (this.suggests_request) {
            this.suggests_request.cancel();
        }
        this.suggests_request = new Request.JSON({
            url : "s/items",
            onSuccess : function(response){
                if (response) {
                    h = [];
                    query.trim().split(' ').each(function(el) {
                        h.include(encodeURIComponent(el));
                    });
                    window.location.hash = "q=" + h.join('+') + ((this.product) ? ('/' + this.product) : "");
                    this.product = null;
                    if (response.items && response.items.length != 0) {
                        this.tagsDiv.empty();
                        this.drawItems(response.items);
                    } else {
                        this.itemsDiv.empty();
                    }

                    var line_filled = false;
                    for (l in response.attributes) {
                        line_filled = line_filled || response.attributes[l].length > 0;
                    }
                    if (line_filled) {
                        this.drawSuggestions(response.attributes);
                    } else {
                        this.suggests.clean();
                    }
                    
                }
            }.bind(this)
        }).get({'query' : query});
    },
    
    loadAttributeSuggests : function(query) {
        if (this.attribute_suggests_request) {
            this.attribute_suggests_request.cancel();
        }
        this.attribute_suggests_request = new Request.JSON({
            url : "s/attributes",
            link : 'cancel',
            onSuccess : function(response){
                this.drawAttributeSuggestions(response);
            }.bind(this)
        }).get({'query' : query});
    }
    
});


ProductDetailsController = new Class({
    initialize : function(myFx) {

        this.myFx = myFx;
        window.addEvent('hashchange', this.hashEvent.bind(this));
        this.overlay_div = $('overlay')
        if( window.location.hash && window.location.hash.length > 1 ) {
            // Get initial page
            this.hashEvent(window.location.hash);
        }
    }, 

    getDetails : function(id) {
        new Request.HTML({
            url : '/items/' + id,
            onSuccess : function(responseTree, responseElements, responseHTML, responseJavaScript) {
                $("details_" + id).set('html', responseHTML);
                $("details_" + id).setStyle('display', 'block');
                this.details_visible = id;
                //$('details').set('html', responseHTML); 
            }.bind(this)
        }).get();
    },

    hashEvent : function(hash) {
        if (this.details_visible) {
            $("details_" + this.details_visible).empty();
            $("details_" + this.details_visible).setStyle('display', 'none');

            this.details_visible = null;
        }
        if (hash.match('/')) {
            id = hash.split("/")[1];
            this.getDetails(id);
        }
    }
});

window.addEvent('domready', function() {
    new ProductDetailsController(new Fx.Scroll(window));
});
