﻿KGetter = function(container){

    this._cn = $(container);
    var self = this;
    
    //default
    var IMG_PATH = '../web_i/img/';
    var IMGT_PATH = '../web_i/img_thumb/';
    var PHP_PATH = './';
    
    this.query = {
        mode: '',
        page: 0, //!!
        room1: false,
        room2: false,
        room3: false,
        roommore: false,
        priceFrom: 0,
        priceTo: 0,
        distanceFrom: 0,
        distanceTo: 0,
        spaceFrom: 0,
        spaceTo: 0,
        keywords: '',
        only_pict: false,
        district: '',
        err: '',
        sale: 0 //0-продажа, 1 -аренда
    };
    
    this.init = function(){
        this.showLoading(false);
        this.showMsg(false);
        this._cn.find('#fsRoom ul li').addClass('roomUnselected');
        this._cn.find('#fsRoom ul li').bind('click', function(event){
            $(event.target).toggleClass('roomSelected');
        });
        this._cn.find('#img_sort').bind('click', function(event){
            self.showSort(!self.sortDesc());
        });
        this._cn.find('.rPane #run').bind('click', function(event){
            
            self.init_query();
            
            if (self.query.err) {
                alert(self.query.err);
                return;
            }
            self.sendRequest();
        });
        
        this.reset();
        
        this.PG = new Page_pane(this._cn.find('#nav_pane'), 20);
        this.PG.init();
        this.PG.onPageChange = function(p){
            self.query.page = p.page;
            self.sendRequest();
        }
    }
    
    this.pushRun = function(){
        this._cn.find('.rPane #run').trigger('click');
    }
    
    //mode: 'h' Дом, 'l' Земельный участок, 'a1' Квартира (жилая), 'a0' Квартира (новостройка)... g i b
    //		'c' Коммерческая
    //autorun - сразу же нажать кнопку найти
    this.setMode = function(mode, autorun){
        this.query.mode = mode;
        //init menu
        switch (mode) {
            case 'h':
            case 'l':
                this._cn.find('#fsRoom').hide();
                this._cn.find('#fsCPart').hide();
                this._cn.find('#fsDistance').show();
                break;
            case 'c':
                this._cn.find('#fsRoom').hide();
                this._cn.find('#fsCPart').show();
                this._cn.find('#fsDistance').hide();
                break;
            case 'a0':
            case 'a1':
                this._cn.find('#fsDistance').hide();
                this._cn.find('#fsCPart').hide();
                this._cn.find('#fsRoom').show();
                break;
            case 'g':
                this._cn.find('#fsRoom').hide();
                this._cn.find('#fsCPart').hide();
                this._cn.find('#fsDistance').hide();
                break;
            case 'i':
            case 'b':
                this._cn.find('#fsRoom').hide();
                this._cn.find('#fsCPart').hide();
                this._cn.find('#fsDistance').hide();
                break;
        }
        this.setDistricts([]);
        
        var sq = PHP_PATH + '_q_district.php?estate_type=' + this.estate(false);
        
        $.ajax({
            url: sq,
            success: function(data, textStatus, jqXHR){
                var d;
                try {
                    eval('d = ' + jqXHR.responseText);
                } 
                catch (e) {
                    d = null;
                }
                self.setDistricts(d ? d.items || [] : []);
            }
        });
        
        if (autorun) 
            this.pushRun();
    }
    
    //sale mode: 0-продажа, 1-аренда
    this.setSaleMode = function(smode){
        this.query.sale = smode;
    }
    
    this.setDistricts = function(adistricts){
        var d = this._cn.find('#district');
        var t = '<option selected="" value="">Все</option>';
        for (var i = 0; i < adistricts.length; i++) 
            t += '<option value="' + adistricts[i] + '">' + adistricts[i] + '</option>';
        d.html(t);
    }
    
    this.reset = function(){
        this._cn.find('.resPane').hide();
        this._cn.find('#priceFrom').val('');
        this._cn.find('#priceTo').val('');
        this._cn.find('#distanceFrom').val('');
        this._cn.find('#distanceTo').val('');
        this._cn.find('#spaceFrom').val('');
        this._cn.find('#spaceTo').val('');
        this._cn.find('#keywords').val('');
        this._cn.find('#keywords').val('');
        this._cn.find('#district').val('');
    }
    
    //true if precheck
    this.init_query = function(){
        with (this.query) {
            page = 0;//!!
            room1 = false;
            room2 = false;
            room3 = false;
            roommore = false;
            priceFrom = 0;
            priceTo = 0;
            distanceFrom = 0;
            distanceTo = 0;
            spaceFrom = 0;
            spaceTo = 0;
            keywords = '';
            only_pict = false;
            district = '';
            err = '';
        }
        var ns = [{
            o: 'priceFrom',
            c: 'Цена от'
        }, {
            o: 'priceTo',
            c: 'Цена до'
        }, {
            o: 'spaceFrom',
            c: 'Площадь от'
        }, {
            o: 'spaceTo',
            c: 'Площадь до'
        }];
        switch (this.query.mode) {
            case 'h':
            case 'l':
                ns = ns.concat([{
                    o: 'distanceFrom',
                    c: 'Расстояние от'
                }, {
                    o: 'distanceTo',
                    c: 'Расстояние до'
                }]);
                break;
            case 'a0':
            case 'a1': //rooms
                this._cn.find('#fsRoom li').each(function(){
                    if ($(this).hasClass('roomSelected')) 
                        self.query['room' + this.id] = true;
                });
                break;
        }
        
        //check inputs
        for (var i = 0; i < ns.length; i++) {
            var x = ns[i];
            var g = getNum(this._cn.find('#' + x.o).val(), x.c);
            if (g.err) {
                this.query.err = g.err;
                return;
            }
            this.query[x.o] = g.n;
        }
        this.query.keywords = this._cn.find('#keywords').val();
        this.query.only_pict = Boolean(this._cn.find('#only_pict:checked').val());
        this.query.district = this._cn.find('#district').val();
    }
    
    this.estate = function(ext_c){
        switch (this.query.mode) {
            case 'h':
                return encodeURI('Дом');
            case 'l':
                return encodeURI('Земельный участок');
            case 'a0':
                return encodeURI('Квартира (новостройка)');
            case 'a1':
                return encodeURI('Квартира (жилая)');
            case 'g':
                return encodeURI('Гаражи');
            case 'i':
                return encodeURI('Инвестиции');
            case 'b':
                return encodeURI('Готовый бизнес');
            case 'c':
                return ext_c ? encodeURI(this._cn.find('#cpart').val()) : 'c';
            default:
                return '';
        }
    }
    
    this.sendRequest = function(){
    
        if (this.requestD) 
            this.requestD.abort();
        
        this.showLoading(true);
        
        var st = this.estate(true);
        if (!st) 
            return;
        
        var sq = PHP_PATH + '_q.php?estate_type=' + st;
        var f = '';
        if (this.query.priceFrom > 0) 
            f += 'a.price>=' + this.query.priceFrom;
        if (this.query.priceTo > 0) 
            f += (f ? ' and ' : '') + 'a.price<=' + this.query.priceFrom;
        if (this.query.distanceFrom > 0) 
            f += 'a.distance_to_city>=' + this.query.distanceFrom;
        if (this.query.distanceTo > 0) 
            f += (f ? ' and ' : '') + 'a.distance_to_city<=' + this.query.distanceTo;
        if (this.query.spaceFrom > 0) 
            f += (f ? ' and ' : '') + 'a.total_floor_space>=' + this.query.spaceFrom;
        if (this.query.spaceTo > 0) 
            f += (f ? ' and ' : '') + 'a.total_floor_space<=' + this.query.spaceTo;
        //
        if (this.query.room1 || this.query.room2 || this.query.room3 || this.query.roommore) {
            f += (f ? ' and ' : '') + '(';
            var fr = this.query.roommore ? 'a.room_quantity>3' : '';
            var fr3 = this.query.room1 ? '1' : '';
            if (this.query.room2) 
                fr3 += (fr3 ? ',' : '') + '2';
            if (this.query.room3) 
                fr3 += (fr3 ? ',' : '') + '3';
            f += fr + (fr3 ? (fr ? ' or ' : '') + ' a.room_quantity in(' + fr3 + ')' : '');
            f += ')';
        }
        //
        if (this.query.district) 
            sq += '&district=' + encodeURI(this.query.district);
        
        if (f) 
            sq += '&filter=' + f;
        if (this.query.keywords) 
            sq += '&keywords=' + encodeURI(this.query.keywords);
        if (this.query.only_pict) 
            sq += '&only_pict=1';
        sq += '&order=' + this.sortField();
        if (this.sortDesc()) 
            sq += '&ordertype=desc';
        
        if (this.query.sale != 0) 
            sq += '&sale=' + this.query.sale;
        
        if (this.query.page > 0) 
            sq += '&page=' + this.query.page;
        
        $.ajax({
            url: sq,
            complete: function(jqXHR, textStatus){
                self.showLoading(false);
                //self.PG.set(0);
            },
            success: function(data, textStatus, jqXHR){
                var d;
                try {
                    eval('d = ' + jqXHR.responseText)
                } 
                catch (e) {
                    d = null;
                }
                self.onQueryDone(d);
            }
        });
    }
    
    this.resData = {}; //test
    this.onQueryDone = function(data){
        this.showLoading(false);
        var _rp = this._cn.find('.resPane');
        _rp.children().remove().empty();
        if (data.err) {
            this.showMsg(data.err);
            _rp.hide();
            this.PG.set(0);
        }
        else {
            this.showMsg(false);
            if (this.query.page == 0) 
                this.PG.set(data.totalCount);
            
            //render
            var af = [{
                o: 'price',
                c: 'Цена'
            }, {
                o: 'first_pic',
                c: 'Фото'
            }, {
                o: 'note',
                c: 'Заголовок'
            }, {
                o: 'district',
                c: 'Район'
            }, {
                o: 'total_floor_space',
                c: 'Общая площадь'
            }, {
                o: 'street',
                c: 'Улица'
            }, {
                o: 'room_quantity',
                c: 'Комнат'
            }];
            switch (this.query.mode) {
                case 'h':
                case 'l':
                    af = af.concat([{
                        o: 'distance_to_city',
                        c: 'Расстояние до города'
                    }]);
                    break;
                case 'a0':
                case 'a1':
                    af = af.concat([{
                        o: 'floor',
                        c: 'Этаж'
                    }]);
                    break;
            }
            af = af.concat([{
                o: 'adate',
                c: 'Дата'
            }]);
            var t = '<table class="tresList"><thead><tr>';
            for (var i = 0; i < af.length; i++) 
                t += '<th>' + af[i].c + '</th>';
            t += '</tr></thead>';
            t += '<tbody>';
            for (var i = 0; i < data.items.length; i++) {
                var rec = data.items[i];
                t += '<tr ' + (i % 2 == 0 ? 'class="even"' : '') + ' id="' + rec.id + '">';
                for (var j = 0; j < af.length; j++) {
                    var v = rec[af[j].o];
                    if (v) {
                        switch (af[j].o) {
                            case 'first_pic':
                                v = '<img src="' + IMGT_PATH + 't' + v + '">';
                                break;
                            case 'note':
                                v = (rec.special_proposal || rec.note);
                                break;
                            case 'adate':
                                v = '<nobr>' + v + '</nobr>';
                                break;
                        }
                    }
                    else 
                        v = '';
                    t += '<td>' + v + '</td>';
                }
                t += '</tr>';
            }
            t += '</tbody></table>';
            t += '<div id="resDetails">';
            t += '</div>';
            _rp.html(t);
            _rp.find('.tresList tbody td').bind('click', function(event){
                var id = $(event.target).parents('tr').attr('id');
                self.showDetails(id);
            });
            _rp.show();
            _rp.find('#resDetails').hide();
        }
        
        this.resData = data;
    }
    
    this.requestD = null;
    
    this.showDetails = function(id){
    
        if (this.requestD) 
            this.requestD.abort();
        
        this._cn.find('.tresList').hide();
        var d = this._cn.find('#resDetails');
        var t = '<table class="tresD"><tr><td><div id="pict_prev"></div></td><td>'; //*
        t += '<table class="tresDetails">';
        t += '<thead><tr><th colspan="2"><button id="toList">К списку</button></th></tr></thead>';
        t += '<tbody></tbody></table>';
        t += '</td></tr></table>'; //*
        this._cn.find('#resDetails').html(t).show();
        this._cn.find('#toList').bind('click', function(event){
            self._cn.find('#resDetails').hide();
            self._cn.find('.tresList').show();
        });
        
        this.requestD = $.ajax({
            url: PHP_PATH + '_qd.php?id=' + id,
            success: function(data, textStatus, jqXHR){
                var d;
                try {
                    eval('d = ' + jqXHR.responseText);
                } 
                catch (e) {
                    d = null;
                }
                self.onQueryDoneD(d);
            }
        });
    }
    
	//slide
	/*
	this.slider = function(){
		if (!this._slider) 
			this._slider = new Slider();
		return this._slider;
	}
	this._slider=null;
	*/
	
    this.onQueryDoneD = function(data){
        if (data && data.fields) {
			var dt = this._cn.find('.tresDetails tbody');
			var t = '';
			for (var i = 0; i < data.fields.length; i++) {
				t += '<tr ' + (i % 2 == 0 ? 'class="even"' : '') + '>';
				t += '<td>' + data.fields[i].c + '</td>';
				t += '<td>' + data.fields[i].v + '</td>';
				t += '</tr>';
			}
			dt.html(t);
			var dp = this._cn.find('#pict_prev');
			t = '';
			//var s = this.slider();
			//s.clear();
			if (data.pictures) {
				for (var i = 0; i < data.pictures.length; i++) {
					//s.addPicture(IMG_PATH + data.pictures[i]);
					//t += '<p class="pict_item"><img src="' + IMGT_PATH + 't' + data.pictures[i] + '"></p>';

                    t += '<p align="center"><a href="' + IMG_PATH + data.pictures[i] + '" target="blank">';
                    t += '<img src="' + IMGT_PATH + 't' + data.pictures[i] + '"></a></p>';
				}
			}
			dp.html(t);
//			$('img', dp).each(function(no){
//				$(this).click(function(){
//					//s.show(no);
//				})
//			});
			
			dp.height(this._cn.find('.tresDetails').height());
		}
    }
    
    this.showMsg = function(value){
        var p = self._cn.find('#msg_pane');
        if (value) {
            p.text(value);
            p.show();
        }
        else 
            p.hide();
    }
    
    this.showLoading = function(value){
        var p = this._cn.find('#img_loading');
        if (value) {
            p.fadeIn('fast');
        }
        else 
            p.hide();
    }
    this.showSort = function(desc){
        this._cn.find('#img_sort').attr('src', 'img/' + (desc ? 'desc' : 'asc') + '.jpg');
    }
    this.sortDesc = function(){
        return this._cn.find('#img_sort').attr('src') == 'img/desc.jpg';
    }
    this.sortField = function(){
        return this._cn.find('#sort option:selected').val();
    }
    
    
}

function getNum(v, capt){
    if (!v) 
        return {
            n: 0
        };
    var n = Number(v);
    return isNaN(n) ? {
        err: 'Неверно указан параметр [' + capt + ']'
    } : {
        n: n
    };
}


