var SearchUI = new Class({
    Implements: [Options, Events],
    
    initialize: function() {
        var self = this;
        $$('.next-page-button, .prev-page-button').addEvent('click', function(ev) {
            ev.stop();
            $('page').set('value', this.get('dynpage') || 1);
            self.submit(ev);
        });

        $$('.go-button').addEvent('click', function(ev) {
            ev.stop();
            var max = $('max-pages').get('text').toInt();
            var inpEl = $(this.get('dynfor'));
            var togo = inpEl.value.toInt();
            if(togo <= max) {
                $('page').set('value', togo);
                $('search-form').submit();
                inpEl.setStyle('background-color', '#fff')
            } else {
                inpEl.setStyle('background-color', '#fdd')
            }
        });

        $$('.sortby').addEvent('change', function() {
            $('sortby').set('value', this.value.replace(/ /g, '-'));
            $('page').set('value','1');
            $('search-form').submit();
        });
        $$('select.category').addEvent('change', function(ev) {
            self.categoryChanged();
        });
        $('search-form').addEvent('submit', this.submit.bind(this));
        $$('.search-full, .search-full .span').addEvent('click', this.submit.bindWithEvent(this));
        $$('.show-more').addEvent('click', this.showMore.bind(this));
        $('search-form-refine').getElement('.show-more').setStyle('display', 'none');
        var currCity = $('main-city-display').getElement('.city-name').getAttribute('dyncode');
        $('search-city').set('value', currCity);
        
        $$('.no-results .city').addEvent('click', function(ev) {
            ev.stop();
            var currCity = this.getAttribute('dyncode');
            $('search-city').set('value', currCity);
            self.submit(false, true);
        });
        
//         var currCity = $('search-city').value;
//         if(currCity && currCity != 'all-cities') {
//             window.mainCityTree.setPlace(currCity);
//         } else {
//             window.mainCityTree.setPlace('all-cities');
//             $('search-city').set('value', window.mainCityTree.currentPlace()[0]);
//         }
//         window.mainCityTree.addEvent('placeselected', function(code, slug, label) {
//             $('search-city').set('value', code);
//         });
    },
    categoryChanged: function(initialLoad) {
        initialLoad = initialLoad || false;
        var self = this;
        var category = $$('select.category')[0];
        $('page').set('value', 1);
        var option = $(category.options[category.selectedIndex]).get('code');
        $$('.item-subtype').setStyle('display', 'none');
        $('search-form-refine').getElement('.show-more').setStyle('display', 'none');
        var options = false;
        if( $A(['categories-wedding-dress', 'categories-mother-bride', 'categories-bridesmaid-dress']).contains(option)) {
            options = $$('.dress-item-options')[0];
        } else if( $A(['categories-jewellery', 'categories-accessories', 'categories-decorations', 'categories-veils', 'categories-decorations-reception', 'categories-decorations-ceremony', 'categories-free'
        ]).contains(option)) {
            options = $$('.catch-all-options')[0];
        } else if ($A(['categories-shoes']).contains(option)) {
            options = $$('.shoe-item-options')[0];
        } else if(option && option != '-1' && option != -1){
            options = $$('.other-attire-options')[0];
        }
        if(options) {
            options.setStyle('display', 'block');
            if(options.getElements('.more').length) {
                $('search-form-refine').getElement('.show-more').setStyle('display', 'block').addClass('more').set('text', 'More Search Options');
                options.getElements('.more').setStyle('display', 'none');
            } else {
                $('search-form-refine').getElement('.show-more').setStyle('display', 'none');
            }
        }
        self.currentItemType = option;
        self.currentItemTypeForm = options;
        if(window.location.search.length && initialLoad) {
	    this.showMore();
        }
    },
    
    setCategory: function(searchCategory) {
        var category = $$('select.category')[0];
        var maincategory = document.getElementById('maincatdd');

        for(i = 0; i < category.options.length; i++) {
            if(category.options[i].value == searchCategory){
                category.selectedIndex = i;
                maincategory.selectedIndex = i;
                break;
            }
        }
        this.categoryChanged();
    },
    
    setSearchString: function(searchString) {
        $$('.searchstring').set('value', searchString);
        $('keyword_search').set('value', searchString);
    },
    
    setSizes: function(sizeLow, sizeHigh, sl_id, sh_id) {
        var options = this.currentItemTypeForm;
        if (options && options.getElement('.sizelow')) {
            s1 = options.getElement('.sizelow');
            s2 = options.getElement('.sizehigh');

            for(i =0; i < s1.options.length; i++) {
                if(s1.options[i].value == sl_id) {
                    s1.selectedIndex = i;
                    break;
                }
            }
            
            for(i =0; i < s2.options.length; i++) {
                if(s2.options[i].value == sh_id) {
                    s2.selectedIndex = i;
                    break;
                }
            }
              
        }
    },
    
//     setColour: function(colour) {
//         var options = this.currentItemTypeForm;
//         if (options) {
//             color = options.getElement('.item-color');
//             console.log(color);
//             for(i=0; i < color.options.length; i++) {
//                 if(color.options[i].value == colour) {
//                     color.selectedIndex = i;
//                     break;
//                 }
//             }
//         }
//     },
//     
    setYearPurchased: function(year) {
        var options = this.currentItemTypeForm;
        if(options) {
            var y = $('year_purchased');
            for(i=0; i< y.options.length; i++) {
                if( y.options[i].value == year) {
                    y.selectedIndex = i;
                    break;
                }
            }
        }
    },
    
    setLength: function(length) {
        var options = this.currentItemTypeForm;
        if(options) {
            var l = $('dress_length');
            for(i=0; i< l.options.length; i++) {
                if(l.options[1].value == length) {
                    l.selectedIndex = l;
                }
            }
        }
    },
    
    setDressRefine: function(silhouette, neckline, designer, condition) {
        var options = this.currentItemTypeForm;
        if(options) {
            var s_silhouette = options.getElementById('silhouette');
            var s_neckline = options.getElementById('neckline');
            var s_designer = options.getElementById('designer');
            var s_condition = options.getElementById('condition');
            if(s_silhouette) {
                for(i=0; i < s_silhouette.options.length; i++) {
                    if(s_silhouette.options[i].value == silhouette) {
                        s_silhouette.selectedIndex = i;
                        break;
                    }
                }
            }
            if(s_neckline) {
                
                for(i=0; i < s_neckline.options.length; i++) {
                    if(s_neckline.options[i].value == neckline) {
                        s_neckline.selectedIndex = i;
                        break;
                    }
                }
            }
            if(s_designer) {
                
                for(i=0; i < s_designer.options.length; i++) {
                    if(s_designer.options[i].value == designer) {
                        s_designer.selectedIndex = i;
                        break;
                    }
                }
            }
            if(s_condition) {
                for(i=0; i < s_condition.options.length; i++) {
                    if(s_condition.options[i].value == condition) {
                        s_condition.selectedIndex = i;
                        break;
                    }
                }
            }
            
        }
        
    },
    
    setShoeRefine: function(colour, style, height, condition) {
        var options = this.currentItemTypeForm;
        if(options) {
            var s_color = $('color');
            var s_style = $('style');
            var s_height = $('heel-height');
            var s_condition = $('condition');
            for(i=0; i< s_color.options.length; i++) {
                if( s_color.options[i].value == colour) {
                    s_color.selectedIndex = i;
                    break;
                }
            }
            
            for(i=0; i< s_style.options.length; i++) {
                if( s_style.options[i].value == style) {
                    s_style.selectedIndex = i;
                    break;
                }
            }
            
            for(i=0; i< s_height.options.length; i++) {
                if( s_height.options[i].value == height) {
                    s_height.selectedIndex = i;
                    break;
                }
            }
            
            for(i=0; i< s_condition.options.length; i++) {
                if( s_condition.options[i].value == condition) {
                    s_condition.selectedIndex = i;
                    break;
                }
            }
            
        }
    
    },
    
    
    setSorting: function(sorting) {
        sortIndex = 0;

        if(sorting == '-postdate'){
            sortIndex = 0;
        } else if(sorting == 'postdate'){
            sortIndex = 1;
        } else if(sorting == 'price'){
            sortIndex = 2;
        } else if(sorting == '-price'){
            sortIndex = 3;
        } else if(sorting == 'designer_term__sort_order'){
            sortIndex = 4;
        }

        $('sortbytop').selectedIndex = sortIndex;
        $('sortbybottom').selectedIndex = sortIndex;
        $('sortby').set('value', $('sortbytop').options[sortIndex].value.replace(/ /g, '-'));
    },
    
    checkPrice: function() {
        var options = this.currentItemTypeForm;
        if(options) {             
            if(!options.getElement('.pricelow')) return true;
            
            var priceLow  = options.getElement('.pricelow').value;
            var priceHigh = options.getElement('.pricehigh').value;
            
            if(priceLow != ''){ 
                if(isNaN(priceLow)){
                    alert('Please enter a valid "Low Price".');
                    return false;
                }
            }

            if(priceHigh != ''){ 
                if(isNaN(priceHigh)){
                    alert('Please enter a valid "High Price".');
                    return false;
                }
            }

            //validate if low price is less than high price
            if (priceLow != '' && priceHigh != ''){
                if(parseFloat(priceHigh) <= parseFloat(priceLow)){
                    alert('Your "Low Price" is higher than your "High Price". Please update the prices.');
                    return false;
                }
            }
        }
        return true;
    },
    checkSize: function() {
        var options = this.currentItemTypeForm;
        if(options) {   
            if(!options.getElement('.sizelow')) return true;
            var sizeLow = options.getElement('.sizelow');
            var sizeHigh = options.getElement('.sizehigh');

    //         sizeLow = sizeLow.options[sizeLow.selectedIndex].get('text');        
    //         sizeHigh = sizeHigh.options[sizeHigh.selectedIndex].get('text');

            if( !(sizeLow.selectedIndex == 0) && !(sizeHigh.selectedIndex == 0) ){
                if(sizeLow.selectedIndex > sizeHigh.selectedIndex ){
                    alert('Your "Low Size" is higher than your "High Size". Please update the sizes.');
                    return false;
                }
            }
        }
        return true;
    },
    submit: function(ev, auto) {
//         console.log('submitting', $(ev.target));
        var type = 'button';
        if(ev) {
            if($(ev.target).hasClass('button') || $(ev.target).getParent('a').hasClass('button')) type = 'a.button';
        }
        var self = this;
        if(type == 'a.button') {
            ev.stop();
        }
        if(!(self.checkPrice() && self.checkSize())) {
            ev.stop();
            ev.preventDefault();
            return false;
        } else {
//             console.log('checked oprices', self.checkPrice(), self.checkSize(), type);
        }

        var options = self.currentItemTypeForm;
        $$('.item-subtype').each(function(el) {
            if(el != options) el.dispose();
        });

//        console.log('submitting form', $(ev.target).getParent('form'));
        if ($(ev.target).getParent('form') && $(ev.target).getParent('form').id == 'search-form'){
	    $('refine-search-was-submitted').set('value', 1);
	}
        if(type == 'a.button' || auto) {
//             console.log('submitting form', $(ev.target).getParent('form'));
            $('search-form').submit();
        }
    },
        
    procData: function(func) {
        var self = this;

        var options = self.currentItemTypeForm;
        var forms = $A([]);
        $$('.item-subtype').each(function(el) {
            if(el != options) forms.push(el.dispose());
        });
        func();
        forms.each(function(el){
            el.inject($('search-form'), 'bottom');
        });
    },
    showMore: function(ev) {
        if(ev) ev.stop();
        var self = this;
        var options = self.currentItemTypeForm;
        var disp = options.getElement('.more').getStyle('display');
        if(disp == 'none') {
            $$('.show-more').set('text', 'Minimize').removeClass('more');
            options.getElements('.more').setStyle('display', 'block');
	    $('expand-search-box').set('value', 1);
        } else {
            $$('.show-more').set('text', 'More Search Options').addClass('more');
            options.getElements('.more').setStyle('display', 'none');
	    $('expand-search-box').set('value', -1);
        }
    }
});




