jQuery(document).ready(function(){
	jQuery('.btn-fogot').click(function(){
		login = jQuery(this).parents('#popuplogin');
		forget = login.siblings('#popupforgot');
		jQuery('#popuplogin').hide();
		jQuery('#popupforgot').show();		
/*		jQuery('#popupforgot').stop(true).show(function(){
			pop = jQuery(this);
			jQuery('#popuplogin').hide();
			jQuery('#popupforgot').show();
			pop.css({display : 'block'}).show();
		});
		*/
		return false;
	});
	
	jQuery('.title .btn-close').click(function(){
		jQuery(this).parent().parent().parent().parent().hide();
	});
});

popupUserFormShow = function(){
	jQuery('#popuplogin').show();
	jQuery('#popupforgot').hide();
}
showWinePopupFormMsg = function(msg, el){
	jQuery("#newsletterpopup").show();
	jQuery("#newsletterpopup").find('.holder').text(msg);
}
var PopupLogin = Class.create();
PopupLogin.prototype = {
    initialize: function(form){
        this.form = $(form);
        if (this.form) {
            this.form.observe('submit', function(event){this.save();Event.stop(event);}.bind(this));
        }

        this.onSuccess = this.success.bindAsEventListener(this);
		this.onFailure = this.failure.bindAsEventListener(this);
		this.onComplete = this.complete.bindAsEventListener(this);
		this.onCreate = this.create.bindAsEventListener(this);
    },

	success: function(ob){
		res = ob.responseJSON;
		jQuery('.usr-success-message').remove();		
		if(!res.success) {
			jQuery(this.form).prepend('<strong class="usr-success-message">'+res.msg+'</strong>');
		} else {
			if (res.url) {
				window.location = res.url;
			} else {
				jQuery(this.form).hide().after('<strong class="usr-success-message">' + res.msg + '</strong>');
				frm = jQuery(this.form);
				setTimeout(function(){
					frm.siblings('.usr-success-message').fadeTo(250, 0, function(){
						jQuery(this).siblings('form').css({ opacity : 0, display : 'block' }).fadeTo(250, 1);
						jQuery(this).remove();
						jQuery('#popupforgot').hide();
						jQuery('#popuplogin').show();
					});
				}, 5000);
			} 
		}
	},
	
	create: function(){
		jQuery(this.form).find('input').attr('disabled', 'disabled');
		jQuery(this.form).find('.popupLoginAjaxLoader').show();
	},
	
	failure: function(){
		
	},
	
	complete: function(){
		jQuery(this.form).find('input').removeAttr('disabled');
		jQuery(this.form).find('.popupLoginAjaxLoader').hide();
	},

    save: function(){
		jQuery(this.form).children('p.validation-advice').remove();
        var validator = new Validation(this.form);
        if (validator.validate()) {
            var request = new Ajax.Request(
                this.form.action,
                {
					evalJSON: 'force',
                    method: 'post',
                    onSuccess: this.onSuccess,
					onFailure: this.onFailure,
					onComplete: this.onComplete,
					onCreate: this.onCreate,
                    parameters: Form.serialize(this.form)
                }
            );
        }
    }
}



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()) {
					showWinePopupFormMsg('Введите правильный e-mail','test');
					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;
							//alert(res.msg);
							showWinePopupFormMsg(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();
        }
    }
};

