﻿var AJAXLoginSignupState = { Closed: 'Closed', OpenedLogin:'TLogin', OpenedSignup:'TSignup', OpenedFacebook:'TFacebook', OpenedTwitter:'TTwitter', OpenedForgotPassword:'TForgotPassword' }; //var AJAXLoginSignupState = { Closed: 'Closed', OpenedLogin:'TLogin', OpenedSignup:'TSignup', OpenedFacebook:'TFacebook', OpenedTwitter:'TTwitter', OpenedGoogle:'TGoogle', OpenedForgotPassword:'TForgotPassword' };
var ASLC;
var GigyaConfig; 
var GigyaParams;   
var GigyaStatusParams; 
function AJAXLoginSignup() {

    var PopupHeight = 0;
    var PopupWidth = 0;  

    this.State = AJAXLoginSignupState.Closed;
    this.FadeMode = 'fast';
    this.BackgroundOpacity = '0.7';
    this.TryGigyaConnect = false;
    this.GigyaUser = null;
    this.RedirectUrl = $("#ALS_RedirectUrl").val();
    this.BaseUrl = $("#ALS_BaseUrl").val();
    this.EmailRegexp = new RegExp($("#ALS_EmailRegex").val());
    $("#ALS_Background").click(function() { PopupExecuteState(AJAXLoginSignupState.Closed); });  
    $(':regex(id,ALS_.+_Star), :regex(id,ALS_(TSignup|TLogin|TForgotPassword)_(Required|EmailInvalid|EmailInUse|Processing|MissingData|Failure|Success))').each(function(){ $(this).css('display', 'none'); });

    // this is a little bit of patching. Make the avatar image invisible if the [AvatarPictureID] was not replaced with the number or was replaced with nothing
    //$("#ALS_TopPanel_Image_Avatar").css("cursor", "default"); // this is in CSS now
    if($("#ALS_TopPanel_Image_Avatar").attr("src").indexOf("[AvatarPictureID]") != -1 || $("#ALS_TopPanel_Image_Avatar").attr("src").indexOf("ID=&") != -1 ) $("#ALS_TopPanel_Image_Avatar").css("display", "none");
    
    // these two will allow to press enter when beeing in the signup/login tab
    // note: return false (I think) causes the browser NOT to trigger the default action related to the button press (which in case of enter is page refresh).
    $("#ALS_TSignup input:text").keypress(function(e) { if ((e.which && e.which == 13) || (e.keyCode && e.keyCode == 13)) { $("#ALS_Signup").click(); return false;} });
    $("#ALS_TLogin input:text, #ALS_TLogin input:password").keypress(function(e) { if ((e.which && e.which == 13) || (e.keyCode && e.keyCode == 13)) { $("#ALS_Login").click(); return false; } });
    
    // in case of 'esc' button pressedm and the popup beeing opened, close it
    $(document).keypress(function(e){ if(e.keyCode == 27 && this.State !== AJAXLoginSignupState.Closed) { PopupExecuteState(AJAXLoginSignupState.Closed); } });      
}
function PopupCenter()
{
    var windowWidth;
    var windowHeight;
    if (document.documentElement) {
        windowWidth = document.documentElement.offsetWidth > document.documentElement.clientWidth ? document.documentElement.offsetWidth : document.documentElement.clientWidth;
        windowHeight = document.documentElement.offsetHeight > document.documentElement.clientHeight ? document.documentElement.offsetHeight : document.documentElement.clientHeight;
    } else if (window.innerWidth && window.innerHeight) {
        windowWidth = window.innerWidth;
        windowHeight = window.innerHeight;
    }
    
    var position_top = windowHeight/2-$("#ALS_Popup").height()/2;
    position_top = position_top > 120 ? 120 : position_top;
    
    $("#ALS_Popup").css({ "position": "absolute", "top": position_top, "left": windowWidth/2-$("#ALS_Popup").width()/2 });  
    $("#ALS_Background").css({ "height": windowHeight });  
}
function PopupExecuteState(NewState) {
    if(NewState !== ASLC.State)
    {
        if(NewState === AJAXLoginSignupState.Closed){  
            $("#ALS_Background").fadeOut(ASLC.FadeMode);  
            $("#ALS_Popup").fadeOut(ASLC.FadeMode);  
        }  
        else if(ASLC.State === AJAXLoginSignupState.Closed)
        {
            jQuery.each(AJAXLoginSignupState, function(index, value) { 
                if(value !== AJAXLoginSignupState.Closed) { 
                    $('#ALS_' + value).css('display',NewState === value ? 'block' : 'none'); 
                    $('#ALS_' + value + '_button').removeClass();
                    $('#ALS_' + value + '_button').addClass(NewState === value ? 'ALS_TButton_on' : 'ALS_TButton');
                } 
            });
            PopupCenter();
            $("#ALS_Background").css("opacity", ASLC.BackgroundOpacity);  
            $("#ALS_Background").fadeIn(ASLC.FadeMode);  
            $("#ALS_Popup").fadeIn(ASLC.FadeMode);  
        }
        else
        {
            jQuery.each(AJAXLoginSignupState, function(index, value) { 
                if(value !== AJAXLoginSignupState.Closed) { 
                    $('#ALS_' + value).css('display',NewState === value ? 'block' : 'none'); 
                    $('#ALS_' + value + '_button').removeClass();
                    $('#ALS_' + value + '_button').addClass(NewState === value ? 'ALS_TButton_on' : 'ALS_TButton');
                } 
            });
        }        
        ASLC.State = NewState;  
    }
}
 
function GigyaConnect(Provider){
    GigyaParams = { "callback": GigyaEventHandler, "provider": Provider, "context": Provider };   
    ASLC.TryGigyaConnect = true;
    gigya.services.socialize.connect(GigyaConfig, GigyaParams);
}
function GigyaDisconnect()
{
    gigya.services.socialize.logout(GigyaConfig);
    gigya.services.socialize.disconnect(GigyaConfig);
}
function Signup(){
    if (ValidateSignup())
    {
        $("#ALS_Signup").attr("disabled", true);
        $("#ALS_TSignup_Processing").css('display', 'block');
        
        if(ASLC.TryGigyaConnect && typeof(gigya) != "undefined") {
            if(ASLC.GigyaUser == null) {
                gigya.services.socialize.getUserInfo(GigyaConfig,GigyaParams);
            } else {
                GigyaEventHandler({});
            }
        } else {
            var JSONdata = 
                "{'email':'" + $("#ALS_TSignup_Email").val() +
                "','firstName':'" + $("#ALS_TSignup_Name").val() +
                "','lastName':'" + $("#ALS_TSignup_Surname").val() +
                "','country':'" + $("#ALS_TSignup_Country").val() +
                "','city':'" + $("#ALS_TSignup_City").val() + "'}";

            $.ajax({  
                type: "POST",  
                url: ASLC.BaseUrl + "UserWS.asmx/Signup",  
                contentType: "application/json; charset=utf-8",  
                data: JSONdata,
                dataType: "json",  
                success: GigyaLoginSuccess,  
                error: GigyaLoginError
            }); 
        }
    }
}
function ValidateSignup()
{
    var retVal = true;
    
    var SignupObj = {};
    
    $(':regex(id,ALS_.+_Star), :regex(id,ALS_(TSignup|TLogin|TForgotPassword)_(Required|EmailInvalid|EmailInUse|Processing|MissingData|Failure|Success))').each(function(){ $(this).css('display', 'none'); });
    
    $('#ALS_TSignup input:text').each(function() {
        var id = $(this).attr('id');
        var val = $(this).val();
        SignupObj[id.replace('ALS_TSignup_', '')] = val; 
        if(val == '') {
            retVal = false;
            $('#' + id + '_Star').css('display', 'inline-block');
            $('#ALS_TSignup_Required').css('display', 'block');
        } else if(id.indexOf('_Email') != -1 && !val.match(ASLC.EmailRegexp)) {
            retVal = false;
            $('#' + id + '_Star').css('display', 'inline-block');
            $('#ALS_TSignup_EmailInvalid').css('display', 'block');
        }
    });

    return retVal;
}
function Login(){
    if(ValidateLogin())
    {
        $("#ALS_Login").attr("disabled", true);
        $("#ALS_TLogin_Processing").css('display', 'block');

        $.ajax({  
            type: "POST",  
            url: ASLC.BaseUrl + "UserWS.asmx/Login",  
            contentType: "application/json; charset=utf-8",  
            data: "{'email':'" + $("#ALS_TLogin_Email").val() + "','password':'" + $("#ALS_TLogin_Password").val() + "'}",
            dataType: "json",  
            success: GigyaLoginSuccess,  
            error: GigyaLoginError
        }); 
    }
}
function ValidateLogin()
{
    var retVal = true;
    
    $(':regex(id,ALS_.+_Star), :regex(id,ALS_(TSignup|TLogin|TForgotPassword)_(Required|EmailInvalid|EmailInUse|Processing|MissingData|Failure|Success))').each(function(){ $(this).css('display', 'none'); });
    
    var email = $("#ALS_TLogin_Email").val();
    var pass = $("#ALS_TLogin_Password").val();
    
    if(pass != '' && email != '') { // && email.match(ASLC.EmailRegexp)) { // comment this out in case of using the regex email validation
        $("#ALS_TLogin_Email_Star").css('display', 'none');
        $("#ALS_TLogin_Password_Star").css('display', 'none'); 
        $('#ALS_TLogin_Required').css('display', 'none'); 
        $('#ALS_TLogin_EmailInvalid').css('display', 'none'); 
    } else { 
        retVal = false; 
        
        if(email == '' || pass == '') { 
            $('#ALS_TLogin_Required').css('display', 'block'); 
            if(email == '') { $("#ALS_TLogin_Email_Star").css('display', 'inline-block'); $("#ALS_TLogin_Password_Star").css('display', 'none'); } 
            else { $("#ALS_TLogin_Email_Star").css('display', 'none'); $("#ALS_TLogin_Password_Star").css('display', 'inline-block'); } 
        }
        else
        {
            $('#ALS_TLogin_Required').css('display', 'none'); 
            $("#ALS_TLogin_Email_Star").css('display', 'none');
            $("#ALS_TLogin_Password_Star").css('display', 'none');
            
            // comment this out in case of using the regex email validation
            //if(email.match(ASLC.EmailRegexp)) { 
            //    $('#ALS_TLogin_EmailInvalid').css('display', 'none'); 
            //    $("#ALS_TLogin_Email_Star").css('display', 'none');
            //} else {
            //    $('#ALS_TLogin_EmailInvalid').css('display', 'block'); 
            //    $("#ALS_TLogin_Email_Star").css('display', 'inline-block');            
            //}
        }
    }

    return retVal;
}
function GigyaEventHandler (event)
{
    if ((ASLC.GigyaUser != null) || (event.user != null && event.user.isConnected))
    {
        var currentProvider = event.context;
    
        if(ASLC.GigyaUser == null)
        {
            ASLC.GigyaUser = event.user.identities[currentProvider];
        }
        var identity = ASLC.GigyaUser;
    
        var email = event.user.email;
        var firstName = identity.firstName;
        var lastName = identity.lastName;
        var city = identity.city;
        var country = identity.country;
    
        if ($("#ALS_TSignup_Email").val() == '') { $("#ALS_TSignup_Email").val(email); } else { email = $("#ALS_TSignup_Email").val(); }
        if ($("#ALS_TSignup_Name").val() == '') { $("#ALS_TSignup_Name").val(firstName); } else { firstName = $("#ALS_TSignup_Name").val(); }
        if ($("#ALS_TSignup_Surname").val() == '') { $("#ALS_TSignup_Surname").val(lastName); } else { lastName = $("#ALS_TSignup_Surname").val(); }
        if ($("#ALS_TSignup_City").val() == '') { $("#ALS_TSignup_City").val(city); } else { city = $("#ALS_TSignup_City").val(); }
        if ($("#ALS_TSignup_Country").val() == '') { $("#ALS_TSignup_Country").val(country); } else { country = $("#ALS_TSignup_Country").val(); }
    
        GigyaLoginSignup(identity.provider, identity.UID, identity.providerUID, identity.isLoginIdentity, identity.nickname, identity.photoURL, identity.thumbnailURL, firstName, lastName, identity.gender, identity.age, identity.birthDay, identity.birthMonth, identity.birthYear, country, identity.state, city, identity.zip, identity.profileURL, email, '');
    }
}
function GigyaLoginSignup(provider, UID, providerUID, isLoginIdentity, nickname, photoURL, thumbnailURL, firstName, lastName, gender, age, birthDay, birthMonth, birthYear, country, state, city, zip, profileURL, email, password)
{   
    var JSONdata = 
            "{'provider':'" + provider +
            "','UID':'" + UID +
            "','providerUID':'" + providerUID +
            "','isLoginIdentity':'" + isLoginIdentity +
            "','nickname':'" + nickname +
            "','photoURL':'" + photoURL +
            "','thumbnailURL':'" + thumbnailURL +
            "','firstName':'" + firstName +
            "','lastName':'" + lastName +
            "','gender':'" + gender +
            "','age':'" + age +
            "','birthDay':'" + birthDay +
            "','birthMonth':'" + birthMonth +
            "','birthYear':'" + birthYear +
            "','email':'" + email +
            "','country':'" + country +
            "','state':'" + state +
            "','city':'" + city +
            "','zip':'" + zip +
            "','profileURL':'" + profileURL + 
            "','password':'" + password + "'}";

    $.ajax({  
        type: "POST",  
        url: ASLC.BaseUrl + "UserWS.asmx/GigyaLogin",  
        contentType: "application/json; charset=utf-8",  
        data: JSONdata,
        dataType: "json",  
        success: GigyaLoginSuccess,  
        error: GigyaLoginError
    }); 
}
function GigyaLoginSuccess(event)
{
    // remove all the messages
    switch(event.d)
    {    
        // :regex(id,ALS_(TSignup|TLogin|TForgotPassword)_(Required|EmailInvalid|EmailInUse|Processing|MissingData|Error|Success))
    
        case 11: //SignupFailureSomeDataIsMissing
            if(ASLC.State !== AJAXLoginSignupState.OpenedLogin) { PopupExecuteState(AJAXLoginSignupState.OpenedSignup); }
            $(':regex(id,ALS_(TSignup|TLogin|TForgotPassword)_(Required|EmailInvalid|EmailInUse|Processing|MissingData|Failure|Success))').each(function(){ $(this).css('display', 'none'); });
            ValidateSignup();
            $("#ALS_TSignup_MissingData").css('display', 'block');
            break;
        case 10: //SignupFailureUsernameInUse
            PopupExecuteState(AJAXLoginSignupState.OpenedSignup);
            $(':regex(id,ALS_(TSignup|TLogin|TForgotPassword)_(Required|EmailInvalid|EmailInUse|Processing|MissingData|Failure|Success))').each(function(){ $(this).css('display', 'none'); });
            $("#ALS_TSignup_EmailInUse").css('display', 'block');
            break;
        case 0://LoginFailure
            PopupExecuteState(AJAXLoginSignupState.OpenedLogin);
            $(':regex(id,ALS_(TSignup|TLogin|TForgotPassword)_(Required|EmailInvalid|EmailInUse|Processing|MissingData|Failure|Success))').each(function(){ $(this).css('display', 'none'); });
            $("#ALS_TLogin_Failure").css('display', 'block');
            break;   
        case 12: //SignupSuccess
            SignupSuccess();
            break;
        case 4: //LoginSuccessExternalUserAddingFailed
            LoginSuccess();
            break;
        case 3: //LoginSuccessExternalUserAdded
            SignupSuccess();
            break;
        case 2: //LoginSuccessExternalUserExists 
            LoginSuccess();
            break;
        case 1: //LoginSuccess
            LoginSuccess();
            break;
    }
    ASLC.GigyaUser = null;
    $("#ALS_Login").removeAttr("disabled"); 
    $("#ALS_Signup").removeAttr("disabled"); 
}    
// Display a status message according to the response from reportAction.  
function SignupSuccess()  
{  
    if(typeof(gigya) != "undefined") { gigya.services.socialize.setStatus(GigyaConfig, GigyaStatusParams); }
    else { LoginSuccess(); }
}  
function LoginSuccess()  
{  
    $(':regex(id,ALS_(TSignup|TLogin|TForgotPassword)_(Required|EmailInvalid|EmailInUse|Processing|MissingData|Failure|Success))').each(function(){ $(this).css('display', 'none'); });
    window.location = $("#ALS_RedirectUrl").val();
}  
function SetStatus_Callback(response)  
{  
    $(':regex(id,ALS_(TSignup|TLogin|TForgotPassword)_(Required|EmailInvalid|EmailInUse|Processing|MissingData|Failure|Success))').each(function(){ $(this).css('display', 'none'); });
    window.location = $("#ALS_RedirectUrl").val();
}  
function GigyaLoginError(error)
{
    ASLC.GigyaUser = null;
    //PopupExecuteState(AJAXLoginSignupState.OpenedSignup);
    $("#ALS_Login").removeAttr("disabled"); 
    $("#ALS_Signup").removeAttr("disabled"); 
}

function ForgotPassword(){
    if(ValidateForgotPassword())
    {
        $("#ALS_ForgotPassword").attr("disabled", true);

        $.ajax({  
            type: "POST",  
            url: ASLC.BaseUrl + "UserWS.asmx/ResetPassword",  
            contentType: "application/json; charset=utf-8",  
            data: "{'email':'" + $("#ALS_TForgotPassword_Email").val() + "'}",
            dataType: "json",  
            success: ResetPasswordSuccess,  
            error: ResetPasswordError
        }); 
    }
}
function ValidateForgotPassword()
{
    var retVal = true;
    
    $(':regex(id,ALS_.+_Star), :regex(id,ALS_(TSignup|TLogin|TForgotPassword)_(Required|EmailInvalid|EmailInUse|Processing|MissingData|Failure|Success))').each(function(){ $(this).css('display', 'none'); });
    retVal = $("#ALS_TForgotPassword_Email").val() != '';
    
    $("#ALS_TForgotPassword_Email_Star").css('display', retVal ? 'none' : 'block');

    return retVal;
}
function ResetPasswordSuccess(event)
{
    $("#ALS_ForgotPassword").attr("disabled", false);
    $("#ALS_TForgotPassword_Success").css('display', 'block');
    
} 
function ResetPasswordError(error)
{
    $("#ALS_ForgotPassword").attr("disabled", false);
    $("#ALS_TForgotPassword_EmailInvalid").css('display', 'block');
}

$(document).ready(function() {           
    ASLC = new AJAXLoginSignup;
    GigyaConfig = { "APIKey": $("#ALS_GigyaKey").val() , "enabledProviders":"facebook,twitter" }; //,google" }; 
    GigyaStatusParams = { status: $("#ALS_Status").html(), callback:SetStatus_Callback, useFacebookConnect : true };
}); 
