//++++++++++++++++++
// GENERAL
//++++++++++++++++++
    function fillHiddenForm(firstName, lastName, gender, email, birthDay, birthMonth, birthYear, picture, userId, social){
        var form = '<form action="" method="POST" style="display: none;">'+
                        '<input type="hidden" id="firstName" name="firstName" value="'+firstName+'"/>'+
                        '<input type="hidden" id="lastName" name="lastName" value="'+lastName+'"/>'+
                        '<input type="hidden" id="gender" name="gender" value="'+gender+'"/>'+
                        '<input type="hidden" id="email" name="email" value="'+email+'"/>'+
                        '<input type="hidden" id="birthDay" name="birthDay" value="'+birthDay+'"/>'+
                        '<input type="hidden" id="birthMonth" name="birthMonth" value="'+birthMonth+'"/>'+
                        '<input type="hidden" id="birthYear" name="birthYear" value="'+birthYear+'"/>'+
                        '<input type="hidden" id="picPath" name="picPath" value="'+picture+'"/>'+
                        '<input type="hidden" id="userId" name="userId" value="'+userId+'"/>'+
                        '<input type="hidden" id="social" name="social" value="'+social+'"/>'+
                        '<input type="submit" id="submitWLSignInBt" value="Submit"/>'+
                   '</form>'; 
       $("body").append(form);
    }

//++++++++++++++++++
// WINDOWS LIVE
//++++++++++++++++++
    function initWL(){
        var client_id = "0000000044060771",
            scope = ["wl.basic", "wl.emails", "wl.birthday"],
            redirect_uri = "http://www.ewhere.org/callback.php";
        var meImgInitialized = false;
        WL.Event.subscribe("auth.login", function()
        { 
            setMe(false);
        });
        WL.Event.subscribe("auth.logout", function()
        {
            setMe(true);
        });
        WL.Event.subscribe("auth.sessionChange", function(){
            onSessionChange();
        });
        WL.init({ 
            client_id: client_id, 
            redirect_uri: redirect_uri, 
            response_type: "token" ,
            logging: true, 
            status: true
        });
        WL.ui({ 
            name: "signin", 
            element: "WLSignIn", 
            scope: scope });
        setMe(false);
    }
    function setMe(clear)
    {
        var meImgInitialized;
        if (clear)
        {
            meImgInitialized = false;
            return;
        }

        if (meImgInitialized)
        {
            return;
        }
        
        var session = WL.getSession(),
                token = session != null ? session.access_token : null;

        if (token != null)
        {
            var imgUrl = "https://apis.live.net/v5.0/me/picture?access_token=" + encodeURIComponent(token);
            WL.api({ 
                path: "me", 
                method: "get" 
            }, function (response)
                {
                    if (!response.error)
                    {
                        //check if email address already exist
                        var sData = "action=checkExistUserFromEmail&email="+response.emails.preferred;
                        $.ajax({
                                type: "POST",
                                url: responderURL,
                                data: sData,
                                async: false,
                                dataType: "html",
                                success: function(data) {
                                        if(data.toString()!='ok'){ //email doesn't exist
                                            //store user data account
                                            var userId = createUserAccount('socialSignUp', response.emails.preferred, '');
                                            if(userId!='ko'){
                                                //create form to send data to validateAccount page
                                                birthDay = response.birth_day<10 ? '0'+response.birth_day : response.birth_day;
                                                birthMonth = response.birth_month<10 ? '0'+response.birth_month : response.birth_month;
                                                var form = fillHiddenForm(response.first_name, response.last_name, response.gender, response.emails.preferred, birthDay, birthMonth, response.birth_year, imgUrl, userId, 'WL')
                                                $("body").append(form);
                                                  WL.logout();
                                                $("#submitWLSignInBt").click();
                                            } // end if createUserAccount
                                            else{
                                                return false;
                                            } //end else createUserAccount
                                        }
                                        else{ //email already exist
                                            $("#socialSignInMsg").addClass('error errorSocialSignup');
                                            $("#socialSignInMsg").html(getLanguageSentence('EMAIL_EXIST_ERROR'));
                                            
                                            WL.logout();
                                        }
                                } //end success
                        }); //end ajax
                    }
                });
            meImgInitialized = true;
        }
    }
    function onSessionChange() {
        var session = WL.getSession();
        if (session) {
            $("#socialSignInMsg").addClass('error errorSocialSignup');
            $("#socialSignInMsg").html(getLanguageSentence('PLEASE_WAIT'));
        }
    }
//++++++++++++++++++
// FACEBOOK
//++++++++++++++++++
    function initFB(){
        FB.init({ 
            appId:'175480855861636', 
            cookie:false, 
            status:false, 
            xfbml:true, 
            oauth: true
        });
        FB.Event.subscribe('auth.login', function() {
            FB.login(function(response) {
                if (response.authResponse) {
                    $("#socialSignInMsg").addClass('error errorSocialSignup');
                    $("#socialSignInMsg").html(getLanguageSentence('PLEASE_WAIT'));
                    FB.api('/me', function(response) {
                        var sData = "action=checkExistUserFromEmail&email="+response.email;
                        $.ajax({
                                type: "POST",
                                url: responderURL,
                                data: sData,
                                async: false,
                                dataType: "html",
                                success: function(data) {
                                    if(data.toString()!='ok'){ //email doesn't exist
                                        var birthArr = response.birthday.split("/"); //GG/MM/AAAA
                                        var userId = createUserAccount('socialSignUp', response.email, '');
                                        if(userId!='ko'){
                                            fillHiddenForm(response.first_name, response.last_name, response.gender, response.email, birthArr[0], birthArr[1], birthArr[2], 'http://graph.facebook.com/' + response.id + '/picture', userId, 'FB');
                                        }
                                        FB.logout(function(response) {
                                        });
                                        if(userId!='ko'){
                                            $("#submitWLSignInBt").click();
                                        }
                                        else{
                                            return;
                                        }
                                    }
                                    else{ //email already exist
                                        $("#socialSignInMsg").addClass('error errorSocialSignup');
                                        $("#socialSignInMsg").html(getLanguageSentence('EMAIL_EXIST_ERROR'));
                                        FB.logout(function(response){});
                                    }
                                    
                                }
                        });// end ajax

                    });
                } 
                else {
    //                User cancelled login or did not fully authorize.
                }
            }, {scope: 'user_about_me,user_birthday,email'});
        });
    }
