/**
 * ::::::::::::::::::::::::::::::::::::::::::::
 * :: Copyright (c) 2006. H-Art & Technology ::
 * ::::::::::::::::::::::::::::::::::::::::::::
**/

var Ricerca = {
    XML_URL: "index.php?id=productsXml&get=products",
    
    model: {
        data: [],
        
        init: function(dom) {
            this.data = $A(dom.getElementsByTagName('product')).sortBy(function(v, i) {
                return v.getAttribute('title');
            });
            //alert(this.data.toSource());
        },
        
        isEmpty: function() { return this.data.length == 0; },
        
        getMatchingProducts: function(prefix) {
            return this.data.findAll(function(v) {
                return v.getAttribute('title').toLowerCase().indexOf(prefix.toLowerCase()) == 0;
            });
        }
    },
    
    view: {
        //curEntryIndex: -1,
        
        entry: {
            render: function(title, index) {
                return '<div index="'+index+'" onmouseout="Ricerca.controller.handlers.onMouseOut(this)" onmouseover="Ricerca.controller.handlers.onMouseOver(this)" onclick="Ricerca.controller.handlers.onClick(this)">' + title + '</div>';
            },
            
            select: function(index) {
                return $A($('ajaxresult').getElementsByTagName('div')).find(function(v) {
                    return v.getAttribute('index') == index;
                });
            },
            
            addClassName:function(index, className) {
                Element.addClassName(this.select(index), className);
            },

            removeClassName:function(index, className) {
                Element.removeClassName(this.select(index), className);
            },

            turnOn: function(index) {
                this.addClassName(index, 'active');
            },
            
            turnOff: function(index) {
                this.removeClassName(index, 'active');
            }
            
        },
        
        result: {
            id: 'ajaxresult',
            idStatus: 'ajaxstatusbar',
            idStatusBack: 'ajaxstatusbarback',
            idBack: 'ajaxback',
            
            offsetTop: {
                'Internet Explorer': 383,
                '*': 355
            },
            
            hide: function() {
                //Element.hide(this.idContainer);
                $(this.id).style.visibility = 'hidden';
                $(this.idBack).style.visibility = 'hidden';
                $(this.idStatus).style.visibility = 'hidden';
                $(this.idStatusBack).style.visibility = 'hidden';
            },
            
            show: function() {
                //Element.show(this.idContainer);
                $(this.id).style.visibility = 'visible';
                $(this.idBack).style.visibility = 'visible';
                $(this.idStatus).style.visibility = 'visible';
                $(this.idStatusBack).style.visibility = 'visible';
            },
            
            resize: function(shown) {
                var result = $(this.id);
                var back = $(this.idBack);
                var offsetTop = (browser in this.offsetTop) ? this.offsetTop[browser] : this.offsetTop['*'];
                
                var h = result.offsetHeight;
                
                back.style.height = h+'px';
                back.style.top = (offsetTop - h)+'px';

result.style.top = (offsetTop - 2*h)+'px';
if(browser == 'Internet Explorer') {
  if(shown == 3) {
    result.style.top = (offsetTop - 2*h - 15)+'px';
  }
  else if(shown == 2) {
    result.style.top = (offsetTop - 3*h)+'px';
  }
  else if (shown == 1){
    result.style.top = (offsetTop - 5*h)+'px';
  }
}
               
            },
            
            update: function(list, resize) {
                var html = ""
                list.each(function(v, i) {
                    html += Ricerca.view.entry.render(v, i);
                });
                
                if (resize) {
                    $(this.id).style.visibility = 'hidden';
                }
                
                Element.update(this.id, html);
                
                if (resize) {
                    this.resize(list.length);
                    $(this.id).style.visibility = 'visible';
                }
            }
        },
        
        status: {
            id: 'ajaxstatus',
            
            render: function(shown, total, prefix) {
                return 'Sono mostrati '+shown+' risultati su '+total+' che iniziano per "'+prefix+'"';
            },
            
            update: function(shown, total, prefix) {
                Element.update(this.id, this.render(shown, total, prefix));
            }
        },
        
        spinner: {
            id: 'ajax_spinner',
            
            show: function() {
                $(this.id).style.visibility = 'visible';
            },
            
            hide: function() {
                $(this.id).style.visibility = 'hidden';
            }
        }
    },
    
    controller: {
        lastPrefix: "",
        
        lastResult: [],
        
        currentEntry: -1,
        
        init: function() {
            var self = this;
            this.req = new Ajax.Request();
            this.req.transport = Ajax.getTransport();
            this.req.setOptions({
                asynchronous: true, //false,
                onComplete: self.onCompleteReq.bind(self)
            });
            
            //Element.hide('ajax_spinner');

            Ajax.Responders.register({
                onCreate: function() {
                    Ricerca.view.spinner.show();
                },
                
                onComplete: function() {
                    Ricerca.view.spinner.hide();
                }
            });
            
            Event.observe('prodotto', 'keyup', this.onKeyUpEvent.bind(this));
            
            this.req.request(Ricerca.XML_URL);
        },
        
        reset: function() {
            this.lastPrefix = "";
            this.lastResult = [];
            this.currentEntry = -1;
            //Ricerca.model.data = [];
            Ricerca.view.result.hide();
        },
        
        onKeyUpEvent: function(event) {
            if (Ricerca.model.isEmpty())
                return;
            switch (event.keyCode) {
                case Event.KEY_UP:
                    if (this.lastResult.length) {
                        if (this.currentEntry >= 0)
                            Ricerca.view.entry.turnOff(this.currentEntry);
                        this.currentEntry = ((this.currentEntry > 0) ? this.currentEntry : this.lastResult.length) - 1;
                        Ricerca.view.entry.turnOn(this.currentEntry);
                    }
                    break;
                case Event.KEY_DOWN:
                    if (this.lastResult.length) {
                        if (this.currentEntry >= 0)
                            Ricerca.view.entry.turnOff(this.currentEntry);
                        this.currentEntry = (this.currentEntry + 1) % this.lastResult.length;
                        Ricerca.view.entry.turnOn(this.currentEntry);
                    }
                    break;
                case Event.KEY_RETURN:
                    if (this.currentEntry >= 0) {
                        var product = this.lastResult[this.currentEntry];
                        if (product)
                            location.href = product.getAttribute('link');
                    }
                    break;
                case Event.KEY_ESC:
                    this.reset();
                    break;
                default:
                    var prefix = $F('prodotto');
                    if (this.lastPrefix.toLowerCase() != prefix.toLowerCase()) {
                        /*
                        if (Ricerca.model.isEmpty()) {
                            this.req.request(Ricerca.XML_URL);
                        } else this.update(prefix);
                        */
                        this.update(prefix);
                    }
            }
        },
        
        onCompleteReq: function(transport, object) {
            Ricerca.model.init(transport.responseXML);
            //this.update($F('prodotto'));
        },
        
        handlers: {
            //container: Ricerca.controller,
            
            onClick: function(div) {
                var index = div.getAttribute('index');
                var product = Ricerca.controller.lastResult[parseInt(index)];
                if (product)
                    location.href = product.getAttribute('link');
            },
            
            onMouseOut: function(div) {
                Element.removeClassName(div, 'active');
            },

            onMouseOver: function(div) {
                Element.addClassName(div, 'active');
            }
        },
        
        update: function(prefix) {
            this.lastPrefix = prefix;
            
            if (!prefix.length) {
                this.reset();
                return;
            }
            
            var products = Ricerca.model.getMatchingProducts(prefix);
/*            
            Ricerca.view.result.update(
                products.map(function(v) {return v.getAttribute('title');}),
                (products.length != this.lastResult.length)
            );
*/
            Ricerca.view.result.update(
                products.map(function(v) {return v.getAttribute('title');}),true
            );
            Ricerca.view.result.show();
            Ricerca.view.status.update(products.length, products.length, prefix);
            
            this.lastResult = products;
        }
    }
};


WindowOnload(Ricerca.controller.init.bind(Ricerca.controller));
