window.PB_CONFIG = null;
window.PB_USERPROFILE = null;

function pbRegister( data )
{
    var xhr = new XMLHttpRequest(),
        request = {
            auth : {
                version : window.PB_CONFIG.version,
                sessionToken : null
            },
            c : 'Auth',
            a: 'registerTrainer',
            params : data
        };

    xhr.onload = function() {
        var response = xhr.responseText ? xhr.responseText : null;
        if ( response )
        {
            try
            {
                response = JSON.parse(response);
            }
            catch( err ) {}

            if ( response && response.hasOwnProperty( 'data' ) && response.hasOwnProperty( 'code' ) )
            {
                if ( response.code == 200 )
                {
                    $( '[data-type="register-section"]' ).hide();

                    $( '[data-id="checkmark-container"]' ).first().html(
                        '                            <div data-type="rsvp-button-recall">\n' +
                        '                                <svg class="rsvp-checkmark"\n' +
                        '                                     xmlns="http://www.w3.org/2000/svg"\n' +
                        '                                     viewBox="0 0 52 52">\n' +
                        '                                    <circle class="rsvp-checkmark__circle" cx="26" cy="26" r="25" fill="none"/>\n' +
                        '                                    <path class="rsvp-checkmark__check" fill="none" d="M14.1 27.2l7.1 7.2 16.7-16.8"/>\n' +
                        '                                </svg>\n' +
                        '                            </div>'
                    );

                    // Show next steps
                    if ( response.data.session === null )
                    {
                        // Show validation info
                        $( '[data-id="registration-new-user"]' ).first().show();
                    }
                    else
                    {
                        // Show login
                        $( '[data-id="registration-existing-user"]' ).first().show();
                    }
                }
                else
                {
                    $( '[data-id="error-general"]' ).first().show();
                }
            }
            $( '[data-id="btn-register"]' ).first().attr( 'disabled', false );
        }
    };

    xhr.onabort = function() {
        $( '[data-id="btn-register"]' ).first().enable();
    };
    xhr.onerror = function() {
        $( '[data-id="btn-register"]' ).first().enable();
    };

    xhr.open( 'POST', 'api.php' );
    xhr.setRequestHeader( "Content-Type", "application/json" );
    xhr.send( JSON.stringify( request ) );
}

function pbRegisterWizard( onOk, onErr )
{
    var xhr = new XMLHttpRequest(),
        request = {
            auth : {
                version : window.PB_CONFIG.version,
                sessionToken : null
            },
            c : 'Auth',
            a: 'registerTrainer',
            params : window.WIZARD_DATA
        },
        onSuccess = onOk || null,
        onError = onErr || null;

    xhr.onload = function()
    {
        var response = xhr.responseText ? xhr.responseText : null;
        if ( response )
        {
            try
            {
                response = JSON.parse(response);
            } catch (err) {}

            if ( response && response.hasOwnProperty( 'data' ) && response.hasOwnProperty( 'code' ) )
            {
                if ( response.code == 200 )
                {
                    onSuccess && onSuccess();
                }
            }
        }
    };

    xhr.onabort = function() {
        onError && onError();
    };
    xhr.onerror = function() {
        onError && onError();
    };

    xhr.open( 'POST', 'api.php' );
    xhr.setRequestHeader( "Content-Type", "application/json" );
    xhr.send( JSON.stringify( request ) );
}

function pbInitWizard()
{
    window.WIZARD_INDEX = 0;
    window.WIZARD_DATA = {};
    window.WIZARD_DATA.industry = 'HORSES';
    window.WIZARD_DATA.affiliateId = 'HorseStartseite';

    var $bWizard = $( '[data-id="wizard-carousel"]' ).first(),
        $wizardProgress = $( '[data-id="wizard-progress"]' ).first();

    $wizardProgress.css( 'width', '0%' );

    $bWizard.carousel({
        interval: false,
        keyboard : false,
        touch: false
    });

    $bWizard.on( 'slide.bs.carousel', function( e )
    {
        var nextH = $(e.relatedTarget).height();
        $(this).find('.carousel-item.active').parent().animate({
            height: nextH
        }, 500);
    });

}

function pbWizardUpdateProgress()
{
    var $wizardProgress = $( '[data-id="wizard-progress"]' ).first(),
        totalSteps = $( '[data-type="wizard-step"]' ).length,
        progress = ~~( window.WIZARD_INDEX / totalSteps * 100);

    $wizardProgress.css( 'width', progress + '%' );
}

function pbWizardNext( step )
{
    window.WIZARD_INDEX++;

    var $bWizard = $( '[data-id="wizard-carousel"]' ).first();

    switch ( step )
    {
        case 'school':
            var $form = $( '[data-id="wizardform-school"]' ).first(),
                heightAdd = $form.hasClass( 'was-validated' ) ? 0 : 70;
            $form.removeClass( 'was-validated' );
            var isValid = $form.get(0).checkValidity();
            $form.addClass( 'was-validated' );

            if ( false === isValid )
            {
                if ( heightAdd > 0 )
                {
                    setTimeout( function()
                    {
                        $( '.carousel-inner' ).animate( { height: $( '.carousel-inner' ).innerHeight() + heightAdd }, 300 );
                    }, 100 );
                }
                return;
            }

        break;
        case 'register':
            var $form = $( '[data-id="wizardform-account"]' ).first(),
                heightAdd = $form.hasClass( 'was-validated' ) ? 0 : 70;
            $form.removeClass( 'was-validated' );
            var isValid = $form.get(0).checkValidity();
            $form.addClass( 'was-validated' );

            if ( false === isValid )
            {
                if ( heightAdd > 0 )
                {
                    setTimeout( function()
                    {
                        $( '.carousel-inner' ).animate( { height: $( '.carousel-inner' ).innerHeight() + heightAdd }, 300 );
                    }, 100 );
                }
                return;
            }

            window.WIZARD_DATA.teamname = $.trim( $( '[data-id="input-register-teamname"]' ).first().val() );
            window.WIZARD_DATA.courseCategories = [];
            $( '[data-type="checkbox-coursecategories"]' ).each( function()
            {
                if ( $(this).prop( 'checked' ) )
                {
                    window.WIZARD_DATA.courseCategories.push( $(this).attr( 'data-value' ) );
                }
            });
            window.WIZARD_DATA.createDemoAppointments = $( '[data-id="register-demo-appointments"]' ).first().prop( 'checked' ) ? 1 : 0;

            window.WIZARD_DATA.firstname = $.trim( $( '[data-id="input-register-firstname"]' ).first().val() );
            window.WIZARD_DATA.lastname = $.trim( $( '[data-id="input-register-lastname"]' ).first().val() );
            window.WIZARD_DATA.email = $.trim( $( '[data-id="input-register-email"]' ).first().val() );
            window.WIZARD_DATA.password = $.trim( $( '[data-id="input-register-password"]' ).first().val() );

            window.WIZARD_DATA.subscribedNews = $.trim( $( '[data-id="register-accept-newsletter"]' ).first().prop( 'checked' ) ? 1 : 0 );

            pbRegisterWizard(
                // onSuccess
                function()
                {
                    $( '[data-id="register-container"]' ).first().html(
                        '                            <div class="register-success">\n' +
                        '                                <svg class="rsvp-checkmark"\n' +
                        '                                     xmlns="http://www.w3.org/2000/svg"\n' +
                        '                                     viewBox="0 0 52 52">\n' +
                        '                                    <circle class="rsvp-checkmark__circle" cx="26" cy="26" r="25" fill="none"/>\n' +
                        '                                    <path class="rsvp-checkmark__check" fill="none" d="M14.1 27.2l7.1 7.2 16.7-16.8"/>\n' +
                        '                                </svg>\n' +
                        '                            </div>'
                    );

                    window.WIZARD_INDEX++;
                    pbWizardUpdateProgress();

                    setTimeout( function()
                    {
                        pbWizardNext( 'done' );
                    }, 1400 );
                },
                // onError
                function()
                {
                    $( '[data-id="section-wizard-form"]' ).hide();
                    $( '[data-id="registration-error"]' ).show();
                }
            );

        break;
    }

    pbWizardUpdateProgress();
    $bWizard.carousel( 'next' );

    $('html, body').animate({
        scrollTop: ( $( '#section-register' ).offset().top - 200 )
    }, 700, 'easeInOutExpo', function(){
        //window.location.hash = hash;
    });

}

function pbWizardPrev()
{
    window.WIZARD_INDEX--;

    var $bWizard = $( '[data-id="wizard-carousel"]' ).first();

    pbWizardUpdateProgress();

    $bWizard.carousel( 'prev' );
}

function pbInit()
{
    var xhr = new XMLHttpRequest(),
        request = {
            auth : {
                version : 0,
                sessionToken : null
            },
            c : 'Auth',
            a: 'getSession',
            params : { includeConfig: true }
    };

    xhr.onload = function() {
        var response = xhr.responseText ? xhr.responseText : null;

        if ( response )
        {
            try
            {
                response = JSON.parse(response);
            }
            catch( err ) {}

            if ( response.hasOwnProperty( 'data' ) )
            {
                if (  response.data.hasOwnProperty( 'config' )  )
                {
                    window.PB_CONFIG = response.data.config;
                }
                if ( response.data.hasOwnProperty( 'userProfile' ) )
                {
                    window.PB_USERPROFILE = response.data.userProfile;
                }
            }
        }
    };

    xhr.onabort = function() {};

    xhr.onerror = function() {};

    xhr.open( 'POST', 'api.php' );
    xhr.setRequestHeader( "Content-Type", "application/json" );
    xhr.send( JSON.stringify( request ) );

    // Form
    $( '[data-id="btn-register"]' ).first().click( function()
    {
        var $form = $( '[data-id="form-register"]' ).first();
        $form.removeClass( 'was-validated' );
        var isValid = $form.get(0).checkValidity();
        $form.addClass( 'was-validated' );

        $( '[data-id="error-email-exists"]' ).first().hide();
        $( '[data-id="error-general"]' ).first().hide();

        if ( isValid )
        {
            $(this).attr( 'disabled', true );

            var data = {};
            data.teamname = $.trim( $( '[data-id="input-register-teamname"]' ).first().val() );
            data.teamCategory = $.trim( $( '[data-id="input-team-category"]' ).first().val() );
            data.affiliateId = $.trim( $( '[data-id="input-affiliate-id"]' ).first().val() );
            data.email = $.trim( $( '[data-id="input-register-email"]' ).first().val() );
            data.password = $.trim( $( '[data-id="input-register-password"]' ).first().val() );
            data.firstname = $.trim( $( '[data-id="input-register-firstname"]' ).first().val() );
            data.lastname = $.trim( $( '[data-id="input-register-lastname"]' ).first().val() );
            data.subscribedNews = $.trim( $( '[data-id="register-accept-newsletter"]' ).first().prop( 'checked' ) ? 1 : 0 );

            pbRegister( data );
        }
    });

    pbInitWizard();
}