(function(a){
    a.fn.extend({
        peerdialog: function(d){
            return this.each(function(){
                new c(this, d)
            })
        },
        addTwitterResult: function(d){
            return this.trigger("addTwitterResult", [d])
        },
        addFacebookResult: function(d){
            return this.trigger("addFacebookResult", [d])
        },
        addCallbackAfterLogin: function(d){
            return this.trigger("addCallbackAfterLogin", [d])
        },
        addCallbackOnClose: function(d){
            return this.trigger("addCallbackOnClose", [d])
        }
    });
    var b = {
        dialog: null,
        mask: null,
        anim: {
            show_mask: true,
            anim_mask: false
        },
        twitter_result: {},
        facebook_result: {},
        connect_result: {},
        //curr_tab: 0,
        //tabs_const: ["dialog-login", "dialog-twitter-connect", "dialog-facebook-connect"],
        min_name_length: 3,
        callbackAfterLogin: null,
        callbackOnClose: null,
        regexp_email: /^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/,
        regexp_name: /^[a-zA-Z0-9_ ]+$/i,
        reg_in_progress: false,
        facebookPopup: null,
        twitterPopup: null
    };
    a.peerdialog = function(d, e){
        this.options = a.extend({}, b, e || {});
        this.parent = a(d);
        this.setup()
    };
    var c = a.peerdialog;
    c.fn = c.prototype = {
        peerdialog: "0.0.1"
    };
    c.fn.extend = c.extend = a.extend;
    c.fn.extend({
        setup: function(){
            if (this.options.anim.show_mask) {
                this.buildMask()
            }
            var d = this;
            this.parent.bind("click.dialog", function(f){
                d._eventClick()
            });
            this.parent.bind("addTwitterResult", function(){
                d.processTwitter(arguments[1])
            });
            this.parent.bind("addFacebookResult", function(){
                d.processFacebook(arguments[1])
            });
            this.parent.bind("addCallbackAfterLogin", function(){
                if (typeof arguments[1] == "function") {
                    d.options.callbackAfterLogin = arguments[1]
                }
            });
            this.parent.bind("addCallbackOnClose", function(){
                if (typeof arguments[1] == "function") {
                    d.options.callbackOnClose = arguments[1]
                }
            })
        },
        showPage: function(d){
            this.resetTabs();
            switch (d) {
                case "registration":
                    a("#dialog-logins").hide();
                    a("#dialog-registration").show();
                    break;
                case "login":
                    a("#dialog-logins").show();
                    a("#dialog-registration").hide();
                    break
            }
        },
        processTwitter: function(i){
            this.options.twitter_result = i;
            this.options.connect_result = i;
            if (i.account_type == "new") {
                var g = this;
                var d = a("#twitter-connect-finish");
                var f = d.find("img");
                var e = d.find("input:text");
                var h = a("#modalTwFinishBtn");
                this.options.connect_input = e;
                this.options.connect_submit = h;
                f.attr("src", this.options.twitter_result.profile_image_url);
                e.attr("value", this.options.twitter_result.name);
                h.bind("click.checkname", function(){
                    g.eventCheckName(h);
                    h.unbind("click.checkname")
                });
                a("#dialog-onconnect").hide();
                d.show()
            }
            else {
                if (i.account_type == "banned") {
                    alert("Banned user");
                    this.closeDialog()
                }
                else {
                    if (i.account_type == "exist") {
                        global_ls = 1;
                        this.setLoginState(i);
                        if (typeof this.options.callbackAfterLogin == "function") {
                            this.callback("callbackAfterLogin")
                        }
                        this.closeDialog()
                    }
                }
            }
        },
        processFacebook: function(i){
            this.options.facebook_result = i;
            this.options.connect_result = i;
            if (i.popup_state == "cancel") {
                this.closeDialog()
            }
            else {
                if (i.account_type == "new") {
                    var g = this;
                    var d = a("#twitter-connect-finish");
                    var f = d.find("img");
                    var e = d.find("input:text");
                    var h = a("#modalTwFinishBtn");
                    this.options.connect_input = e;
                    this.options.connect_submit = h;
                    f.attr("src", this.options.facebook_result.profile_image_url);
                    e.attr("value", this.options.facebook_result.name);
                    h.bind("click.checkname", function(ev){
						ev.preventDefault();	
                        g.eventCheckName()
                    });
                    a("#dialog-onconnect").hide();
                    d.show()
                }
                else {
                    if (i.account_type == "banned") {
                        alert("Banned user");
                        this.closeDialog()
                    }
                    else {
                        if (i.account_type == "exist") {
							global_ls = 1;
                            this.setLoginState(i);
                            if (typeof this.options.callbackAfterLogin == "function") {
                                this.callback("callbackAfterLogin")
                            }
                            this.closeDialog()
                        }
                    }
                }
            }
        },
        checkRegistration: function(){
            this.options.reg_in_progress = true;
            var d = this;
            var e = false;
            if (a("#reg-input-name").val() == "") {
                a("#reg-input-name").next("p.error").remove();
                a("#reg-input-name").after('<p class="error">' + g_language["dialog-login-error-name-1"] + "</p>");
                e = true
            }
            else {
                if (a("#reg-input-name").val().length < this.options.min_name_length) {
                    a("#reg-input-name").next("p.error").remove();
                    a("#reg-input-name").after('<p class="error">' + g_language["dialog-login-error-name-2"] + "</p>");
                    e = true
                }
                else {
                    a("#reg-input-name").next("p.error").remove()
                }
            }
            if (a("#reg-input-email").val() == "") {
                a("#reg-input-email").next("p.error").remove();
                a("#reg-input-email").after('<p class="error">' + g_language["dialog-login-error-email-1"] + "</p>");
                e = true
            }
            else {
                if (!this.options.regexp_email.test(a("#reg-input-email").val())) {
                    a("#reg-input-email").next("p.error").remove();
                    a("#reg-input-email").after('<p class="error">' + g_language["dialog-login-error-email-2"] + "</p>");
                    e = true
                }
                else {
                    a("#reg-input-email").next("p.error").remove()
                }
            }
            if (a("#reg-input-passwd1").val() == "" || a("#reg-input-passwd2").val() == "") {
                a("#reg-input-passwd2").next("p.error").remove();
                a("#reg-input-passwd2").after('<p class="error">' + g_language["dialog-login-error-passwd-1"] + "</p>");
                e = true
            }
            else {
                if (a("#reg-input-passwd1").val() != a("#reg-input-passwd2").val()) {
                    a("#reg-input-passwd2").next("p.error").remove();
                    a("#reg-input-passwd2").after('<p class="error">' + g_language["dialog-login-error-passwd-2"] + "</p>");
                    e = true
                }
                else {
                    a("#reg-input-passwd2").next("p.error").remove()
                }
            }
            if (!e) {
                a.ajax({
                    type: "POST",
                    dataType: "json",
                    url: "/index.php?action=ajax",
                    data: "reg=1&name=" + a("#reg-input-name").val() + "&email=" + a("#reg-input-email").val() + "&passwd1=" + a("#reg-input-passwd1").val() + "&passwd2=" + a("#reg-input-passwd1").val(),
                    beforeSend: function(){
                        //a("#reg-submit").attr("disabled", true);
                        a('#modalRegBtn').unbind();
						a("#dialog-registration-form").find("img.loader").show()
                    },
                    success: function(g){
                        //a("#reg-submit").attr("disabled", false);
						a('#modalRegBtn').bind('click', function(e) {
							e.preventDefault();
							d.checkRegistration();
						})
						a("#dialog-registration-form").find("img.loader").hide();
                        var f = false;
                        if (g.error.name) {
                            a("#reg-input-name").next("p.error").remove();
                            a("#reg-input-name").after('<p class="error">' + g_language["dialog-login-error-name-" + g.error.name] + "</p>");
                            f = true
                        }
                        if (g.error.email) {
                            a("#reg-input-email").next("p.error").remove();
                            a("#reg-input-email").after('<p class="error">' + g_language["dialog-login-error-email-" + g.error.email] + "</p>");
                            f = true
                        }
                        if (g.error.password) {
                            a("#reg-input-passwd2").next("p.error").remove();
                            a("#reg-input-passwd2").after('<p class="error">' + g_language["dialog-login-error-passwd-" + g.error.password] + "</p>");
                            f = true
                        }
                        if (!f) {
                            d.showActivationTab(g.data.email)
                        }
                        else {
                            d.options.reg_in_progress = false
                        }
                    }
                })
            }
        },
        showActivationTab: function(d){
			var t = this;
            //this.resetTabs();
			a('#modalRegFinishBtn').unbind();
            a("#dialog-registration-form").hide();
            a("#registration-finish").show();
            a("#registration-finish").find("p span").html(d)
        	a('#modalRegFinishBtn').bind('click', function(e) {
				e.preventDefault();
				t.submitActivationCode();
			});
		},
        submitActivationCode: function(){
            var d = this;
            var e = a("#dialog-regfinish-form").find("input:text").val();
            if (e != "") {
                a.ajax({
                    type: "POST",
                    dataType: "json",
                    url: "/index.php?action=ajax",
                    data: "reg_activate=1&code=" + e,
                    beforeSend: function(){
                        //a("#dialog-regfinish-form").find("input:submit").attr("disabled", true);
                        a('#modalRegFinishBtn').unbind();
					    a("#dialog-regfinish-form").find("img.loader").show()
                    },
                    success: function(f){
                        a("#dialog-regfinish-form").find("img.loader").hide();
                        if (f.error.length == 0) {
                            global_ls = 1;
                            d.resetTabs();
                            d.closeDialog();
                            d.setLoginState(f.data)
                        }
                        else {
                            //a("#dialog-regfinish-form").find("input:submit").attr("disabled", false);
                        	a('#modalRegFinishBtn').bind('click', function(ev) {
								ev.preventDefault();
								d.submitActivationCode();
							});
							a("#dialog-regfinish-form").find("input:text").next("p.error").remove();
                            a("#dialog-regfinish-form").find("input:text").after('<p class="error">' + g_language["dialog-reg-activate-error-code-" + f.error.code] + "</p>")
                        }
                    }
                })
            }
        },
        checkLogin: function(){
            var d = this;
            var f = false;
            var h = a("#dialog-login-form").find("input:text");
            var e = a("#dialog-login-form").find("input:password");
            //var g = a("#dialog-login-form").find("input:submit");
            var g = a('#modalLoginBtn');
			
			if (h.val() == "" || e.val() == "") {
                f = true
            }
            else {
                if (!this.options.regexp_email.test(h.val())) {
                    f = true
                }
            }
            if (!f) {
                a.ajax({
                    type: "POST",
                    url: "/index.php?action=ajax",
                    dataType: "json",
                    data: "login=1&email=" + h.val() + "&passwd=" + e.val(),
                    beforeSend: function(){
                        a("#dialog-login-form").find("p.error").hide();
                        a("#dialog-login-form").find("img.loader").show();
                        //g.attr("disabled", true)
                    	g.unbind();
					},
                    error: function(i, k, j){
                        alert(k)
                    },
                    success: function(i){
                        switch (i.result) {
                            case -1:
                                if (a("#dialog-login-form").find("p.error").length == 0) {
                                    a("#dialog-login-form").find("input:password").after('<p class="error">' + g_language["dialog-login-error-2"] + "</p>")
                                }
                                break;
                            case 0:
                                d.showActivationTab(h.val());
                                break;
                            case 1:
                                global_ls = 1;
                                d.setLoginState(i.data);
                                d.closeDialog();
                                if (typeof d.options.callbackAfterLogin == "function") {
                                    d.options.connect_result = i.data;
                                    d.callback("callbackAfterLogin")
                                }
                                break
                        }
                        a("#dialog-login-form").find("img.loader").hide();
                        //g.attr("disabled", false)
						g.bind('click', function(e) {
							e.preventDefault();
							d.checkLogin();
						})
                    }
                })
            }
            else {
                if (a("#dialog-login-form").find("p.error").length == 0) {
                    a("#dialog-login-form").find("input:password").after('<p class="error">' + g_language["dialog-login-error-2"] + "</p>")
                }
            }
        },
        eventCheckName: function(){
            jQuery.trim(this.options.connect_input.val());
            if (this.options.connect_input.val().length == 0) {
                alert(g_language["dialog-conn-error-name-1"])
            }
            else {
                if (this.options.connect_input.val().length < this.options.min_name_length) {
                    alert(g_language["dialog-conn-error-name-2"])
                }
                else {
                    this.ajaxCheckName()
                }
            }
        },
        ajaxCheckName: function(){
            this.options.connect_submit.unbind("click.checkname");
            var d = this;
            var f = this.options.facebook_result;
            var e = this.options.twitter_result;
            a.ajax({
                type: "POST",
                dataType: "json",
                url: "/index.php?action=ajax",
                data: "chkname=1&name=" + this.options.connect_input.val(),
                error: function(g, i, h){
                    alert(i)
                },
                success: function(g){
                    if (g.result == 0) {
                        d.nameIsBusy(false);
                        if (d.options.twitter_result.id) {
                            d.registerAccount(d.options.twitter_result, "twitter")
                        }
                        else {
                            if (d.options.facebook_result.id) {
                                d.registerAccount(d.options.facebook_result, "facebook")
                            }
                        }
                    }
                    else {
                        a("#modalTwFinishBtn").bind("click.checkname", function(){
                            d.eventCheckName();
                            a("#modalTwFinishBtn").unbind("click.checkname")
                        });
                        d.nameIsBusy(true)
                    }
                }
            })
        },
        nameIsBusy: function(d){
            if (!a(".dialog-check-name-error")) {
                return
            }
            if (d) {
                a(".dialog-check-name-error").html(g_language["dialog-login-error-1"])
            }
            else {
                a(".dialog-check-name-error").html("")
            }
        },
        registerAccount: function(f, e){
            var d = this;
            a.ajax({
                type: "POST",
                dataType: "json",
                url: "/index.php?action=ajax",
                data: "addacc=" + e + "&name=" + this.options.connect_input.val() + "&id=" + f.id + "&imgsrc=" + f.profile_image_url + "&email=" + f.email + "&offline_access=" + f.offline_access,
                error: function(g, i, h){
                    alert(i)
                },
                success: function(g){
                    if (g.result == true) {
                        d.setLoginState(g.data);
                        d.callback("callbackAfterLogin");
                        d.closeDialog()
                    }
                }
            })
        },
        buildMask: function(){
            var d = a(document).height();
            var e = a(window).width();
            if (a("#" + this.options.mask).length == 0 || this.options.mask == null) {
                this.options.mask = a('<div id="mask"></div>').appendTo("body")
            }
            else {
                this.options.mask = a("#" + this.options.mask)
            }
            this.options.mask.css({
                width: e,
                height: d,
                top: 0,
                left: 0,
                position: "absolute",
                display: "none",
                opacity: 0.4,
                "background-color": "#300b03",
				'z-index': 3
            }).appendTo("body")
        },
        showMask: function(e){
            if (!a("#" + this.options.dialog)) {
                return
            }
            var d = this;
            switch (e) {
                case true:
                    a(this.options.mask).css("display", "block");
                    if (this.options.anim.anim_mask) {
                        a(this.options.mask).fadeTo("fast", 0.5, function(){
                            d.showDialog()
                        })
                    }
                    else {
                        a(this.options.mask).css({
                            width: a(window).width(),
                            height: a(document).height()
                        });
                        d.showDialog()
                    }
                    break;
                case false:
                    this.options.mask.hide();
                    break
            }
        },
        _eventClick: function(d){
            if (this.options.anim.show_mask) {
                this.showMask(true)
            }
            else {
                this.showDialog()
            }
            this.parent.unbind("click.dialog")
        },
        _eventDialog: function(){
            var d = this;
            this.options.btn_close = a("#" + this.options.dialog).find("a.modalCancelBtn");
            this.options.btn_close.click(function(){
                d.closeDialog()
            });
            a(document).bind("keyup.closeDialog", function(f){
                switch (f.keyCode) {
                    case 27:
                        d.closeDialog();
                        break
                }
            });
            a("#modalTwBtn").bind("click", function(f){
                f.preventDefault();
                d.options.twitterPopup = window.open('/twitter/connect', "popup_twitter_login", "dialog,modal,scrollbar=yes,resizable=no,width=800,height=500,top=100,left=10");
                a(".dialog-logins").hide();
                a("#dialog-onconnect").show()
            });
            a("#modalFbBtn").bind("click", function(f){
                f.preventDefault();
                if (d.options.facebookPopup == null) {
                    d.options.facebookPopup = window.open("http://www.facebook.com/login.php?api_key=929817c06aa146adb8655a1e2f4506bf&display=popup&extern=1&fbconnect=1&req_perms=publish_stream,read_stream,offline_access,email&return_session=1&v=1.0&next=http%3A%2F%2Fnaturhalo.hu%2Fconnect%2Ffacebook%2Fconfirm.php?s=ok&fb_connect=1&cancel_url=http%3A%2F%2Fnaturhalo.hu%2Fconnect%2Ffacebook%2Fconfirm.php?s=cancel", "_blank", "top=100,left=10,width=480,height=460,resizable=yes", true)
                }
                a(".dialog-logins").hide();
                a("#dialog-onconnect").show()
            });
            a("#dialog-login-form").bind("submit", function(f){
                f.preventDefault();
                //d.checkLogin()
            });
			a('#modalLoginBtn').bind('click', function(f) {
				f.preventDefault();
				d.checkLogin();
			});
            a("#dialog-registration-form").bind("submit.registration", function(f){
                f.preventDefault();
                //d.checkRegistration()
            });
			a('#modalRegBtn').bind('click', function(f) {
				f.preventDefault();
				d.checkRegistration();
			});			
            /* a("#dialog-regfinish-form").bind("submit.activate", function(f){
                f.preventDefault();
                d.submitActivationCode()
            }); */
            /*jQuery.each(this.options.tabs_const, function(f, e){
                a("#dialog-tab-" + f).click(function(g){
                    g.preventDefault();
                    if (f == d.options.curr_tab || a("#dialog-tab-" + f).hasClass("close")) {
                        return
                    }
                    a("#" + d.options.tabs_const[d.options.curr_tab]).hide();
                    a("#" + e).show();
                    a("#dialog-tab-" + d.options.curr_tab).parent("li").removeClass("on");
                    a("#dialog-tab-" + f).parent("li").addClass("on");
                    d.options.curr_tab = f
                });
                if (a("#dialog-show-reg")) {
                    a("#dialog-show-reg").click(function(g){
                        g.preventDefault();
                        d.showPage("registration")
                    })
                }
                if (a("#dialog-show-login")) {
                    a("#dialog-show-login").click(function(g){
                        g.preventDefault();
                        d.showPage("login")
                    })
                }
            })*/
			a('#switchToReg').click(function(e) {
				e.preventDefault();
				a('#switchToReg').parent().hide();
				a('#regCont').show();
				a('#loginCont').hide();
				a('#switchToLogin').parent().show();
			});
			a('#switchToLogin').click(function(e) {
				e.preventDefault();
				a('#switchToLogin').parent().hide();
				a('#loginCont').show();
				a('#regCont').hide();
				a('#switchToReg').parent().show();
			});
        },
        showDialog: function(){
            if (!a("#" + this.options.dialog)) {
                return
            }
            var e = a(window).height();
            var d = a(window).width();
            a("#" + this.options.dialog).css("top", this.getPageScroll()[1] + (this.getPageHeight() / 3));
            //a("#" + this.options.dialog).css("left", d / 2 - a("#" + this.options.dialog).width() / 2);
            a("#" + this.options.dialog).show();
            this.options.closeTop = this.getPageScroll()[1] + (this.getPageHeight() / 3);
            this._eventDialog()
        },
        closeDialog: function(){
            var d = this;
            this.parent.bind("click.dialog", function(f){
                f.preventDefault();
                d._eventClick()
            });
            a(document).unbind("keyup.closeDialog");
            a("#" + this.options.dialog).hide();
            this.resetTabs();
            this.showMask(false);
            this.options.facebookPopup = null;
            if (typeof d.options.callbackOnClose == "function") {
                this.callback("callbackOnClose")
            }
        },
        setLoginState: function(d){
            a("div.header-login").html('<div id="headerInfo" class="colorYellow">' + g_language["header-txt-1"] + " <strong>" + d.name + '</strong> | <a href="' + global_domain + 'kilepes">' + g_language["header-txt-2"] + "</a></div>");
        },
        callback: function(e){
            var f = this.options[e];
            if (!a.isFunction(f)) {
                return
            }
            var d = this;
            f(d)
        },
        resetTabs: function(){
            //a("#dialog-tab-" + this.options.curr_tab).parent("li").removeClass("on");
            //this.options.curr_tab = 0;
            //a("#dialog-tab-" + this.options.curr_tab).parent("li").addClass("on");
            //a("#dialog-logins").show();
            //a("#dialog-login").show();
			a('#switchToLogin').parent().hide();
			a('#loginCont').show();
			a('#regCont').hide();
			a('#switchToReg').parent().show();
			a("#dialog-twitter-connect").hide();
            a("#dialog-facebook-connect").hide();
            a("#twitter-connect-finish").hide();
            a("#facebook-connect-finish").hide();
            a("#dialog-onconnect").hide();
            a("#dialog-registration").hide();
			a("#dialog-registration-form").show();
            a("#registration-finish").hide();
            a(":input", "#dialog-login-form").not(":submit, :button, :hidden").attr("value", "");
            a(":input", "#dialog-regfinish-form").not(":submit, :button, :hidden").attr("value", "");
            a(":input", "#dialog-registration-form").not(":submit, :button, :hidden").attr("value", "");
            a("#dialog-login-form").find("p.error").remove();
            a("#dialog-regfinish-form").find("p.error").remove();
            a("#dialog-registration-form").find("p.error").remove();
            a("#reg-input-name").val("");
            a("#twitter-connect-finish").find("input:text").attr("value", "");
            this.options.twitter_result = {};
            this.options.facebook_result = {};
            this.options.connect_result = {}
        },
        getPageScroll: function(){
            var e, d;
            if (self.pageYOffset) {
                d = self.pageYOffset;
                e = self.pageXOffset
            }
            else {
                if (document.documentElement && document.documentElement.scrollTop) {
                    d = document.documentElement.scrollTop;
                    e = document.documentElement.scrollLeft
                }
                else {
                    if (document.body) {
                        d = document.body.scrollTop;
                        e = document.body.scrollLeft
                    }
                }
            }
            return new Array(e, d)
        },
        getPageHeight: function(){
            var d;
            if (self.innerHeight) {
                d = self.innerHeight
            }
            else {
                if (document.documentElement && document.documentElement.clientHeight) {
                    d = document.documentElement.clientHeight
                }
                else {
                    if (document.body) {
                        d = document.body.clientHeight
                    }
                }
            }
            return d
        }
    })
})(jQuery);

