jQuery(document).ready(function($){
    const locations     = wpstlAjaxHandler.locations;
    const packageTable  = $('#wpcstl-package-table');
    // function helpers
    function intlTelInputScript(){    
        if ( $.isFunction($.fn.intlTelInput) ) {  
            var errorMap = ["Invalid number", "Invalid country code", "Too short", "Too long", "Invalid number"];        
            // $("#wpcargo_receiver_phone, #wpcargo_shipper_phone").intlTelInput({
            //     utilsScript: wpstlAjaxHandler.utilsScript,
            // });
            $("#"+wpstlAjaxHandler.shipperPhoneMetakey+", #"+wpstlAjaxHandler.receiverPhoneMetakey).intlTelInput({
                utilsScript: wpstlAjaxHandler.utilsScript,
                allowDropdown: false,
                //autoPlaceholder: "off",
                separateDialCode: true,
                onlyCountries: ["au"],
            });
            function intlTelInputReset( thisField ) {
                thisField.closest('.form-group').find('.valid-msg, .error-msg').addClass('d-none');
                thisField.closest('.form-group').find('.error-msg').text('');
            };
            $("#"+wpstlAjaxHandler.shipperPhoneMetakey+", #"+wpstlAjaxHandler.receiverPhoneMetakey).on('blur', function() {
                var input = $(this);
                intlTelInputReset( input );
                if ( $.trim( input.val()) ) {
                    if ( input.intlTelInput("isValidNumber")) {
                        input.closest('.form-group').find('.valid-msg').removeClass('d-none');
                    } else {
                        var errorCode = input.intlTelInput("getValidationError");
                        var errorMEssage = errorCode === -99 ? 'Wrong Format' : errorMap[errorCode];
                        input.closest('.form-group').find('.valid-msg').addClass('d-none');
                        input.closest('.form-group').find('.error-msg').removeClass('d-none').text( errorMEssage );
                    }
                }
            });
            $("#"+wpstlAjaxHandler.shipperPhoneMetakey+", #"+wpstlAjaxHandler.receiverPhoneMetakey).on('change, keyup', function() {
                intlTelInputReset( $(this) );
            });
        }
    }
    function download_file(fileURL, fileName) {
        // for non-IE
        if (!window.ActiveXObject) {
            var save = document.createElement('a');
            save.href = fileURL;
            save.target = '_blank';
            var filename = fileURL.substring(fileURL.lastIndexOf('/')+1);
            save.download = fileName || filename;
            if ( navigator.userAgent.toLowerCase().match(/(ipad|iphone|safari)/) && navigator.userAgent.search("Chrome") < 0) {
                    document.location = save.href; 
                // window event not working here
                }else{
                    var evt = new MouseEvent('click', {
                        'view': window,
                        'bubbles': true,
                        'cancelable': false
                    });
                    save.dispatchEvent(evt);
                    (window.URL || window.webkitURL).revokeObjectURL(save.href);
                }	
        }
        // for IE < 11
        else if ( !! window.ActiveXObject && document.execCommand)     {
            var _window = window.open(fileURL, '_blank');
            _window.document.close();
            _window.document.execCommand('SaveAs', true, fileName || fileURL)
            _window.close();
        }
    }
    function get_location_list( code ){
        // const postcodes = Object.values(locations);
        // const result = postcodes.filter( elem =>  Number(elem.split('')[0]) === code );
        // return result;
        return locations[code];
    }
    function generate_postcode_options( selectElem, code ){
        const postcode = get_location_list( code );
        selectElem.find('option').not(':first').remove();
        selectElem.prop('disabled', true );
        if( !postcode.length ){   
            alert( 'Cannot find postcode for the selection options' );
            return false;
        }
        selectElem.prop('disabled', false ); 
        postcode.forEach( function( value ){
            selectElem.append(new Option( value, value ));
        });
    }
    function calculate_total_qty( ){
        let totalQty = 0;
        packageTable.find('tbody tr').each(function(){
            const value = $(this).find('.wpstl-qty').val();
            if( isNaN(value) ){
                return;
            }
            totalQty += Number( value );
        });
        calculate_total_weight( )
        packageTable.find( 'tfoot #wpcstl-total-qty' ).val( totalQty );
    }
    function calculate_total_weight( ){
        let totalWeight = 0;
        packageTable.find('tbody tr').each(function(){
            let qty       = $(this).find('.wpstl-qty').val();
            let weight    = $(this).find('.wpstl-weight').val();
            qty           = isNaN(qty) ? 0 : qty;
            weight        = isNaN(weight) ? 0 : weight;
            totalWeight   += Number( qty ) * Number( weight );
        });
        packageTable.find( 'tfoot #wpcstl-total-weight' ).val( totalWeight );
    }
    // Run Phone Formatter
    intlTelInputScript();
    // Auto Generate Postcode 
    $('#wpcsr-findrate').on('change', '.wpcstl-location',function(){
        /*
         * 6 - Syndney
         * 5 - Melbourne
         * 4 - Brisbane
         **/
        let code            = 0;
        const selectElem    = $(this).closest('.wpcstl-option-wrapper').find('.wpcstl-postcode');
        switch( $(this).val() ) {
            case '5':
                code = 'sydney';
                break;
            case '6':
                code = 'melbourne';
                break;
            case '7':
                code = 'brisbane';
                break;
            default:
                // code block
        }

        if( $(this).hasClass('wpcstl-origin') ){
            if( code == 'melbourne'){
                /*
                 * PLEASE CHANGE ME into 'sydney' code
                 **/
                $('#wpcsr-findrate select.wpcstl-destination').val( 5 ).trigger('change');
                $('#wpcsr-findrate select.wpcstl-destination').attr('readonly', true);
                $('#wpcsr-findrate select.wpcstl-destination option[value!="5"]').attr("disabled", true);
            }else{
                $('#wpcsr-findrate select.wpcstl-destination').val('');
                $('#wpcsr-findrate select.wpcstl-destination').attr('readonly', false);
                $('#wpcsr-findrate select.wpcstl-destination option').attr("disabled", false);
                $('#destination_postcode').find('option').not(':first').remove();
            }
        }   

        generate_postcode_options( selectElem, code );
    });
    // Auto calculate total quantity and weight
    packageTable.on('keyup', '.wpstl-qty', function(){
        calculate_total_qty( );
    });
    packageTable.on('keyup', '.wpstl-weight', function(){
        if( Number($(this).val()) > 800 ){
            $(this).val( 800 );
            alert( 'Weight exceeded the maximum weight of 800Kg.' );
        }
        calculate_total_weight( );
    });
    packageTable.on('keyup', '.wpstl-length, .wpstl-width, .wpstl-height', function(){
        const limitValue    = $(this).hasClass('wpstl-height') ? 150 : 115 ;
        const elemLabel     = $(this).attr('data-label');
        if( Number($(this).val()) > limitValue ){
            $(this).val( limitValue );
            alert( elemLabel+' exceeded the maximum weight of '+limitValue+'cm.' );
        }
    });
    // Print Barcode
    $('.wpcstl-barcode').on('click', '.wpcstl-print-barcode', function(e){
        e.preventDefault();
        var shipmentID  = $(this).attr('data-id');
        $.ajax({
            type:"POST",
            data:{
                action  : 'wpcstl_print_barcode',    
                shipmentID   : shipmentID
            },
            url : wpstlAjaxHandler.ajaxurl,
            beforeSend:function(){
                $('body').append('<div class="wpcargo-loading">Loading...</div>');
            },
            success:function( response ){
                $('body .wpcargo-loading').remove();
                $data = JSON.parse(response);
                if($.isEmptyObject($data)) {
                    alert( 'Download Barcode file Error.' );
                    return;
                } else {
                    $('.wpcfe-shipments').each( function(){ //iterate all listed checkbox items
                        this.checked = status; //change ".checkbox" checked status
                    });
                    download_file( $data.file_url, $data.file_name );
                    return;
                }
            }
        });
    });
    $('#wpcstl-packages').on('click', '.wpcstl-print-pbarcode', function(e){
        e.preventDefault();
        var pallet      = $(this).attr('data-pallet');
        var shipmentID  = $(this).attr('data-id');
        $.ajax({
            type:"POST",
            data:{
                action  : 'wpcstl_print_pallet',    
                shipmentID  : shipmentID,
                pallet  : pallet,
            },
            url : wpstlAjaxHandler.ajaxurl,
            beforeSend:function(){
                $('body').append('<div class="wpcargo-loading">Loading...</div>');
            },
            success:function( response ){
                $('body .wpcargo-loading').remove();
                $data = JSON.parse(response);
                if($.isEmptyObject($data)) {
                    alert( 'Download Barcode file Error.' );
                    return;
                } else {
                    $('.wpcfe-shipments').each( function(){ //iterate all listed checkbox items
                        this.checked = status; //change ".checkbox" checked status
                    });
                    download_file( $data.file_url, $data.file_name );
                    return;
                }
            }
        });
    });
});