﻿var filter = {
    source: null,
    cities: null,
    neighborhoods: null,
    types: null,
    metrics: null,
    allProps: new Array(),
    allPropsRange: new Array(),
    propsRange: null,
    paramsRange: null,
    tempRange: null,

    init: function() {
        this.cities = new BaseObject();
        this.neighborhoods = new BaseObject();
        this.types = new Type();
        this.metrics = new Object();
        this.metrics.option = new Object();
        this.metrics.option[1] = { "value": 1, "label": "0 - 100m²" };
        this.metrics.option[2] = { "value": 2, "label": "101 - 200m²" };
        this.metrics.option[3] = { "value": 3, "label": "201 - 300m²" };
        this.metrics.option[4] = { "value": 4, "label": "301 - 400m²" };
        this.metrics.option[5] = { "value": 5, "label": "401 - 500m²" };
        this.metrics.option[6] = { "value": 6, "label": "Acima de 500m²" };

        $.getJSON(structure.baseUrl + 'imoveis/itens.aspx', function(json) {
            filter.source = json;
            filter.mount();
        });
    },

    mount: function() {

        this.cities.dom = $('.city select').eq(0);
        this.cities.addDomOption(0, "Selecione");

        this.neighborhoods.dom = $('.neighborhood select').eq(0);
        this.neighborhoods.addDomOption(0, "Selecione");

        this.types.dom = $('.type select').eq(0);
        this.types.addDomOption(0, "Selecione");

        $.each(this.source, function(i, item) {
            //---
            filter.allPropsRange.push(item.Identifier);
            filter.allProps.push({ "ID": item.Identifier, "cityID": item.IdCidade, "city": item.NomeCidade, "neibID": item.IdBairro, "neib": item.NomeBairro, "typeID": item.IdTipoImovel, "type": item.NomeTipoImovel, "metrics": item.MetrosQuadradosCorrigido });
            //---
            var city = filter.cities.getByID(item.IdCidade);
            if (city == null) {
                city = filter.cities.add(item.Identifier, item.IdCidade, item.NomeCidade, item.Identifier);
            } else {
                city.props.push(item.Identifier);
            }
            //---
            var neighborhood = filter.neighborhoods.getByID(item.IdBairro);
            if (neighborhood == null) {
                neighborhood = filter.neighborhoods.add(item.Identifier, item.IdBairro, item.NomeBairro, item.IdCidade);
            } else {
                neighborhood.props.push(item.Identifier);
            }
            //---
            var type = filter.types.getByID(item.IdTipoImovel);
            if (type == null) {
                type = filter.types.add(item.Identifier, item.IdTipoImovel, item.NomeTipoImovel);
            } else {
                type.props.push(item.Identifier);
            }
            //---

            filter.metrics[item.Identifier] = item.MetrosQuadradosCorrigido;
        });

        this.propsRange = this.allPropsRange;
        this.updateCount(this.propsRange.length);

        $('.btnShow').attr('href', 'javascript:;');
        $('.btnShow').bind('click', function(e) {
            var ids = new Array();
            ids.push(filter.cities.current);
            ids.push(filter.neighborhoods.current);
            ids.push(filter.types.current);
            ids.push($('#selArea').val());

            var baseUrl = structure.baseUrl + 'imoveis/?p={0}&i={1}';
            var url = baseUrl.replace('{0}', filter.propsRange.join('-')).replace('{1}', ids.join('-'));

            document.location.href = url;
        });

        this.configureApp();
    },

    configureApp: function() {
        this.cities.dom.bind('change', function(e) {
            filter.cities.current = this.value;

            if (filter.cities.getByID(this.value) == null) {
                filter.propsRange = filter.allPropsRange;
            } else {
                filter.propsRange = filter.cities.getByID(this.value).props;
            }

            var neighborhoods = filter.neighborhoods.listByDetailID(this.value);

            if (neighborhoods == undefined) {
                filter.neighborhoods.dom.attr('disabled', 'disabled');
                filter.neighborhoods.current = 0;
                filter.neighborhoods.clear();

                filter.propsRange = filter.allPropsRange;
            } else {
                filter.neighborhoods.mountByDetailID(this.value);
                filter.neighborhoods.dom.removeAttr('disabled');
                filter.propsRange = filter.cities.getByID(this.value).props;
            }

            filter.updateCount(filter.propsRange.length);

            filter.types.dom.attr('disabled', 'disabled');
            filter.types.current = 0;
            filter.types.clear();

            $('#selArea').attr('disabled', 'disabled');
            $('#selArea option').eq(0).attr('selected', 'selected');

            return false;
        });
        //---
        this.neighborhoods.dom.attr('disabled', 'disabled');
        this.neighborhoods.dom.bind('change', function(e) {

            filter.neighborhoods.current = this.value;

            if (filter.neighborhoods.current == 0) {
                filter.cities.dom.trigger('change');
            }
            else {

                var currTypes = new Array();

                filter.propsRange = filter.neighborhoods.getByID(this.value).props;
                filter.types.clear();

                $.each(filter.allProps, function(i, item) {

                    if (item.neibID == filter.neighborhoods.current) {

                        var itemExists = false;

                        for (var j = 0; j < currTypes.length; j++) {
                            if (currTypes[j].typeID == item.typeID) itemExists = true;
                        }

                        if (!itemExists) {
                            currTypes.push({ 'typeID': item.typeID, 'type': item.type });
                            filter.types.addDomOption(item.typeID, item.type);
                        }
                    }
                });

                filter.updateCount(filter.propsRange.length);
                filter.types.dom.removeAttr('disabled');
            }
        });
        //---
        this.types.dom.attr('disabled', 'disabled');
        this.types.dom.bind('change', function(e) {

            filter.types.current = this.value;

            if (filter.types.current == 0) {
                filter.neighborhoods.dom.trigger('change');
                $('#selArea').attr('disabled', 'disabled');
            }
            else {
                $('#selArea').removeAttr('disabled');

                filter.propsRange = new Array();

                $.each(filter.allProps, function(i, item) {
                    if (item.typeID == filter.types.current && item.neibID == filter.neighborhoods.current) {
                        filter.propsRange.push(item.ID)
                    }
                });

                filter.updateCount(filter.propsRange.length);
                filter.tempRange = filter.propsRange;
            }

            var optMetrics = new Array();
            var optAddeds = new Object();

            optMetrics.push('0,Selecione');

            for (var i = 0; i < filter.propsRange.length; i++) {
                var _item = filter.propsRange[i];

                for (var j = 0; j < filter.metrics[_item].length; j++) {
                    var item = filter.metrics[filter.propsRange[i]][j];

                    if (item >= 0 && item <= 100) {
                        if (optAddeds[1] != true) {
                            optMetrics.push(filter.metrics.option[1].value + "," + filter.metrics.option[1].label);
                            optAddeds[1] = true;
                        }
                    }
                    else if (item >= 101 && item <= 200) {
                        if (optAddeds[2] != true) {
                            optMetrics.push(filter.metrics.option[2].value + "," + filter.metrics.option[2].label);
                            optAddeds[2] = true;
                        }
                    }
                    else if (item >= 201 && item <= 300) {
                        if (optAddeds[3] != true) {
                            optMetrics.push(filter.metrics.option[3].value + "," + filter.metrics.option[3].label);
                            optAddeds[3] = true;
                        }
                    }
                    else if (item >= 301 && item <= 400) {
                        if (optAddeds[4] != true) {
                            optMetrics.push(filter.metrics.option[4].value + "," + filter.metrics.option[4].label);
                            optAddeds[4] = true;
                        }
                    }
                    else if (item >= 401 && item <= 500) {
                        if (optAddeds[5] != true) {
                            optMetrics.push(filter.metrics.option[5].value + "," + filter.metrics.option[5].label);
                            optAddeds[5] = true;
                        }
                    }
                    else if (item >= 501 && item <= 100000) {
                        if (optAddeds[6] != true) {
                            optMetrics.push(filter.metrics.option[6].value + "," + filter.metrics.option[6].label);
                            optAddeds[6] = true;
                        }
                    }
                }
            }

            optMetrics.sort();

            $('#selArea').html('');

            $.each(optMetrics, function(i, item) {
                var option = $(document.createElement('option'));
                option.text(item.split(',')[1]);
                option.val(item.split(',')[0]);
                $('#selArea').append(option);
            });

            $('#selArea option').eq(0).attr('selected', 'selected');
        });

        $('#selArea').attr('disabled', 'disabled');
        $('#selArea option').eq(0).attr('selected', 'selected');
        $('#selArea').bind('change', function(e) {

            var thisValue = this.value;

            filter.propsRange = filter.tempRange;

            if (thisValue > 0) {
                var tempRange = filter.propsRange;
                filter.propsRange = new Array();

                $.each(tempRange, function(i, item) {
                    var addThisProp = false;
                    var valInit = 0;
                    var valEnd = 0;

                    $.each(filter.getPropById(item).metrics, function(j, jItem) {

                        if (thisValue == 1) {
                            valInit = 0;
                            valEnd = 100;
                        }
                        else if (thisValue == 2) {
                            valInit = 101;
                            valEnd = 200;
                        }
                        else if (thisValue == 3) {
                            valInit = 201;
                            valEnd = 300;
                        }
                        else if (thisValue == 4) {
                            valInit = 301;
                            valEnd = 400;
                        }
                        else if (thisValue == 5) {
                            valInit = 401;
                            valEnd = 500;
                        }
                        else if (thisValue == 6) {
                            valInit = 501;
                            valEnd = 100000;
                        }

                        if (jItem >= valInit && jItem <= valEnd) addThisProp = true;
                    });

                    if (addThisProp == true) filter.propsRange.push(item);
                });

                filter.updateCount(filter.propsRange.length);
            }
            else {
                filter.types.dom.trigger('change');
            }
        });
    },

    getPropById: function(id) {
        var retValue;
        $.each(this.allProps, function(i, item) {
            if (item.ID == id) {
                retValue = item;
                return;
            }
        });

        return retValue;
    },

    updateCount: function(value) {
        $('.numPropertiesFound').eq(0).text(value);
        $('.txtPropertiesFound').eq(0).text(value == 1 ? 'Imóvel encontrado' : 'Imóveis encontrados');
    }
}

function sortSelect(selectToSort) {
    jQuery(selectToSort.options).sort(function(a, b) {
        return a.value > b.value ? 1 : -1;
    });
}

var Type = function() {
    this.dom = null,
	this.items = new Array();
    this.dItems = new Object();
    this.props = new Array();
    current: null,

	this.getByID = function(id) {
	    return this[id] == undefined ? null : this[id];
	},

	this.getByLabel = function(label) {
	    return this[label.toLowerCase()] == undefined ? null : this[label.toLowerCase()];
	},

	this.listByDetailID = function(id) {
	    return this.dItems[id] == undefined ? null : this.dItems[id];
	},

	this.add = function(_propId, _id, _label) {
	    var item = { id: _id, label: _label, props: [_propId] };

	    this[_id] = this[_label.toLowerCase()] = item;

	    this.items.push(item);

	    this.addDomOption(_id, _label);

	    return item
	},

	this.mountByDetailID = function(detailID) {
	    this._mount(this.dItems[detailID]);
	},

	this.addDomOption = function(_id, _label) {
	    var option = $(document.createElement('option'));
	    option.text(_label);
	    option.val(_id);
	    this.dom.append(option);
	},

	this.mount = function() {
	    this._mount(this.items);
	},

	this.clear = function() {
	    this.dom.html('');
	    this.addDomOption(0, 'Selecione');
	},

	this._mount = function(items) {
	    this.dom.html('');
	    this.addDomOption(0, 'Selecione');
	    for (i in items) {
	        this.addDomOption(items[i].id, items[i].label);
	    }
	}
}

var BaseObject = function() {
    this.dom = null,
	this.items = new Array();
    this.dItems = new Object();
    this.props = new Array();
    this.current = 0;

    this.getByID = function(id) {
        return this[id] == undefined ? null : this[id];
    },

	this.getByLabel = function(label) {
	    return this[label.toLowerCase()] == undefined ? null : this[label.toLowerCase()];
	},

	this.listByDetailID = function(id) {
	    return this.dItems[id] == undefined ? null : this.dItems[id];
	},

	this.add = function(_propId, _id, _label, _detailID) {
	    var item = { id: _id, label: _label, detailID: _detailID, props: [_propId] };

	    this[_id] = this[_label.toLowerCase()] = item;

	    this.items.push(item);

	    if (this.dItems[_detailID] == undefined) this.dItems[_detailID] = new Array();
	    this.dItems[_detailID].push(item)

	    this.addDomOption(_id, _label);

	    return item
	},

	this.mountByDetailID = function(detailID) {
	    this._mount(this.dItems[detailID]);
	},

	this.addDomOption = function(_id, _label) {
	    var option = $(document.createElement('option'));
	    option.text(_label);
	    option.val(_id);
	    this.dom.append(option);
	},

	this.mount = function() {
	    this._mount(this.items);
	},

	this.clear = function() {
	    this.dom.html('');
	    this.addDomOption(0, 'Selecione');
	},

	this._mount = function(items) {
	    this.dom.html('');
	    this.addDomOption(0, 'Selecione');
	    for (i in items) {
	        this.addDomOption(items[i].id, items[i].label);
	    }
	}
}

var Metric = function() {
    this.dom = null,
	this.items = new Array();
    this.labels = new Object();

    this.getByLabel = function(label) {
        return labels[label];
    },

	this.add = function(_label, _beginValue, _endValue) {
	    var item = new Object();
	    item.label = _label;
	    item.beginValue = _beginValue;
	    item.endValue = _endValue;

	    this.labels[_label] = item;
	    this.items.push(item);
	},

	this.has = function(label) {
	    return this.labels[label] != undefined;
	}
}

