/**
 * Created by Elmar <e.abdurayimov@gmail.com> Abdurayimov
 * @copyright (C)Copyright 2018
 * 09/27/2018 16:34
 */

$( document ).ready( function() {
    var checkoutV2 = function() {
        var self = this;

        var $steps = $( '#multi-step' );
        var $multiple_products = $( '.pk_section__productList' );

        self.init = function() {
            self.handleEvents();

            $('[data-toggle="tooltip"]').tooltip();
        };

        self.handleEvents = function() {
            self.handleSteps();
            self.handleCCNumParts();
            self.handleMultipleProducts();
            self.handlePhoneFormatting();

            setTimeout( function() {
                if(typeof window.validateCheckoutForm !== 'undefined') {
                    window.validateCheckoutForm();
                }
            }, 900);
        };

        /*
         |--------------------------------------------------------------------------
         | CC NUM PARTS
         |--------------------------------------------------------------------------
         */

        self.handleCCNumParts = function() {
            $( '#ccnum-part1, #ccnum-part2, #ccnum-part3, #ccnum-part4' )
                .on( 'keyup', function( e ) {
                    var target         = e.target;
                    var max_length     = 4;
                    var current_length = $( this ).val().length;

                    if( current_length >= max_length ) {
                        var $next = $( '#ccnum-part' + (parseInt( target.id.replace( 'ccnum-part', '' ) ) + 1) );

                        if( $next.length && ((e.which >= 48 && e.which <= 57) || (e.which >= 96 && e.which <= 105)) ) {
                            $next.focus().select();
                        }
                    }

                    var part1 = $( '#ccnum-part1' ).val();
                    var part2 = $( '#ccnum-part2' ).val();
                    var part3 = $( '#ccnum-part3' ).val();
                    var part4 = $( '#ccnum-part4' ).val();

                    $( '#ccNum' ).val( part1 + part2 + part3 + part4 ).trigger( 'keyup' );
                } );
        };

        /*
         |--------------------------------------------------------------------------
         | Steps
         |--------------------------------------------------------------------------
         */

        self.hasSteps = function() {
            return $steps.length > 0;
        };

        self.handleSteps = function() {
            if( !self.hasSteps() ) {
                return;
            }

            $steps.steps( {
                startAt          : 0,
                showBackButton   : true,
                showFooterButtons: true,
                stepSelector     : ".step-controller > li",
                contentSelector  : ".step-content > .step-tab-panel",
                footerSelector   : ".step-footer",
                buttonSelector   : "button",
                activeClass      : "active",
                doneClass        : "done",
                errorClass       : "error",
                onInit           : function() {
                    if( window.sendPostMessage != undefined ) {
                        window.sendPostMessage( 'height', {
                            height: $( 'body' ).height(),
                            event : 'steps are initialized'
                        } );
                    }

                    $( '.step-content, .step-footer' ).attr( 'data-step', 0 )
                        .attr( 'data-is-last-step', 0 )
                        .attr( 'data-is-first-step', 1 );
                },
                onDestroy        : $.noop,
                onFinish         : function() {
                    $( "#frmOrder" ).attr( 'target', '_top' ).submit();
                },
                onChange         : function( currentIndex, newIndex, stepDirection ) {
                    askIframeHeight();
                    setIframesHeight();

                    if( window.sendPostMessage != undefined ) {
                        window.sendPostMessage( 'height', {
                            height: $( 'body' ).height(),
                            event : 'step is changed'
                        } );
                    }

                    $( '.step-content, .step-footer' ).attr( 'data-step', currentIndex )
                        .attr( 'data-is-last-step', (currentIndex === ($( ".step-controller > li" ).length - 1)) ? 1 : 0 )
                        .attr( 'data-is-first-step', (currentIndex === 0) ? 1 : 0 );

                    if( stepDirection === 'backward' || stepDirection === 'none' ) {
                        return true;
                    }

                    if( stepDirection === 'forward' ) {
                        var is_valid = $( '#frmOrder' ).validate().checkForm();

                        if( !is_valid ) {
                            $( '#frmOrder' ).valid();

                            return false;
                        }

                        if( (currentIndex + 1) == ($( ".step-controller > li" ).length - 1) && window.pp_validation_actions !== undefined ) {
                            setTimeout( function(  ) {
                                if( $( '#frmOrder' ).validate().checkForm() ) {
                                    window.pp_validation_actions.enable();
                                } else {
                                    window.pp_validation_actions.disable();
                                }
                            }, 500);
                        }
                    }

                    $('html, body').animate({
                        scrollTop: $("#multi-step").offset().top
                    }, 2000);

                    return true;
                }
            } );
        };

        self.handleMultipleProducts = function() {
            if( !$multiple_products.length || dummy_page) return;

            switch( true ) {
                case $multiple_products.find( 'select.productList-dropdown' ).length > 0:
                    $multiple_products
                        .find( 'select.productList-dropdown' )
                        .on( 'change', function() {
                            self.redirect(
                                self.replicateCurrentSearchParams(
                                    $( this ).find( 'option:selected' ).data( 'url' )
                                )
                            );
                        } );
                    break;

                case $multiple_products.find( '.productList-radio' ).length > 0:
                    $multiple_products
                        .find( 'input:radio' )
                        .on( 'change', function() {
                            self.redirect(
                                self.replicateCurrentSearchParams(
                                    $(this).data('url')
                                )
                            );
                        } );
                    break;
            }
        };

        self.handlePhoneFormatting = function() {
            [ 'billing', 'shipping' ].forEach( function( type ) {
                if( $( '#' + type + '_phone_code' ).length && $( '#' + type + '_phone_number' ).length ) {
                    (new PhoneManager()).initPhoneEvents(
                        '#' + type + '_phone_code',
                        '#' + type + '_phone_number'
                    );
                }
            } );
        };

        self.replicateCurrentSearchParams = function (urlStr) {
            var params = self.getSearchParameters();
            var url = new URL(urlStr);
            var searchParams = url.searchParams;

            var keys = Object.keys(params);

            if (keys.length) {
                for (var i in keys) {
                    if (!keys.hasOwnProperty(i)) continue;
                    if (!keys[0]) continue;

                    searchParams.set(keys[i], params[keys[i]] || '');
                }

                url.search = searchParams.toString();
            }

            return url.toString();
        };

        self.getSearchParameters = function () {
            return window.location.search.slice(1)
                .split('&')
                .reduce(function _reduce(a, b) {
                    b = b.split('=');
                    a[b[0]] = decodeURIComponent(b[1]);

                    return a;
                }, {});
        };

        self.redirect = function( url ) {
            location.href = url;
        };
    };

    (new checkoutV2()).init();
} );