
var Search = Class.create();
Search.prototype = {

    sr: null,
    sw: null,

    el_result_block: null,
    el_loader: null,


    s_field: null, s_str: null,

    loading: false,

    initialize: function(params){

        // поля формы
        this.sw = new swicthFields( params.swicth_fields );
        // форма
        this.form = $( params.form );
        this.form.onsubmit = Delegate.create(this, this.on_submit);
        // таблица результатов
        this.sr = new search_result({
            list_id: params.result_list,
            item_id: params.result_item,
            paging_id: params.result_paging,
            count_id: params.result_count
        });

        this.sr.parent = this;

        this.el_result_block = $( params.result_block );
        this.el_loader = $( params.loader );
    },







    on_submit: function(){

        var radio = this.sw.cur_radio;
        var text = this.sw.cur_text;

        if( !radio || text.value == text.title ){
            alert ("Чего ищем?");
            return false;
        }

        this.s_field = radio.value;
        this.s_str = text.value;

        this.send(1);
        // форму не сабмитем
        return false;
    },









    send: function(event, page){
        if( this.loading ) alert('Ваш запрос обрабатывается.')
        if( !page ) page = event; // IE
        this.loading = true;

        // прячем блок результатов и показываем загруЩик
        this.el_result_block.hide();
        cur.attach('/media/img/loader.gif', 'загрузка...');
        //
        //alert('field=' + this.s_field + ', str=' + this.s_str + ', page=' + page);

        // делаем запрос
        var obj = this;
        new Ajax.Request('/ajax/search', {
            method: 'post',
            parameters: { field: this.sw.cur_radio.value, str: this.sw.cur_text.value, page: page },
            onSuccess: function(transport) {
                obj.on_load(transport.responseText);
            },
            onFailure: function(transport) { obj.on_load(false); },
            onException: function(transport) { obj.on_load(false); }
        });

        // для ссылки
        return false;
    },






    on_load: function(str){
        this.loading = false;
        cur.reset();

        if( str == false ){
            alert('ошибка запроса');
            return;
        }
/*
        // формат:
        var obj = {
            info:{ total_pages: 2, current_page: 1, on_page: 15, total_items: 26},
            items: [
                {id: 1, title: 'Название1', product_id: 'E-95'},
                {id: 2, title: 'Название2', product_id: 'M-80'}
            ]
        };
*/
		if( !str.isJSON() ){
			alert(str);
			return;
		}

        var obj = str.evalJSON();

        this.sr.set_data(obj);
        // показываем блок
        this.el_result_block.show();
    }







}// end class
