var getUniqueId = (function() {var id=0;return function() {if (arguments[0]==0) {id=1;return 0;} else return id++;}})();

showPopupFormMsg = function(msg, el){
	pop = getPopupFormMsg(msg, el);
	position = jQuery(el).position();
	pop.css({
		top : position.top-20,
		left : position.left-30
	});

	pop.find('> .cont > .popcnt').html(msg).wrapInner('<strong />');
	pop.show();
}

getPopupFormMsg = function(msg, el){
	if(el) {
		key = jQuery(el).data('popValidatorKey');
		if(!key) {
			key = (String(el.id).length > 0 ? el.id : getUniqueId()) + '-pop';
			jQuery(el).data('popValidatorKey', key);
		}
	}
	pop = jQuery('#' + key);
	if(pop.size() <= 0) {
		pop = createPopupFormMsg(msg, el);
	}
	return pop;
}

createPopupFormMsg = function(msg, el){	
	if(el) {
		key = jQuery(el).data('popValidatorKey');
		if(!key) {
			key = (String(el.id).length > 0 ? el.id : getUniqueId()) + '-pop';
			jQuery(el).data('popValidatorKey', key);
		}
	}
	
	popupClass = jQuery(el).data('popupClass') || "";
	
	jQuery('#mainBox').append('<div class="boxPopupIn"><div id="' + key + '" class="procuctListPopup' + (popupClass.length > 0 ? ' ' + popupClass : '') + '" style="display: block;"><div class="top"></div><div class="cont"><div class="close"><a href="javascript: void(0)" title="Закрыть"><span>Закрыть</span></a></div><p class="popcnt"></p></div><div class="bot"></div></div></div>');
	pop = jQuery('#' + key);
	pop.find('> .cont > .popcnt').html(msg).wrapInner('<strong />');
	return pop;
}

AtalanSubcribeForm = Class.create();
AtalanSubcribeForm.prototype = {
    initialize: function(formId, field, emptyText, popupClass,firstFieldFocus){
        this.form       = $(formId);
        if (!this.form) {
            return;
        }
		this.field  = $(field);
		jQuery(this.form).data('inpfield', this.field);
		this.emptyText = emptyText;
		
        this.cache      = $A();
		jQuery('#' + field).data('popupClass', popupClass);
        this.currLoader = false;
        this.currDataIndex = false;
        this.validator = new AtalanValidation(this.form, {
			onSubmit: function(ev){
				if (!this.validate()) {
					Event.stop(ev);
					return false;
				}
				
				frm = this.form;
				fld = jQuery(frm).data('inpfield');
				
	            var request = new Ajax.Request(
	                this.form.action,
	                {
	                    method: 'post',
						evalJSON: 'force',
						onCreate: function(){
							jQuery(fld).data('savedVal', jQuery(fld).val());
							jQuery(fld).val("Подождите...");
							jQuery(frm).find('input').attr('disabled', 'disabled');
						},
						onComplete: function(){
							jQuery(frm).find('input').removeAttr('disabled');
							jQuery(fld).val(jQuery(fld).data('savedVal'));
						},
	                    onSuccess: function(ob){
							res = ob.responseJSON;
							showPopupFormMsg(res.msg, fld)
						},
	                    onFailure: function(){
							alert('При отправке поизошла ошибка.');
						},
	                    parameters: Form.serialize(this.form)
	                }
	            );
				Event.stop(ev);
				return false;
			}
		});
        this.elementFocus   = this.elementOnFocus.bindAsEventListener(this);
        this.elementBlur    = this.elementOnBlur.bindAsEventListener(this);
        this.childLoader    = this.onChangeChildLoad.bindAsEventListener(this);
        this.highlightClass = 'highlight';
        this.extraChildParams = '';
        this.firstFieldFocus= firstFieldFocus || false;
        this.bindElements();
        if(this.firstFieldFocus){
            try{
                Form.Element.focus(Form.findFirstElement(this.form))
            }
            catch(e){}
        }

        Event.observe(this.field, 'focus', this.focus.bind(this));
        Event.observe(this.field, 'blur', this.blur.bind(this));
		this.blur();
    },
	
    focus : function(event){
        if(this.field.value==this.emptyText){
            this.field.value='';
        }

    },

    blur : function(event){
        if(this.field.value==''){
            this.field.value=this.emptyText;
        }
    },

    submit : function(url){
        if(this.validator && this.validator.validate()){
             this.form.submit();
        }
        return false;
    },

    bindElements:function (){
        var elements = Form.getElements(this.form);
        for (var row in elements) {
            if (elements[row].id) {
                Event.observe(elements[row],'focus',this.elementFocus);
                Event.observe(elements[row],'blur',this.elementBlur);
            }
        }
    },

    elementOnFocus: function(event){
        var element = Event.findElement(event, 'fieldset');
        if(element){
            Element.addClassName(element, this.highlightClass);
        }
    },

    elementOnBlur: function(event){
        var element = Event.findElement(event, 'fieldset');
        if(element){
            Element.removeClassName(element, this.highlightClass);
        }
    },

    setElementsRelation: function(parent, child, dataUrl, first){
        if (parent=$(parent)) {
            // TODO: array of relation and caching
            if (!this.cache[parent.id]){
                this.cache[parent.id] = $A();
                this.cache[parent.id]['child']     = child;
                this.cache[parent.id]['dataUrl']   = dataUrl;
                this.cache[parent.id]['data']      = $A();
                this.cache[parent.id]['first']      = first || false;
            }
            Event.observe(parent,'change',this.childLoader);
        }
    },

    onChangeChildLoad: function(event){
        element = Event.element(event);
        this.elementChildLoad(element);
    },

    elementChildLoad: function(element, callback){
        this.callback = callback || false;
        if (element.value) {
            this.currLoader = element.id;
            this.currDataIndex = element.value;
            if (this.cache[element.id]['data'][element.value]) {
                this.setDataToChild(this.cache[element.id]['data'][element.value]);
            }
            else{
                new Ajax.Request(this.cache[this.currLoader]['dataUrl'],{
                        method: 'post',
                        parameters: {"parent":element.value},
                        onComplete: this.reloadChildren.bind(this)
                });
            }
        }
    },

    reloadChildren: function(transport){
        var data = eval('(' + transport.responseText + ')');
        this.cache[this.currLoader]['data'][this.currDataIndex] = data;
        this.setDataToChild(data);
    },

    setDataToChild: function(data){
        if (data.length) {
            var child = $(this.cache[this.currLoader]['child']);
            if (child){
                var html = '<select name="'+child.name+'" id="'+child.id+'" class="'+child.className+'" title="'+child.title+'" '+this.extraChildParams+'>';
                if(this.cache[this.currLoader]['first']){
                    html+= '<option value="">'+this.cache[this.currLoader]['first']+'</option>';
                }
                for (var i in data){
                    if(data[i].value) {
                        html+= '<option value="'+data[i].value+'"';
                        if(child.value && (child.value == data[i].value || child.value == data[i].label)){
                            html+= ' selected';
                        }
                        html+='>'+data[i].label+'</option>';
                    }
                }
                html+= '</select>';
                Element.insert(child, {before: html});
                Element.remove(child);
            }
        }
        else{
            var child = $(this.cache[this.currLoader]['child']);
            if (child){
                var html = '<input type="text" name="'+child.name+'" id="'+child.id+'" class="'+child.className+'" title="'+child.title+'" '+this.extraChildParams+'>';
                Element.insert(child, {before: html});
                Element.remove(child);
            }
        }

        this.bindElements();
        if (this.callback) {
            this.callback();
        }
    }
};

