"use strict";

var TB = TB || {};
TB.Control = TB.Control || {};

TB.Control.Settings = {
    // Overview
    account : function( params )
    {
        TB.GUI.showLoader();

        var page = new TB.Page('settings_account');

        TB.Service.request('Account', 'getEmailChange', {}, function (data) {
            TB.GUI.hideLoader();

            if ( data && data.acc ) {
                TB.Client.updateSessionAccount( data.acc );
            }

            TB.GUI.show(page, {account: TB.Client.account, ec : (data.ec ? data.ec : null) });

            page.$container.find('#btn-change-password-cancel').click(function () {

                TB.Ext.Notification.show('Keine Änderungen vorgenommen.', TB.Ext.Notification.TYPE_INFO);
                TB.Controller.reload();

            });

            page.$container.find('#btn-change-password-submit').click(function () {

                if (!TB.GUI.performFormValidation($('#form_change_password'))) {
                    return false;
                }

                TB.Service.request(
                    'Account',
                    'changePassword',
                    $('#form_change_password').serializeObject(),
                    function (res) {

                        if (res && res.ok) {

                            TB.Ext.Notification.show('Passwort erfolgreich geändert.', TB.Ext.Notification.TYPE_SUCCESS);
                            TB.Controller.reload();

                        } else if (res && res.nochange) {

                            TB.Ext.Notification.show('Neues und altes Passwort sind identisch. Keine Änderungen.', TB.Ext.Notification.TYPE_WARNING);

                        } else if (res && res.oldpasswordnok) {

                            TB.Ext.Notification.show('Das alte Password ist nicht korrekt.', TB.Ext.Notification.TYPE_DANGER);

                        }

                    },
                    $(this)
                );

                return false;
            });

            page.$container.find('#btn-change-email-cancel').click(function () {

                TB.Ext.Notification.show('Keine Änderungen vorgenommen.', TB.Ext.Notification.TYPE_INFO);
                TB.Controller.reload();

            });


            page.$container.find('#btn-change-email-submit').click(function () {
                if (!TB.GUI.performFormValidation($('#form_change_email'))) {
                    return false;
                }

                TB.Service.request(
                    'Account',
                    'changeEmail',
                    $('#form_change_email').serializeObject(),
                    function (res) {

                        if (res && res.ok) {

                            TB.Ext.Notification.show('Eine Validierungsnachricht wurde an die neue Email Adresse geschickt. Bitte folge den Anweisungen in der Mail.', TB.Ext.Notification.TYPE_SUCCESS);
                            TB.Controller.reload();

                        } else if (res && res.nochange) {

                            TB.Ext.Notification.show('Neue Email Adresse ist identisch mit deiner alten Adresse. Keine Änderungen.', TB.Ext.Notification.TYPE_WARNING);

                        } else if (res && res.emailexists) {

                            TB.Ext.Notification.show('Die Email Adresse existiert bereits im System. Wenn du mehrere Accounts zusammenlegen möchtest, wende dich bitte an den Support.', TB.Ext.Notification.TYPE_WARNING);

                        } else if (res && res.invalidpw) {
                            TB.Ext.Notification.show('Das eingegebene Passwort ist falsch.', TB.Ext.Notification.TYPE_WARNING);
                        }
                    },
                    $(this)
                );
                return false;
            });
        });
    }
    ,
    premium : function( params )
    {
        TB.GUI.showLoader();
        var page = new TB.Page('settings_premium' ),
            showSuccess = params.hasOwnProperty( 'success' ) && "1" == params.success ? true : false,
            showCancellation = params.hasOwnProperty( 'cancellation' ) && "1" == params.cancellation ? true : false;

        TB.Service.request(
            'Settings',
            'getPremiumDetails',
            {},
            function( data )
            {
                var teamName,
                    teams = data && data.teams && data.teams.length ? data.teams : [];

                if ( data && data.premium_logs && data.premium_logs.length > 0 )
                {
                    teamName = '-gelöscht-';

                    for ( var pli = 0; pli < data.premium_logs.length; pli++ )
                    {
                        for ( var ti = 0; ti < teams.length; ti++ )
                        {
                            if ( teams[ ti ].id == data.premium_logs[ pli ].team_id )
                            {
                                teamName = teams[ ti ].display_name;
                                break;
                            }
                        }

                        data.premium_logs[ pli ].__teamName = teamName;
                    }
                }

                TB.GUI.show( page, data );

                page.$container.find( '[data-type="book-premium"]' ).on( 'click', function()
                {
                    var currentTeam = TB.Client.getCurrentTeam(),
                        premiumTeamId = $(this).attr( 'data-team-id' ),
                        profileId;

                    if ( premiumTeamId == currentTeam.id )
                    {
                        TB.Controller.do( 'Settings', 'order_premium' );
                    }
                    else
                    {
                        // Change team - redirect to Setting-order_premium, reload
                        for ( var pi = 0; pi < TB.Client.profiles.length; pi++ )
                        {
                            if ( TB.Client.profiles[ pi ].team_id == premiumTeamId )
                            {
                                profileId = TB.Client.profiles[ pi ].id;
                                break;
                            }
                        }

                        if ( profileId )
                        {
                            TB.Service.request( 'Profile', 'change', { profile_id : profileId },
                                function( data )
                                {
                                    if ( data && data.session && data.profile && data.profiles && data.teams )
                                    {
                                        TB.Client.setSessionData( TB.Client.account, data.profile, data.session, data.profiles, data.teams );
                                        $( window ).off( 'hashchange' );
                                        TB.Controller.updateHash( 'Settings', 'order_premium' );
                                        location.reload( true );
                                    }
                                }
                            );
                        }

                    }

                });

                TB.GUI.hideLoader();

                if ( true === showSuccess )
                {
                    TB.Ext.Alert.modal({
                        title : 'Kauf erfolgreich abgeschlossen',
                        text : 'Vielen Dank, dass du dich für TBuddy Premium entschieden hast.',
                        type : 'success',
                        showCancelButton : false
                    });
                }
                else if ( true === showCancellation )
                {
                    TB.Ext.Alert.modal({
                        title : 'Premium Paket storniert.',
                        text : 'Achtung. Sobald das Premium Paket abgelaufen ist, stehen dem gesamten Team die Premiumfunktionen nicht mehr zur Verfügung.',
                        type : 'warning',
                        showCancelButton : false
                    });
                }
            }
        );


    }
    ,
    premium_detail : function( params )
    {
        TB.GUI.showLoader();
        var page = new TB.Page('settings_premium_detail' );

        TB.Service.request(
            'Settings',
            'getPremiumDetail',
            { premiumLogId : params.premium_log_id },
            function( data )
            {
                TB.GUI.show( page, data );
                TB.GUI.hideLoader();
            }
        );
    }
    ,
    premium_edit : function( params )
    {
        TB.GUI.showLoader();
        var page = new TB.Page('settings_premium_edit' ),
            premiumLogId = params.premium_log_id ? params.premium_log_id : null,
            $bf,
            billingData = {};

        TB.Service.request(
            'Settings',
            'getPremiumDetail',
            { premiumLogId : premiumLogId },
            function( data )
            {
                TB.GUI.show( page, data );

                page.$container.find( '[data-id="btn-cancel-subscription"]' ).first().click( function()
                {
                    TB.Ext.Alert.modal(
                        {
                            title: "Bist du sicher, dass Du das Premium Paket stornieren möchtest?",
                            text: "Du und dein Team verlierst damit zum nächsten Abrechnungsdatum den Premium Status und somit die Möglichkeit, die TBuddy Prmeium Funktionen nützen zu können.",
                            confirmButtonText : 'Ja, stornieren!',
                            type: 'warning'
                        },
                        function()
                        {
                            $("html, body").animate({ scrollTop: 0 }, "slow");
                            TB.GUI.showLoader();
                            TB.Service.request(
                                'Settings',
                                'cancelSubscription',
                                {
                                    premiumLogId : premiumLogId
                                },
                                function( res )
                                {
                                    TB.Controller.do( 'Settings', 'premium', { cancellation : 1 } );
                                }
                            );
                        }
                    )
                });

                page.$container.find( '[data-id="btn-update-subscription"]' ).first().click( function()
                {
                    if ( !TB.GUI.performFormValidation( $( '#form_billing_address' ) ) )
                    {
                        TB.Ext.Alert.modal(
                            {
                                title: "Fehlerhafter Rechnungsempfänger",
                                text: "Bitte kontrolliere die Eingaben im Bereich des Rechnungsempfängers.",
                                confirmButtonText : 'Stornieren!',
                                type: 'warning',
                                showCancelButton: false
                            }
                        );
                        return false;
                    }


                    // BillingForm
                    $bf =  $( '#form_billing_address' );
                    billingData.company_name = $bf.find( 'input[name="company_name"]' ).val();
                    billingData.tax_id = $bf.find( 'input[name="tax_id"]' ).val();
                    billingData.first_name = $bf.find( 'input[name="first_name"]' ).val();
                    billingData.last_name = $bf.find( 'input[name="last_name"]' ).val();
                    billingData.street = $bf.find( 'input[name="street"]' ).val();
                    billingData.zip_code = $bf.find( 'input[name="zip_code"]' ).val();
                    billingData.city = $bf.find( 'input[name="city"]' ).val();
                    billingData.email = $bf.find( 'input[name="email"]' ).val();

                    TB.Service.request(
                        'Settings',
                        'updatePremiumDetail',
                        {
                            premiumLogId : premiumLogId,
                            billingData : billingData
                        },
                        function( data )
                        {
                            TB.Ext.Notification.show(
                                'Daten erfolreich aktualisiert. Sie werden ab der nächsten Buchung berücksichtigt.',
                                TB.Ext.Notification.TYPE_SUCCESS
                            );

                            TB.Controller.do( 'Settings', 'premium_detail', { premium_log_id : premiumLogId } );
                        }
                    );

                    return false;
                });

                TB.GUI.hideLoader();
            }
        );
    }
    ,
    order_premium : function( params )
    {
        TB.GUI.showLoader();

        var page,
            braintreeCustomerData = null,
            billingData = {},
            $bf,
            selectedPremiumId = params.hasOwnProperty( 'selectedpackage' ) ? params.selectedpackage.toUpperCase() : null,
            activeTab = 'premium';

        TB.Service.request( 'Team', 'load', { addPremium : true } , function( data ) {

            TB.GUI.hideLoader();

            if ( false === TB.Premium.isValidPremiumPackage( selectedPremiumId ) )
            {
                selectedPremiumId = TB.Premium.getRecommendedPremiumPackageForTeam( data.team, data.profiles );
            }

            data.numProfiles = data.profiles.length;
            data.activeTab = activeTab;
            data.braintreeCustomerData = braintreeCustomerData;
            data.selectedPremiumId = selectedPremiumId;
            data.possiblePackages = TB.Premium.getPossiblePremiumPackagesForTeam( data.team, data.profiles );
            data.account = TB.Client.account;

            page = new TB.Page( 'settings_premium_order' );

            TB.GUI.show(page, data);

            page.$container.find( 'button[data-type="btn-premium-select"]' ).click( function()
            {
                var $btn = $(this);

                // Remove all active states
                page.$container.find( 'button.btn-premium-selected' ).each( function( i, v ) {
                    var $btn = $(this);
                    $btn.removeClass( 'btn-premium-selected' );
                    $btn.find( 'span.btn-premium-selected-text' ).hide();
                    $btn.find( 'span.btn-premium-select-text' ).show();
                });

                // Set active state to pressed button
                $btn.addClass( 'btn-premium-selected' );
                $btn.find( 'span.btn-premium-select-text' ).hide();
                $btn.find( 'span.btn-premium-selected-text' ).show();

                selectedPremiumId = $btn.attr( 'data-premium-id' );

                data.selectedPremiumId = selectedPremiumId;

                page.$container.find( '[data-id="premium-summary-container"]' ).first().html(
                    tmpl( 'tpl_settings_premium_order_summary', { data: data } )
                );

                return false;
            });


            braintree.setup(
                TB.Client.BRAINTREE_CLIENT_TOKEN,
                //'sandbox_ddbykh5t_mmr6s9yxbhkcf57q',        // SANDBOX
                //'production_w8xgg4jb_4n796zqzrv66pysf',     // PRODUCTION
                'custom',
                {
                    paypal : {
                        container : 'paypal-container',
                        locale : 'de_DE',
                        displayName : 'TBuddy UG (haftungsbeschränkt)',
                        onCancelled : function()
                        {
                            braintreeCustomerData = null;
                            data.braintreeCustomerData = braintreeCustomerData;
                            page.$container.find( '[data-id="premium-summary-container"]' ).first().html(
                                tmpl( 'tpl_settings_premium_order_summary', { data: data } )
                            );
                        }
                    },
                    onPaymentMethodReceived : function( obj )
                    {
                        braintreeCustomerData = obj;
                        data.braintreeCustomerData = braintreeCustomerData;
                        page.$container.find( '[data-id="premium-summary-container"]' ).first().html(
                            tmpl( 'tpl_settings_premium_order_summary', { data: data } )
                        );
                    }
                }
            );

            page.$container.find( 'button[data-id="btn-create-premium"]' ).first().click( function()
            {

                if ( !braintreeCustomerData )
                {
                    TB.Ext.Alert.modal(
                        {
                            title: "Fehlender Paypal Account",
                            text : "Drücke auf den Paypal-Button und wähle das Rechnungskonto aus.",
                            type: 'warning',
                            showCancelButton : false
                        }
                    );
                    return false;
                }
                else if ( !selectedPremiumId )
                {
                    TB.Ext.Alert.modal(
                        {
                            title: "Unbekanntes Premium Paket",
                            text : "Das angegebene Paket scheint nicht zu existieren.",
                            type: 'error',
                            showCancelButton : false
                        }
                    );
                    return false;
                }
                else if ( !TB.GUI.performFormValidation( $( '#form_billing_address' ) ) )
                {
                    TB.Ext.Alert.modal(
                        {
                            title: "Fehlerhafter Rechnungsempfänger",
                            text : "Bitte kontrolliere die Eingaben im Bereich des Rechnungsempfängers.",
                            type: 'warning',
                            showCancelButton : false
                        }
                    );
                    return false;
                }
                else if ( false === page.$container.find( '[data-id="checkbox-billing-premium-agb"]' ).first().is( ':checked' ) )
                {
                    TB.Ext.Alert.modal(
                        {
                            title: "Akzeptiere die AGBs",
                            text : "Du musst die AGBs akzeptieren, bevor du die Bestellung abschicken kannst.",
                            type: 'warning',
                            showCancelButton : false
                        }
                    );
                    return false;
                }
                else
                {
                    // BillingForm
                    $bf =  $( '#form_billing_address' );
                    billingData.company_name = $bf.find( 'input[name="company_name"]' ).val();
                    billingData.tax_id = $bf.find( 'input[name="tax_id"]' ).val();
                    billingData.first_name = $bf.find( 'input[name="first_name"]' ).val();
                    billingData.last_name = $bf.find( 'input[name="last_name"]' ).val();
                    billingData.street = $bf.find( 'input[name="street"]' ).val();
                    billingData.zip_code = $bf.find( 'input[name="zip_code"]' ).val();
                    billingData.city = $bf.find( 'input[name="city"]' ).val();
                    billingData.email = $bf.find( 'input[name="email"]' ).val();

                    $("html, body").animate({ scrollTop: 0 }, "slow");
                    TB.GUI.showLoader();

                    TB.Service.request(
                        'Team',
                        'createPremium',
                        {
                            billingData : billingData,
                            braintreeCustomerData : braintreeCustomerData,
                            packageId : selectedPremiumId
                        },
                        function( data )
                        {
                            var pageSuccess;

                            if ( data && data.team )
                            {
                                TB.Client.updateSessionTeam( data.team );
                            }

                            TB.Utils.trackEvent( 'premium', 'booked' );

                            TB.Controller.do( 'Settings', 'premium', { success : 1 } );
                        }
                    );
                }
            });

        });
    }
    ,
    billing : function( params )
    {
        TB.GUI.showLoader();
        var page = new TB.Page('settings_billing' );

        TB.Service.request(
            'Settings',
            'getBilling',
            {},
            function( data )
            {
                TB.GUI.show( page, data );

                page.$container.find( '[data-invoice-id]' ).click( function()
                {
                    TB.Controller.do( 'Settings', 'billingdetail', { bid : $(this).attr( 'data-invoice-id' ) } );
                });


                TB.GUI.hideLoader();
            }
        );
    }
    ,
    billingdetail : function( params )
    {
        var billingId = params.bid || null;

        TB.GUI.showLoader();
        var page = new TB.Page('settings_billing_detail' );

        TB.Service.request(
            'Settings',
            'getBillingDetail',
            { id : billingId },
            function( data )
            {
                TB.GUI.show( page, data );

                page.$container.find( '[data-id="btn-invoice-print"]' ).click( function()
                {
                    window.print();
                });

                TB.GUI.hideLoader();
            }
        );
    }
};