var SiteSearch = Class.create({

    initialize: function(handle, params) {

        this.handle = $(handle);
        this.submit = $('submit_site-search');
        this.queryInput = $(this.handle.getInputs('text', 'search_query_keyword')[0]);
        this.loading = $('site-search-loading');
        this.result = null;
        this.timer = null;

        //this.submit.observe('click', this.request.bind(this));
        this.queryInput.observe('keyup', this.handleKeys.bind(this));
		this.handle.observe('submit', this.handleSubmit.bind(this))
    },
    request: function() {

        if ("" == this.queryInput.getValue()){
			if( this.result ) this.result.destroy();
			this.loading.setStyle({display:"none"});
			return;
		}
		
		new Ajax.Request( $('site-search-link').readAttribute('href'), {
			method:'post', 
			parameters: this.handle.serialize(),
			onComplete: this.updateResults.bind(this)
		});

        return false;
    },
    handleKeys: function(e) {
		
		if (e.keyCode == Event.KEY_RETURN && this.result ) return this.result.openResultRowLink();
        if (e.keyCode == Event.KEY_ESC && this.result) return this.result.destroy();
        if (e.keyCode == Event.KEY_DOWN && this.result) return this.result.moveDown();
        if (e.keyCode == Event.KEY_UP && this.result) return this.result.moveUp();
		
        var breakKeys = [Event.KEY_RETURN, Event.KEY_TAB, Event.KEY_LEFT, Event.KEY_RIGHT, 224, 16, 17, 18, 46, 34, 33];
        for (var i in breakKeys) if (breakKeys[i] == e.keyCode) return;
		
		this.loading.setStyle({display:"block"});
		
        if (this.timer) clearTimeout(this.timer);
        this.timer = setTimeout(this.request.bind(this), 300);
    },
	handleSubmit: function(e){
		this.request();
		Event.stop(e);
	},
    updateResults: function(t) {
        if (this.result) this.result.destroy();
		this.loading.setStyle({display:"none"});
        this.result = new SiteSearchResult($('page-meta'), t.responseText);
    }
});

var SiteSearchResult = Class.create({

    initialize: function(parent, resultText) {

        this.handle = parent.insert(resultText);
        this.errorMessage = $('search-noresult').hide();
		this.footerMessage = $('search-footer');

        var productItems = this.handle.getElementsByClassName('product-item');
        var newsItems = this.handle.getElementsByClassName('news-item');
        var boutiqueItems = this.handle.getElementsByClassName('boutique-item');
        var maxItems = 8;
        var maxProducts = Math.min(maxItems, productItems.length);
        var maxNews = Math.min(maxItems, newsItems.length);
        var maxBoutiques = Math.min(maxItems, boutiqueItems.length);

        if (maxProducts + maxNews + maxBoutiques > maxItems) {

            maxProducts = Math.min(5, maxProducts);
            maxNews = maxBoutiques > 0 ? Math.min(Math.max(newsItems.length - boutiqueItems.length, newsItems.length), newsItems.length, 2) : maxItems - maxProducts;
            maxBoutiques = Math.min(maxItems - maxProducts - maxNews, boutiqueItems.length);

            for (var i = maxProducts; i < productItems.length; i++) $(productItems[i]).hide().addClassName('hidden-row').removeClassName('search-row');
            for (var i = maxNews; i < newsItems.length; i++) $(newsItems[i]).hide().addClassName('hidden-row').removeClassName('search-row');
            for (var i = maxBoutiques; i < boutiqueItems.length; i++) $(boutiqueItems[i]).hide().addClassName('hidden-row').removeClassName('search-row');
        }

        var headProducts = $('search-header-products');
        var headNews = $('search-header-news');
        var headBoutiques = $('search-header-boutiques')

        if (headProducts && maxProducts == 0) headProducts.hide();
        if (headNews && maxNews == 0) headNews.hide();
        if (headBoutiques && maxBoutiques == 0) headBoutiques.hide();

        this.items = $A(this.handle.getElementsByClassName('search-row'));
        this.currentRow = null;

        this.boundRowRollover = this.rowAction.bind(this);
        this.boundRowRollout = this.rowAction.bind(this);

        this.items.each(function(elm) {
            $(elm).observe('mouseover', this.boundRowRollover).observe('mouseout', this.boundRowRollout);
        }.bind(this));
		
		this.updateResultsLink( maxProducts, maxNews, maxBoutiques );
		
		if( this.items.length > 0 ){
			this.errorMessage.hide();
			this.footerMessage.show();
		}
		else{
			this.errorMessage.show();
			this.footerMessage.hide();
		}
		
		var srch = $('search-wrap');
		
		if( srch ){
			srch.setStyle("display", "block");
			
			if(isIE6OrLess() == true) {

				// changing pulldown backgrounds because alpha-pngs are used
				var arrOutElements = new Array('#search-wrap .sh-out');
				arrOutElements.each(function(OutElement) {
					$$(OutElement).each(function(Element) {
							Element.setStyle({backgroundImage:'none'});
							Element.setStyle({padding:'0px'});
					});
				});

				// changing pulldown backgrounds because alpha-pngs are used
				var arrInElements = new Array('#search-wrap .sh-in');
				arrInElements.each(function(InElement) {
					$$(InElement).each(function(Element) {
						Element.setStyle({backgroundImage:'none'});
						Element.setStyle({borderRight:'#CCC 1px solid'});
						Element.setStyle({borderLeft:'#CCC 1px solid'});
						Element.setStyle({borderBottom:'#CCC 1px solid'});
						Element.setStyle({padding:'0px'});
						Element.setStyle({margin:'0px 5px 8px 5px'});
					});
				});

			}
		}
    },
    selectRow: function(row) {
        if (!row) return;
        if (this.currentRow) this.currentRow.toggleClassName('search-row-active').toggleClassName('search-row');
        this.currentRow = $(row).toggleClassName('search-row-active').toggleClassName('search-row');
    },
    rowAction: function(e) {
        this.selectRow(e.element().tagName != 'DIV' ? e.findElement('DIV') : e.element());
    },
    moveDown: function() {
        var nextRow = this.handle.down('.search-row-active');
        nextRow = nextRow ? nextRow.next('.search-row') : this.handle.down('.search-row');
        this.selectRow(nextRow);
    },
    moveUp: function() {
        var prevRow = this.handle.down('.search-row-active');
        prevRow = prevRow ? prevRow.previous('.search-row') : this.handle.down('.search-row');
        this.selectRow(prevRow);
    },
	openResultRowLink: function(){
		if( !this.currentRow ) return;
		window.location.href = this.currentRow.down('a').readAttribute('href');
	},
	updateResultsLink: function( mp, mn, mb ){
		var href = this.footerMessage.down('a').readAttribute('href');
		var search_type = 'products';
		var max = 0;
		
		if( mp > max ){
			max = mp;
			search_type = 'products';
		}
		if( mn > max ){
			max = mn;
			search_type = 'news';
		}
		if( mb > max ){
			max = mb;
			search_type = 'boutiques';
		}
		
		this.footerMessage.down('a').writeAttribute('href', href + '&search_type=' + search_type  );
	},
    destroy: function() {

        if ($('search-wrap')) $('search-wrap').remove();

        this.items.each(function(elm) {
            Event.stopObserving(elm, 'mouseover', this.boundRowRollover);
            Event.stopObserving(elm, 'mouseout', this.boundRowRollout);
        }.bind(this));

        delete this.boundRowRollover;
        delete this.boundRowRollout;
    }
});

initFunctions.push(function() {
    if ($('site-search')) {
        new SiteSearch($('site-search'));
    }
});
