/*global MooTools: true */
if(typeof FDFB === "undefined") var FDFB;
if(typeof FDFBLocalization === "undefined") var FDFBLocalization = {};
(function(){
	FDFB = function(FB, appId, fduid) {
        if(!appId) throw new Error("Facebook app id required");
        this.appId = appId;
        this.fduid = fduid;
		this.fbstate = {
			status : "unknown"
		};
		this.lang = new Hash({
			"login-unknown" : "Login",
			"login-notConnected" : "Login",
			"login-connected": "Login",
            "login-connected-loggedin": "Login",
            "login-unknown-loggedin" : "Login &amp; Connect",
            "login-notConnected-loggedin" : "Connect",
			facebookLogout : "Logout from Facebook"
		});
        this.lang.extend(FDFBLocalization);
		this.FB = FB;
        this.FB.init({
            appId: appId,
            status: true, // check login status
            cookie: true, // enable cookies to allow the server to access the session
            xfbml: true  // parse XFBML
        });
		this.FB.getLoginStatus(this.handleLoginStatus.bind(this));
	};
	
	FDFB.prototype = {
		init : function() {
            var fbstate = this.fbstate;
            var lang = this.lang;
            var loggedin = this.isLoggedIn() ? "-loggedin" : "";
            Array.each($$('.fb_button_text'), function(element, i) {
                element.innerHTML = lang["login-" + fbstate.status + loggedin];
            });
            this.boundLoginHandler = this.handleLoginClick.bind(this);
            var loginButton = $$("a.fb_button.fb_button_medium");
            loginButton.removeEvents("click");
            loginButton.addEvent("click", this.boundLoginHandler);
		},
        login : function() {
            
        },
        handleLoginResponse : function(response) {
            this.fbstate = response;
            if(response.authResponse) {
                FB.api('/me', function(response) {
                    var email=response.email;
                    var birth=response.birthday;
                    var month="";
                    var day="";
                    var year="";
                    if(birth!=null)
                    {
                        var datum=birth.split("/");
                        if(datum.length>2)
                        {
                            month=datum[0];
                            day=datum[1];
                            year=datum[2];
                        }
                    }
                    if(response.gender!=null)
                    {
                        gender=response.gender;
                    }
                    var location="";
                    if(response.location!=null)
                    {
                        location=response.location.name;
                    }
                    var city="";
                    var country="";
                    if(location!=null)
                    {
                        var place=location.split(", ");
                        city=place[0];
                        if(place.length>1)
                        {
                            country=place[1];
                        }
                    }
                    document.location.href = "/?reg=1&fbcity="+city+"&fbcountry="+country+"&fbgender="+gender+"&fbemail="+email+"&fbyear="+year+"&fbmonth="+month+"&fbday="+day;    
                });
            }
            else
            {
            if (response.status == 'connected') {
            FB.getLoginStatus(function(response) {
                this.fbstate = response;
                if (response.authResponse) {
                        FB.api('/me', function(response) {
                    var email=response.email;
                    var birth=response.birthday;
                    var month="";
                    var day="";
                    var year="";
                    if(birth!=null)
                    {
                        var datum=birth.split("/");
                        if(datum.length>2)
                        {
                            month=datum[0];
                            day=datum[1];
                            year=datum[2];
                        }
                    }
                    if(response.gender!=null)
                    {
                        gender=response.gender;
                    }
                    var location="";
                    if(response.location!=null)
                    {
                        location=response.location.name;
                    }
                    var city="";
                    var country="";
                    if(location!=null)
                    {
                        var place=location.split(", ");
                        city=place[0];
                        if(place.length>1)
                        {
                            country=place[1];
                        }
                    }
                    document.location.href = "/?reg=1&fbcity="+city+"&fbcountry="+country+"&fbgender="+gender+"&fbemail="+email+"&fbyear="+year+"&fbmonth="+month+"&fbday="+day;    
                });
                    }
            }, true);}}
        },
		handleLoginStatus : function(response) {
        this.fbstate = response;
			if(typeof this[response.status] === "function") {
				this[response.status].call(this, response);
			}
			this.init();
		},
		connected : function(response) {
			// logged in and authorized
			if(this.isLoggedIn()) {
                var fblink = $$("a.fb_button.fb_button_medium");
//				fblink.destroy();
			} else {
				// not logged in to Firstdate
				/*
				 * <fb:login>
				 * <a class="fb_button fb_button_medium">
				 * <span class="fb_button_text">Logga in</span>
				 * </a>
				 * </fb:login>
				 */
            
				var logoutLink = new Element('a', {'class': "fdfb_logout", href:"#"});
				logoutLink.appendText(this.lang.facebookLogout);
                logoutLink.addEvent("click", this.handleLogoutClick.bind(this));
                var logoutPlaceholder = $$(".fb-logout-link");
				logoutPlaceholder.grab(logoutLink);
                var lFB = this.FB;
				logoutLink.addEvent("click", function() {
					lFB.logout(function() {
						document.location.href = document.location.href;
					});
				});
			}
		},
        boundLoginHandler : undefined,
		notConnected : function(response) {
			// logged in not authorized
		},
		unknown : function(response) {
			var cookie = this.getCookie("fbs_" + this.appId);
            if(cookie) {
                var date = new Date(1970, 0, 1, 1);
                console.log("fbs_" + this.appId + ";expires=" + date.toGMTString());
                document.cookie = "fbs_" + this.appId + ";expires=" + date.toGMTString();
                window.location.refresh();
            }
		},
		getFirstdateState : function() {
			
		},
		handleLoginClick : function(event) {
			event.preventDefault();
            event.stopPropagation();
            if(this.fbstate.status !== "connected") {
                this.FB.login(this.handleLoginResponse.bind(this), {
                 scope:"user_about_me,user_birthday,user_groups,user_interests,user_likes,email,user_hometown,user_location"
                });
            } else {
                FB.api('/me', function(response) {
                    var email=response.email;
                    var birth=response.birthday;
                    var month="";
                    var day="";
                    var year="";
                    if(birth!=null)
                    {
                        var datum=birth.split("/");
                        if(datum.length>2)
                        {
                            month=datum[0];
                            day=datum[1];
                            year=datum[2];
                        }
                    }
                    if(response.gender!=null)
                    {
                        gender=response.gender;
                    }
                    var location="";
                    if(response.location!=null)
                    {
                        location=response.location.name;
                    }
                    var city="";
                    var country="";
                    if(location!=null)
                    {
                        var place=location.split(", ");
                        city=place[0];
                        if(place.length>1)
                        {
                            country=place[1];
                        }
                    }
                    document.location.href = "/?reg=1&fbcity="+city+"&fbcountry="+country+"&fbgender="+gender+"&fbemail="+email+"&fbyear="+year+"&fbmonth="+month+"&fbday="+day;    
                });
            }
		},
        handleLogoutClick : function(event) {
			event.preventDefault();
			this.FB.logout(this.unhandleLoginClick.bind(this));
		},
        unhandleLoginClick : function() {
            if(this.boundLoginHandler) {
                //$$("fb\\:login-button a").removeEvent("click", this.boundLoginHandler);
            }
            $$(".fdfb_logout").destroy();
        },
		isLoggedIn : function() {
            return this.fduid > 0;
		},
		getUserId : function() {
			var uid;
			if(this.isLoggedIn())
			{
                uid = this.fduid;
//				var cookie = this.getCookie("fd_r");
//				uid = cookie.split("_")[0];
			}
			return uid;
		},
		getCookie : function(name)
		{
			var cookie;
			if(document.cookie) {
				var results = document.cookie.match ( '(^|;) ?' + name + '=([^;]*)(;|jQ)' );
				if(results)
				{
					cookie = ( decodeURIComponent ( results[2] ) );
				}
			}
			return cookie;
		}
	};
}());
