/*
 * Компонент FormSender, обеспечивающий лёгкое управление формами, путём html-разметки
 * Параметры:
 * name - уникальное имя экземпляра класса
 * url - url на который шлётся запрос
 * timeout - время на которое появляется сообщение об ошибке или успешной отправки информации
 * onsuccess - действие, которое необходимо выполнить при успешной отправке формы, варианты:
 *           update  - обновить статусное сообщение
 *           replace - скрыть форму и заменить её новым содержимым
 *           refresh - перезагрузить страницу (необходимо для реализации функциональности типа login/logout 
 * before_send - функция, вызывающаяся перед отправкой формы
 * success - функция, вызывающаяся после успешной отправки формы
 * 
 * Элементы формы:
 * name__form    - сама форма
 * name__sender  - элемент по клику на который должна отправляться форма
 * name__message - элемент в который должны выводится статусные сообщения
 * name__replace - элемент, которым будет заменена форма
 * name__loader -  иконка загрузки
 * Компонент поддерживает интеграцию с компонентом Validator
 */
FormSender = function(params) {
    var default_params = $H({
        name: 'fs',
        url: 'vz/save',
        timeout: 2000,
        onsuccess: 'update',
        before_validate: function() {},
        before_send: function() {},
        after_send: function() {return true;},
        success: function() {},
        onenter: false,
        validate_one: false
    });

    this.params = default_params.merge(params).toObject(); 
    this.params.prefix = this.params.name + '__';
    
    this.name = this.params.name;
    
    this.form = $(this.params.prefix + 'form');
    if (!this.form) return;
    
    this.ajax_params = $H();
    
    this.sender = $(this.params.prefix + 'sender');
	this.forenter = $(this.params.prefix + 'forenter');
	this.forenter1 = $(this.params.prefix + 'forenter1');
	//this.inputtext = $$('input[type="text"]');
    this.message = $(this.params.prefix + 'message');
    this.replace = $(this.params.prefix + 'replace');
    this.loader = $(this.params.prefix + 'loader');
    
    this.messageTimer = false;
    
    this.ready_status = true;

    if (this.sender) {
        this.sender.observe('click', this.send.bind(this));
    }	

	if (this.forenter) {	
     this.forenter.observe('keypress', this.keyenter.bind(this));
    }
	
	if (this.forenter1) {    
     this.forenter1.observe('keypress', this.keyenter.bind(this));
    }

	
/*
	   if (this.inputtext) {    
     this.forenter1.observe('keypress', this.keyenter.bind(this));
    }

*/
	
    this.form.onsubmit = this.send.bind(this);
    if (this.params.onenter) {
        this.form.appendChild(new Element('input', {'type':'submit', 'class':'hide'}));
    }
}

FormSender.prototype.keyenter = function(e) {
        var code;
        if (!e) e = window.event;    
        if (e.keyCode) code = e.keyCode;
            else if (e.which) code = e.which;     
        if (code == 13) {
            this.send();
        }	
}


FormSender.prototype.getElement = function(key) {
    return this.form.select('[name="' + key + '"]')[0];
}

FormSender.prototype.setParam = function(param, value) {
    this.params[param] = value;
    return this;
}

FormSender.prototype.send = function() {
    if (!this.ready_status) return;
    
    this.params.before_validate(this);
    
    //Не даём сабмитить placeholder'ы вместо value
    this.form.select('input.placeholder').each(function(e){e.value='';e.removeClassName('placeholder')});
    if ((window.Validator != undefined) && !Validator.validate(this.form, this.params.validate_one)) {            
        this.showMessage(Validator.error_message, false);
        return false;
    }
    this.lock();

    this.params.before_send(this);
    
    var file_inputs = this.form.select('input[type="file"]');
    if (file_inputs.length > 0) {
       var flag = false; 
       for (var i = 0; i < file_inputs.length; i++) {
           if (file_inputs[i].value) flag=true;
       }
       
       if (flag) {
           this.sendFiles();
       } 
       else {
           this.request();
       }
    }
    else {
       this.request();
    }
    
    return false;
}

FormSender.prototype.request = function() {
    request(this.params.url, this.ajax_params.merge(this.form.serialize(true)), this.onSuccess.bind(this));
}

FormSender.prototype.getData = function() {
    return this.form.serialize(true);
}

FormSender.prototype.addParams = function(params) {
    this.ajax_params.update(params);
    return this;
}

FormSender.prototype.sendFiles = function() {
    this.form.select('input[id*="ff__"]').invoke('remove');
    if (this.ifr) this.ifr.remove();

    this.ifr = new Element('iframe', {'class':'hide'});
    var id = this.ifr.identify();
    this.ifr.name = id;
    
    this.form.target = id;
    this.form.method = 'post';
    this.form.action = '/_services/files/save';
    this.form.enctype = 'multipart/form-data';
    this.form.encoding = 'multipart/form-data'; 

    this.form.appendChild(this.ifr);

    this.ifr.observe('load', this.onFileSend.bind(this));
    this.form.submit();
}

FormSender.prototype.onFileSend = function() {
    var response = getIFrameBody(this.ifr).innerHTML.evalJSON();
    if (response.status) {       
        for (var i = 0; i < response.data.length; i++) {
            var el = new Element('input', {
                type: 'hidden',
                name: response.data[i].key,
                value: response.data[i].value,
                id: 'ff__' + response.data[i].key
            })
            this.form.appendChild(el);
            this.file_sends = true;
        };
        this.request();
    }
    else {
        this.showMessage(response.message, response.status).unlock();
    }
}

FormSender.prototype.showMessage = function (message, status) {
    if (!this.message) return;
    if (message.blank()) {
        this.hideMessage();
        return;
    }
    var add_class = 'error', remove_class = 'success';
    if (status) {add_class = 'success', remove_class = 'error';}
    this.message.removeClassName(remove_class);
    this.message.addClassName(add_class);   
    //clearTimeout(this.messageTimer);
    this.message.update(message);
    
    j$(this.message).show();
    
    //this.messageTimer = setTimeout(this.hideMessage.bind(this), this.params.timeout);
    return this;
}

FormSender.prototype.hideMessage = function(response) {
    j$(this.message).hide();
    this.message.update('');
}

FormSender.prototype.unlock = function() {
    if (this.loader) this.loader.addClassName('hide');
    this.ready_status = true;
}

FormSender.prototype.lock = function() {
    if (this.loader) this.loader.removeClassName('hide');
    this.ready_status = false;
}

FormSender.prototype.onSuccess = function(transport) {
    this.unlock();
    
    var response = transport.responseText.evalJSON();
    
    if (response.status) {
        if (window.Validator != undefined) {Validator.clear();}
        
        if (!this.params.after_send(response)) return;
        
        var action = (response.action)? response.action : this.params.onsuccess;

        if (action == 'refresh') {
            location.reload(); return;
        }
        else if (action == 'submit') {
            this.form.submit();
        }
        else if (action == 'update') {
            this.showMessage(response.message, response.status);
        }
        else if (action == 'replace') {
            this.form.hide();
            this.replace.update(response.message).removeClassName('hide');
        }
        else if (action.indexOf('location:') === 0) {
            var path = action.substr(9);
            window.location.href = path;
            return;
        }
        
        this.params.success(response);
        notify(this, 'send');
    }
    else {
        this.showMessage(response.message, response.status);  
    }    
}
