var SchoolsFilter = new Class({
    Implements: [Events],

    initialize: function (schools, schoolsElements) {
        this.filters = {};
        this.schools = schools;
        this.schoolsElement = schoolsElements;
        for (var i = 0; i < schools.length; i++) {
            schools[i].el = schoolsElements[i];
            schoolsElements[i].set('school', schools[i]);
        }
        this.updateFiltersFromUrl();
    },


    updateFiltersFromUrl : function() {

        if(window.location.hash) {
            var hash = window.location.hash;
            hash = hash.replace('#', '');
            var params = hash.split('&');
            for(var i = 0; i < params.length; i++) {
                var values = params[i].split('=');
                if(values.length == 2)
                    this.filters[values[0]] = JSON.decode(values[1]);
            }
            this.updateSchools();
        }

    },


    /**
     * Set a filter
     *
     * @param string name The filter name
     * @param mixed value The filter value
     */
    setFilter: function (name, value) {
        if (!value) {
            delete this.filters[name]
        } else {
            this.filters[name] = value;
        }



        this.updateSchools();
    },



    /**
     * Reset all the field
     */
    reset: function () {
        this.filters = {};
        this.updateSchools();
    },



    /**
     * Sort the school elements
     * @param type
     */
    sort: function(type) {

        var schoolContainer = $('schools-list-container');
        switch(type){
            case 'price':
                var currency = this.filters.currency ? this.filters.currency : 'EUR';

                this.schools.sort(function(a,b){
                    var aPrice, bPrice;
                    a.minPricePerWeek.each(function(price, index){
                        if (price.currency == currency) {
                            aPrice =  price.minPricePerWeek;
                            return;
                        }
                    });

                    b.minPricePerWeek.each(function(price, index){
                        if (price.currency == currency) {
                            bPrice =  price.minPricePerWeek;
                            return;
                        }
                    });

                    return (aPrice - bPrice)
                });

                break;
            case 'country':
                this.schools.sort(function(item1,item2){
                    return item1.countryName.localeCompare(item2.countryName);
                });

                break;
            case 'name':
                this.schools.sort(function(item1,item2){
                    return item1.cityName.localeCompare(item2.cityName);
                });

                break;
            case 'rating':
                this.schools.sort(function(item1,item2){
                    return (item2.rating - item1.rating)
                });


                break;
            case 'program':
                this.schools.sort(function(item1,item2){
                    return (item1.schoolProgramId - item2.schoolProgramId)
                });


                break;

        }


        /*
         this.schools.each(function(school){
         school.el.addClass('inactive');
         });*/

        this.schools.each(function(school){
            school.el.inject(schoolContainer);
        });
    },


    /**
     * Update the schools list
     *
     */
    updateSchools: function () {
        // update the url hash
        var hashUrl = '';
        for (var key in this.filters) {
            var value = this.filters[key];
            if (typeof value != 'object' || (typeof value == 'object' && value.length)) {
                hashUrl = hashUrl + (hashUrl ? '&' : '') + key + '=' + JSON.encode(value);
            }
        }
        if(!hashUrl)
            hashUrl = '';
        window.location.hash = hashUrl;



        var validSchools = this.schools;
        validSchools.each(function (school, index) {
            school.el.removeClass('inactive');
        });

        for (var key in this.filters) {
            var value = this.filters[key];
            if (typeof value != 'object' || (typeof value == 'object' && value.length)) {

                switch (key) {
                    case 'age':
                        validSchools.each(function (school, index) {
                            if (!school.el.hasClass('inactive')) {
                                if (school.maximumAge && school.maximumAge < value) {
                                    school.el.addClass('inactive');
                                    return;
                                }
                                if (school.minimumAge && school.minimumAge > value) {
                                    school.el.addClass('inactive');
                                    return;
                                }
                            }
                        }, this);
                        break;
                    case 'language':
                        validSchools.each(function (school, index) {
                            if (!school.el.hasClass('inactive')) {
                                if (school.languages.indexOf(value) === -1) {
                                    school.el.addClass('inactive');
                                }
                            }
                        }, this);
                        break;
                    case 'program':
                        validSchools.each(function (school, index) {
                            if (!school.el.hasClass('inactive')) {
                                if (school.schoolProgramId != value) {
                                    school.el.addClass('inactive');
                                }
                            }
                        }, this);
                        break;
                    case 'accommodationTypes':
                        validSchools.each(function (school, index) {
                            if (!school.el.hasClass('inactive')) {
                                var valid = false;
                                for (var i = 0; i < value.length; i++) {
                                    var acc = value[i];

                                    if (school.accommodationsTypes.indexOf(acc) !== -1) {
                                        valid = true;
                                    }

                                }
                                if (!valid && value.length) {
                                    school.el.addClass('inactive');
                                }
                            }

                        }, this);

                        break;
                    case 'accommodationRoomTypes':

                        validSchools.each(function (school, index) {
                            if (!school.el.hasClass('inactive')) {
                                var valid = false;
                                for (var i = 0; i < value.length; i++) {
                                    var roomType = value[i];

                                    if (school.accommodationRoomTypes.indexOf(roomType) !== -1) {
                                        valid = true;
                                    }
                                }
                                if (!valid && value.length) {
                                    school.el.addClass('inactive');
                                }
                            }

                        }, this);

                        break;
                    case 'accommodationMeals':
                        validSchools.each(function (school, index) {
                            if (!school.el.hasClass('inactive')) {
                                var valid = false;
                                for (var i = 0; i < value.length; i++) {
                                    var meal = value[i];
                                    if (school.accommodationMeal.indexOf(meal) !== -1) {
                                        valid = true;
                                    }
                                }
                                if (!valid && value.length) {
                                    school.el.addClass('inactive');
                                }
                            }

                        }, this);


                        break;
                    case 'accommodationBathroom':


                        for (var i = 0; i < value.length; i++) {
                            var bathroomType = value[i];
                            validSchools.each(function (school, index) {
                                if (!school.el.hasClass('inactive')) {
                                    if (school.accommodationBathrooms.indexOf(bathroomType) === -1) {
                                        school.el.addClass('inactive');
                                    }
                                }
                            }, this);
                        }
                        break;

                    // this works like a or for each values
                    case 'accommodationInternet':
                        validSchools.each(function (school, index) {
                            if (!school.el.hasClass('inactive')) {
                                var valid = false;
                                for (var i = 0; i < value.length; i++) {
                                    var internetType = value[i];

                                    if (school.accommodationInternet.indexOf(internetType) !== -1) {
                                        valid = true;
                                    }
                                }
                                if (!valid && value.length) {
                                    school.el.addClass('inactive');
                                }
                            }

                        }, this);

                        break;

                    case 'activities':
                        for (var i = 0; i < value.length; i++) {
                            var activity = value[i];
                            validSchools.each(function (school, index) {
                                if (!school.el.hasClass('inactive')) {
                                    if (school.categories.indexOf(activity) === -1) {
                                        school.el.addClass('inactive');
                                    }
                                }
                            }, this);
                        }
                        break;
                    case 'courseTypes':
                        for (var i = 0; i < value.length; i++) {
                            var courseType = value[i];
                            validSchools.each(function (school, index) {
                                if (!school.el.hasClass('inactive')) {
                                    if (school.coursesTypes.indexOf(courseType) === -1) {
                                        school.el.addClass('inactive');
                                    }
                                }
                            }, this);
                        }
                        break;
                    case 'startDate':
                    case 'flexibility':
                        if (!this.filters.startDate)
                            break;
                        var flexibility = this.filters.flexibility ? this.filters.flexibility : 0;
                        var dateSplit = this.filters.startDate.split('/');
                        var date = dateSplit[2] + '-' + dateSplit[0] + '-' + dateSplit[1];
                        var dates = [date];

                        if (flexibility) {
                            var downDate = new Date(dateSplit[2], (dateSplit[0] - 1), dateSplit[1]);
                            var upDate = new Date(dateSplit[2], (dateSplit[0] - 1), dateSplit[1]);

                            for (var i = 1; i <= flexibility; i++) {
                                downDate.setDate(downDate.getDate() - 1);
                                upDate.setDate(upDate.getDate() + 1);
                                dates.push(downDate.getFullYear() + '-' + ((downDate.getMonth() + 1) > 9 ? '' : '0') + (downDate.getMonth() + 1) + '-' + ((downDate.getDate() > 9) ? '' : '0' ) + downDate.getDate());
                                dates.push(upDate.getFullYear() + '-' + ((upDate.getMonth() + 1) > 9 ? '' : '0') + (upDate.getMonth() + 1) + '-' + ((upDate.getDate() > 9) ? '' : '0' ) + upDate.getDate());
                            }


                            validSchools.each(function (school, index) {
                                if (!school.el.hasClass('inactive')) {
                                    var isValid = false;

                                    dates.each(function (startDate) {
                                        if (school.startDates.indexOf(startDate) != -1) {
                                            isValid = true;
                                            return true;
                                        }
                                    });

                                    if (isValid) {
//                                        school.el.removeClass('inactive');
                                    } else {
                                        school.el.addClass('inactive');
                                    }
                                }
                            }, this);


                        } else {

                            validSchools.each(function (school, index) {
                                if (!school.el.hasClass('inactive')) {
                                    var isValid = false;
                                    if (school.startDates.indexOf(date) != -1)
                                        isValid = true;


                                    if (isValid) {
//                                        school.el.removeClass('inactive');
                                    } else {
                                        school.el.addClass('inactive');
                                    }
                                }
                            }, this);
                        }

                        break;
                    case 'duration':
                        validSchools.each(function (school, index) {
                            if (!school.el.hasClass('inactive')) {
                                if (school.maxDuration && school.maxDuration < value) {
                                    school.el.addClass('inactive');
                                    return;
                                }
                                if (school.minDuration && school.minDuration > value) {
                                    school.el.addClass('inactive');
                                    return;
                                }
                            }
                        }, this);
                        break;
                    case 'price':
                        var minValue = value[0];
                        var maxValue = value[1];
                        var currency = this.filters.currency ? this.filters.currency : 'EUR';
                        validSchools.each(function (school, index) {
                            if (!school.el.hasClass('inactive')) {
                                var schoolValidCurrency = false;
                                school.minPricePerWeek.each(function (price, index) {
                                    if (price.currency == currency) {
                                        schoolValidCurrency = true;
                                        if (price.minPricePerWeek < minValue) {
                                            school.el.addClass('inactive');
                                            return;
                                        }
                                        if (price.minPricePerWeek > maxValue) {
                                            school.el.addClass('inactive');
                                            return;
                                        }
                                    }
                                });

                                // if the school doesn't has a valid currency it's hidden
                                if (!schoolValidCurrency) {
                                    school.el.addClass('inactive');
                                }
                            }
                        }, this);
                        break;
                    case 'countries':
                        validSchools.each(function (school, index) {
                            var isValid = false;

                            if (value && value.length) {
//                                if (school.el.hasClass('inactive')) {
                                if (value.indexOf(school.countryCode) != -1) {
                                    isValid = true;
                                }
//                                }
                            } else {
                                isValid = true;
                            }

                            if (isValid && value.length) {
//                                school.el.removeClass('inactive');
                            } else {
                                school.el.addClass('inactive');
                            }

                        }, this);


                        break;
                    case 'cities':
                        validSchools.each(function (school, index) {
                            var isValid = false;

                            if (value && value.length) {
//                                if (school.el.hasClass('inactive')) {
                                if (value.indexOf(school.cityName) != -1) {
                                    isValid = true;
                                }
//                                }
                            } else {
                                isValid = true;
                            }

                            if (isValid && value.length) {
//                                school.el.removeClass('inactive');
                            } else {
                                school.el.addClass('inactive');
                            }

                        }, this);


                        break;
                }
            }

        }

        this.fireEvent('change');

    }

});