wpsl-admin.js 45.7 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247
jQuery( document ).ready( function( $ ) {
    var map, geocoder, startLatLng, markersArray = [],
        wpslAdmin = wpslAdmin || {};

    /**
     * Verify the provided API keys
     *
     * @since 2.2.22
     */
    wpslAdmin.verifyKeys = {
        init: function() {
            var self       = this,
                $btn       = $( "#wpsl-verify-keys" ),
                preloader  = wpslSettings.url + "img/ajax-loader.gif",
                mapService = ( typeof wpslSettings.mapService !== "undefined" ) ? wpslSettings.mapService : "gmaps";

            $btn.on( "click", function() {
                $( "#wpsl-wrap .notice" ).remove();

                self[mapService].check();

                $btn.after( '<img src="' + preloader + '" class="wpsl-api-key-preloader" />' );

                return false;
            });
        },
        /**
         * Show the status of the API keys.
         *
         * @since 2.2.22
         * @param {string} response   The API response
         * @param {string} keyType 	   The type of API key we need to show the notice for
         * @param {string} noticeType Show either an error or success notice.
         * @returns {void}
         */
        showStatus: function( response, keyType, noticeType = "error" ) {

            this.createNotice( response, keyType, noticeType );

            // After the browser check has finished we remove the preloader.
            if ( keyType == "browser" ) {
                $( ".wpsl-api-key-preloader" ).remove();
            }
        },
        /**
         * Create the error notice.
         *
         * @since 2.2.10
         * @param {string} response   The API response to show
         * @param {string} keyType 	   The type of API key we need to show the notice for
         * @param {string} noticeType Show either an error or success notice.
         * @returns void
         */
        createNotice: function( response, keyType, noticeType ) {
            var notice, noticeLocation, cssClass;

            cssClass = ( noticeType == "error" ) ? "error" : "updated";

            notice = '<div class="' + cssClass + ' notice is-dismissible">';
            notice += '<p><strong>' + response + '</strong></p>';
            notice += '<button type="button" class="notice-dismiss"><span class="screen-reader-text">' + wpslL10n.dismissNotice + '</span></button>';
            notice += '</div>';

            noticeLocation = ( $( "#wpsl-tabs" ).length ) ? "wpsl-tabs" : "wpsl-settings-form";

            $( "#" + noticeLocation + "" ).before( notice );

            if ( noticeType == "error" ) {
                $( "#wpsl-api-" + keyType + "-key" ).addClass( "wpsl-error" );
            } else {
                $( "#wpsl-api-" + keyType + "-key" ).removeClass( "wpsl-error" );
            }
        },
        gmaps: {
            /**
             * Check for any issues with the used API keys.
             *
             * @since   2.2.22
             * @returns {void}
             */
            check: function() {
                this.server(function() {
                    wpslAdmin.verifyKeys.gmaps.browser();
                });
            },
            /**
             * Make a request to the Google Geocode API to
             * check if the server key is valid or not.
             *
             * @since   2.2.22
             * @returns {void}
             */
            server: function( callback ) {
                var status,
                    ajaxData = {
                        action: "validate_server_key",
                        server_key: $( "#wpsl-api-server-key" ).val()
                    };

                if ( ajaxData.server_key ) {
                    $.get( wpslSettings.ajaxurl, ajaxData, function( response ) {
                        status = ( response.valid ) ? "updated" : "error";

                        wpslAdmin.verifyKeys.showStatus( response.msg, "server", status );

                        callback();
                    });
                } else {
                    wpslAdmin.verifyKeys.showStatus( wpslL10n.serverKeyMissing, "server" );

                    callback();
                }
            },
            /**
             * Make a request to the Google JavaScript API to
             * check if the browser key is valid or not.
             *
             * @since   2.2.22
             * @returns {void}
             */
            browser: function() {
                var browserAPICheck,
                    browserKey = $( "#wpsl-api-browser-key" ).val();

                if ( browserKey ) {

                    /**
                     * Wait 3 seconds before checking if the
                     * Geocode API returned data.
                     *
                     * If this hasn't happened, then there has to
                     * be a problem with the API keys.
                     */
                    browserAPICheck = setInterval(function() {
                        wpslAdmin.verifyKeys.showStatus( wpslL10n.browserKeyError, "browser" );

                        clearInterval( browserAPICheck );
                    }, 3000 );

                    /**
                     * This will only complete if there are no issues
                     * with the API key, otherwise it won't even make a request.
                     *
                     * To check this we use the setInterval in the above section.
                     */
                    geocoder.geocode( { 'address': 'Manhattan, NY 10036, USA' }, function( response, status ) {
                        if ( status == google.maps.GeocoderStatus.OK ) {
                            wpslAdmin.verifyKeys.showStatus( wpslL10n.browserKeySuccess, "browser", "success" );
                        } else {
                            wpslAdmin.verifyKeys.showStatus( wpslL10n.browserKeyError, "browser" );
                        }

                        clearInterval( browserAPICheck );
                    });
                } else {
                    wpslAdmin.verifyKeys.showStatus( wpslL10n.browserKeyMissing, "browser" );
                }
            }
        }
    };

    /**
     * Handle the Geocode requests made from
     * the Tools section on the settings page.
     *
     * This can be used to check the API response
     * for any input the user provides, and see if
     * it's in the expected location.
     *
     * Will show error messages if there are any
     * issues with the used browser API keys.
     *
     * @since 2.2.22
     */
    wpslAdmin.showApiResponse = {
        init: function() {
            var $geocodeInput = $( "#wpsl-geocode-input" ),
                self          = this,
                mapLoaded     = false;

            $( "#wpsl-show-geocode-response" ).on( "click", function( e ) {
                self.createDialog();

                initializeGmap("wpsl-geocode-preview" );

                // Make sure we don't add the same message twice.
                if ( !$( ".wpsl-geocode-warning span" ).length ) {
                    self.createRestrictionsMsg();
                }

                // Check for map errors after it finished loading.
                google.maps.event.addListenerOnce( map, "tilesloaded", function() {
                    mapLoaded = true;
                    self.checkQuotaError();
                });

                // Check if the map was load succesfully, if not show an error message explaining it.
                setTimeout(function() {
                    if ( !mapLoaded ) {
                        $(".wpsl-geocode-warning, #wpsl-geocode-test input, #wpsl-geocode-tabs").remove();
                        $(".wpsl-geocode-api-notice").show().html( wpslL10n.loadingFailed );
                    }
                }, 1000 );

                return false;
            });

            // Submit the geocode request.
            $( "#wpsl-geocode-submit" ).on( "click", function( e ) {
                $geocodeInput.removeClass( "wpsl-error" );

                if ( !$geocodeInput.val() ) {
                    $geocodeInput.addClass( "wpsl-error" );
                    $( ".wpsl-geocode-api-notice" ).hide();
                } else {
                    self.geocoding.makeRequest();
                }
            });

            // Handle users using the enter key in the dialog box.
            $( "#wpsl-geocode-test" ).keydown( function( event ) {
                var keyCode = ( event.keyCode ? event.keyCode : event.which );

                if ( keyCode == 13 ) {
                    $( "#wpsl-geocode-submit" ).trigger( "click" );
                }
            });
        },
        /**
         * Create the dialog box
         *
         * @since   2.2.22
         * @returns {void}
         */
        createDialog: function() {
            $( "#wpsl-geocode-test" ).dialog({
                resizable: false,
                height: "auto",
                width: 550,
                modal: true,
                open: function() {

                    // Move it closer to the top then it normally would
                    $( this ).parent().css({ "top": window.pageYOffset + 50 });

                    $( "#wpsl-geocode-tabs" ).tabs();
                    $( "#wpsl-geocode-input" ).focus();
                    $( ".wpsl-geocode-api-notice" ).hide();

                    // Make sure the first tab is always selected after the dialog is opened a second time
                    $( "#wpsl-geocode-tabs" ).tabs( "option", "active", $( "li" ).index( $( "li:visible:eq(0)" ) ) );

                    // Make sure to remove any previous input
                    $( "#wpsl-geocode-input, #wpsl-geocode-response textarea" ).val( "" );

                    $( ".ui-widget-overlay" ).bind( "click", function() {
                        $( "#wpsl-geocode-test" ).dialog( "close" );
                    });
                },
                buttons: {
                    Cancel: function() {
                        $( this ).dialog( "close" );
                    }
                }
            });
        },
        /**
         * If there's a problem with the billing account,
         * then a 'dismissButton' class will exist in the map itself.
         *
         * If this is the case, then we remove everything and
         * show an error explaining the problem.
         *
         * @since   2.2.22
         * @returns {void}
         */
        checkQuotaError: function() {

            setTimeout(function() {
                if ( $( "#wpsl-geocode-preview .dismissButton" ).length > 0 ) {
                    $( ".wpsl-geocode-warning, #wpsl-geocode-test input" ).remove();

                    $( ".wpsl-geocode-api-notice" ).show();
                    $( ".wpsl-geocode-api-notice span" ).html( wpslL10n.loadingError );
                }

            }, 1000 );
        },
        /**
         * Create a message explaning the user that the
         * results are restricted to the selected map region,
         * and possibly only work for zip codes.
         *
         * @since   2.2.22
         * @returns {void}
         */
        createRestrictionsMsg: function() {
            var countryName, zipcodeOnly,
                $warningElem = $( ".wpsl-geocode-warning" ).show().find( "strong" );

            if ( $( "#wpsl-api-region" ).val() ) {
                countryName = $( "#wpsl-api-region option:selected" ).text();
                zipcodeOnly = ( $( "#wpsl-force-postalcode" ).is( ":checked" ) ) ? wpslL10n.restrictedZipCode : '';

                $warningElem.after( "<span>" + wpslL10n.resultsWarning + ' ' + countryName + ' ' + zipcodeOnly + "</span>" );
            } else {
                $warningElem.after( "<span>" + wpslL10n.noRestriction + "</span>" );

                $( ".wpsl-region-href" ).on( "click", function() {
                    $( ".ui-widget-overlay" ).trigger( "click" );
                });
            }
        },
        geocoding: {
            /**
             * Geocode the provided user input
             *
             * @since   2.2.22
             * @returns {void}
             */
            makeRequest: function() {
                var request = this.createParams();

                geocoder.geocode( request, function( response, status ) {

                    // Show an error message if there is a problem with the browser API key.
                    if ( status == "OK" || status == "ZERO_RESULTS" ) {

                        // Make sure to remove the marker from the map if one exists.
                        if ( typeof markersArray[0] !== "undefined" ) {
                            markersArray[0].setMap( null );
                            markersArray.length = 0;
                        }

                        if ( status == "OK" ) {
                            addMarker( response[0].geometry.location, false );

                            map.setZoom( 12 );
                            map.setCenter( response[0].geometry.location );
                        } else {
                            map.setZoom( parseInt( wpslSettings.defaultZoom ) );
                            map.setCenter( startLatLng );
                        }
                    } else {
                        status = wpslL10n.browserKeyError;

                        $( "#wpsl-geocode-preview, #wpsl-geocode-response textarea" ).remove();
                    }

                    $( ".wpsl-geocode-api-notice" ).show();
                    $( ".wpsl-geocode-api-notice span" ).html( status );
                    $( "#wpsl-geocode-response textarea" ).val( JSON.stringify( response, null, 4 ) );
                });
            },
            /**
             * Create the params used in the geocode request
             * made through the test tool in the tools section.
             *
             * @since  2.2.22
             * @return {object} request The parameters included in the geocode API request
             */
            createParams: function() {
                var request = {};

                // Check if we need to set the geocode component restrictions.
                if ( typeof wpslSettings.geocodeComponents !== "undefined" && !$.isEmptyObject( wpslSettings.geocodeComponents ) ) {
                    request.componentRestrictions = wpslSettings.geocodeComponents;

                    if ( typeof request.componentRestrictions.postalCode !== "undefined" ) {
                        request.componentRestrictions.postalCode = $( "#wpsl-geocode-input" ).val();
                    } else {
                        request.address = $( "#wpsl-geocode-input" ).val();
                    }
                } else {
                    request.address = $( "#wpsl-geocode-input" ).val();
                }

                return request;
            },
        },
    };

    if ( $( "#wpsl-gmap-wrap" ).length ) {
        initializeGmap();
    }

    /**
     * If we are on the settings page, then init the API tools.
     */
    if ( $( "#wpsl-map-settings").length ) {
        wpslAdmin.verifyKeys.init();
        wpslAdmin.showApiResponse.init();
    }

    /**
     * Initialize the map with the correct settings.
     *
     * @since	1.0.0
     * @param   string mapId The ID of the element to render the map in
     * @returns {void}
     */
    function initializeGmap( mapId = "wpsl-gmap-wrap" ) {
        var defaultLatLng = wpslSettings.defaultLatLng.split( "," ),
            mapOptions;

        startLatLng = new google.maps.LatLng( defaultLatLng[0], defaultLatLng[1] );
        mapOptions  = {
            zoom: parseInt( wpslSettings.defaultZoom ),
            center: startLatLng,
            mapTypeId: google.maps.MapTypeId[ wpslSettings.mapType.toUpperCase() ],
            mapTypeControl: false,
            streetViewControl: false,
            zoomControlOptions: {
                position: google.maps.ControlPosition.RIGHT_TOP
            }
        };

        geocoder = new google.maps.Geocoder();
        map		  = new google.maps.Map( document.getElementById( mapId ), mapOptions );

        checkEditStoreMarker();
    }

    /**
     * Check if we have an existing latlng value.
     *
     * If there is an latlng value, then we add a marker to the map.
     * This can only happen on the edit store page.
     *
     * @since	1.0.0
     * @returns {void}
     */
    function checkEditStoreMarker() {
        var location,
            lat = $( "#wpsl-lat" ).val(),
            lng = $( "#wpsl-lng" ).val();

        if ( ( lat ) && ( lng ) ) {
            location = new google.maps.LatLng( lat, lng );

            map.setCenter( location );
            map.setZoom( 16 );
            addMarker( location );
        }
    }

    // If we have a city/country input field enable the autocomplete.
    if ( $( "#wpsl-start-name" ).length ) {
        activateAutoComplete();
    }

    /**
     * Activate the autocomplete function for the city/country field.
     *
     * @since	1.0.0
     * @returns {void}
     */
    function activateAutoComplete() {
        var latlng,
            input = document.getElementById( "wpsl-start-name" ),
            options = {
                types: ['geocode']
            },
            autocomplete = new google.maps.places.Autocomplete( input, options );

        google.maps.event.addListener( autocomplete, "place_changed", function() {
            latlng = autocomplete.getPlace().geometry.location;
            setLatlng( latlng, "zoom" );
        });
    }

    /**
     * Add a new marker to the map based on the provided location (latlng).
     *
     * @since	1.0.0
     * @param   {object}  location   The latlng value
     * @param   {boolean} draggable Whether the marker should be draggable or not
     * @returns {void}
     */
    function addMarker( location, draggable = true ) {
        var marker = new google.maps.Marker({
            position: location,
            map: map,
            draggable: draggable
        });

        markersArray.push( marker );

        // If the marker is dragged on the map, make sure the latlng values are updated.
        google.maps.event.addListener( marker, "dragend", function() {
            setLatlng( marker.getPosition(), "store" );
        });
    }

    // Lookup the provided location with the Google Maps API.
    $( "#wpsl-lookup-location" ).on( "click", function( e ) {
        e.preventDefault();
        codeAddress();
    });

    /**
     * Update the hidden input field with the current latlng values.
     *
     * @since	1.0.0
     * @param   {object} latLng The latLng values
     * @param   {string} target The location where we need to set the latLng
     * @returns {void}
     */
    function setLatlng( latLng, target ) {
        var coordinates = stripCoordinates( latLng ),
            lat			= roundCoordinate( coordinates[0] ),
            lng			= roundCoordinate( coordinates[1] );

        if ( target == "store" ) {
            $( "#wpsl-lat" ).val( lat );
            $( "#wpsl-lng" ).val( lng );
        } else if ( target == "zoom" ) {
            $( "#wpsl-latlng" ).val( lat + ',' + lng );
        }
    }

    /**
     * Geocode the user input.
     *
     * @since	1.0.0
     * @returns {void}
     */
    function codeAddress() {
        var filteredResponse, geocodeAddress;

        // Check if we have all the required data before attempting to geocode the address.
        if ( !validatePreviewFields() ) {
            geocodeAddress = createGeocodeAddress();

            geocoder.geocode( { 'address': geocodeAddress }, function( response, status ) {
                if ( status === google.maps.GeocoderStatus.OK ) {

                    // If we have a previous marker on the map we remove it.
                    if ( typeof( markersArray[0] ) !== "undefined" ) {
                        if ( markersArray[0].draggable ) {
                            markersArray[0].setMap( null );
                            markersArray.splice(0, 1);
                        }
                    }

                    // Center and zoom to the searched location.
                    map.setCenter( response[0].geometry.location );
                    map.setZoom( 16 );

                    addMarker( response[0].geometry.location );
                    setLatlng( response[0].geometry.location, "store" );

                    filteredResponse = filterApiResponse( response );

                    $( "#wpsl-country" ).val( filteredResponse.country.long_name );
                    $( "#wpsl-country_iso" ).val( filteredResponse.country.short_name );
                } else {
                    alert( wpslL10n.geocodeFail + ": " + status );
                }
            });

            return false;
        } else {
            activateStoreTab( "first" );

            alert( wpslL10n.missingGeoData );

            return true;
        }
    }

    /**
     * Check that all required fields for the map preview are there.
     *
     * @since	1.0.0
     * @returns {boolean} error  Whether all the required fields contained data.
     */
    function validatePreviewFields() {
        var i, fieldData, requiredFields,
            error = false;

        $( ".wpsl-store-meta input" ).removeClass( "wpsl-error" );

        // Check which fields are required.
        if ( typeof wpslSettings.requiredFields !== "undefined" && _.isArray( wpslSettings.requiredFields ) ) {
            requiredFields = wpslSettings.requiredFields;

            // Check if all the required fields contain data.
            for ( i = 0; i < requiredFields.length; i++ ) {
                fieldData = $.trim( $( "#wpsl-" + requiredFields[i] ).val() );

                if ( !fieldData ) {
                    $( "#wpsl-" + requiredFields[i] ).addClass( "wpsl-error" );
                    error = true;
                }

                fieldData = '';
            }
        }

        return error;
    }

    /**
     * Build the address that's send to the Geocode API.
     *
     * @since	2.1.0
     * @returns {string} geocodeAddress The address separated by , that's send to the Geocoder.
     */
    function createGeocodeAddress() {
        var i, part,
            address      = [],
            addressParts = [ "address", "city", "state", "zip", "country" ];

        for ( i = 0; i < addressParts.length; i++ ) {
            part = $.trim( $( "#wpsl-" + addressParts[i] ).val() );

            /*
             * At this point we already know the address, city and country fields contain data.
             * But no need to include the zip and state if they are empty.
             */
            if ( part ) {
                address.push( part );
            }

            part = "";
        }

        return address.join();
    }

    /**
     * Filter out the country name from the API response.
     *
     * @since	1.0.0
     * @param   {object} response	   The response of the geocode API
     * @returns {object} collectedData The short and long country name
     */
    function filterApiResponse( response ) {
        var i, responseType, collectedData,
            country		  = {},
            addressLength = response[0].address_components.length;

        // Loop over the API response.
        for ( i = 0; i < addressLength; i++ ) {
            responseType = response[0].address_components[i].types;

            // Filter out the country name.
            if ( /^country,political$/.test( responseType ) ) {
                country = {
                    long_name: response[0].address_components[i].long_name,
                    short_name: response[0].address_components[i].short_name
                };
            }
        }

        collectedData = {
            country: country
        };

        return collectedData;
    }

    /**
     * Round the coordinate to 6 digits after the comma.
     *
     * @since	1.0.0
     * @param   {string} coordinate   The coordinate
     * @returns {number} roundedCoord The rounded coordinate
     */
    function roundCoordinate( coordinate ) {
        var roundedCoord, decimals = 6;

        roundedCoord = Math.round( coordinate * Math.pow( 10, decimals ) ) / Math.pow( 10, decimals );

        return roundedCoord;
    }

    /**
     * Strip the '(' and ')' from the captured coordinates and split them.
     *
     * @since	1.0.0
     * @param   {string} coordinates The coordinates
     * @returns {object} latLng      The latlng coordinates
     */
    function stripCoordinates( coordinates ) {
        var latLng    = [],
            selected  = coordinates.toString(),
            latLngStr = selected.split( ",", 2 );

        latLng[0] = latLngStr[0].replace( "(", "" );
        latLng[1] = latLngStr[1].replace( ")", "" );

        return latLng;
    }

    $( ".wpsl-marker-list input[type=radio]" ).click( function() {
        $( this ).parents( ".wpsl-marker-list" ).find( "li" ).removeClass();
        $( this ).parent( "li" ).addClass( "wpsl-active-marker" );
    });

    $( ".wpsl-marker-list li" ).click( function() {
        $( this ).parents( ".wpsl-marker-list" ).find( "input" ).prop( "checked", false );
        $( this ).find( "input" ).prop( "checked", true );
        $( this ).siblings().removeClass();
        $( this ).addClass( "wpsl-active-marker" );
    });

    // Detect changes in checkboxes that have a conditional option.
    $( ".wpsl-has-conditional-option" ).on( "change", function() {
        $( this ).parent().next( ".wpsl-conditional-option" ).toggle();
    });

    /*
     * Detect changes to the store template dropdown. If the template is selected to
     * show the store list under the map then we show the option to hide the scrollbar.
     */
    $( "#wpsl-store-template" ).on( "change", function() {
        var $scrollOption = $( "#wpsl-listing-below-no-scroll" );

        if ( $( this ).val() == "below_map" ) {
            $scrollOption.show();
        } else {
            $scrollOption.hide();
        }
    });

    $( "#wpsl-api-region" ).on( "change", function() {
        var $geocodeComponent = $( "#wpsl-geocode-component" );

        if ( $( this ).val() ) {
            $geocodeComponent.show();
        } else {
            $geocodeComponent.hide();
        }
    });

    // Make sure the correct hour input format is visible.
    $( "#wpsl-editor-hour-input" ).on( "change", function() {
        $( ".wpsl-" + $( this ).val() + "-hours" ).show().siblings( "div" ).hide();
        $( ".wpsl-hour-notice" ).toggle();
    });

    // Set the correct tab to active and show the correct content block.
    $( "#wpsl-meta-nav li" ).on( "click", function( e ) {
        var activeClass = $( this ).attr( "class" );
        activeClass = activeClass.split( "-tab" );

        e.stopPropagation();

        // Set the correct tab and metabox to active.
        $( this ).addClass( "wpsl-active" ).siblings().removeClass( "wpsl-active" );
        $( ".wpsl-store-meta ." + activeClass[0] + "" ).show().addClass( "wpsl-active" ).siblings( "div" ).hide().removeClass( "wpsl-active" );
    });

    // Make sure the required store fields contain data.
    if ( $( "#wpsl-store-details" ).length ) {
        $( "#publish" ).click( function() {
            var firstErrorElem, currentTabClass, elemClass,
                errorMsg	= '<div id="message" class="error"><p>' + wpslL10n.requiredFields + '</p></div>',
                missingData = false;

            // Remove error messages and css classes from previous submissions.
            $( "#wpbody-content .wrap #message" ).remove();
            $( ".wpsl-required" ).removeClass( "wpsl-error" );

            // Loop over the required fields and check for a value.
            $( ".wpsl-required" ).each( function() {
                if ( $( this ).val() == "" ) {
                    $( this ).addClass( "wpsl-error" );

                    if ( typeof firstErrorElem === "undefined" ) {
                        firstErrorElem = getFirstErrorElemAttr( $( this ) );
                    }

                    missingData = true;
                }
            });

            // If one of the required fields are empty, then show the error msg and make sure the correct tab is visible.
            if ( missingData ) {
                $( "#wpbody-content .wrap > h2" ).after( errorMsg );

                if ( typeof firstErrorElem.val !== "undefined" ) {
                    if ( firstErrorElem.type == "id" ) {
                        currentTabClass = $( "#" + firstErrorElem.val + "" ).parents( ".wpsl-tab" ).attr( "class" );
                        $( "html, body" ).scrollTop( Math.round( $( "#" + firstErrorElem.val + "" ).offset().top - 100 ) );
                    } else if ( firstErrorElem.type == "class" ) {
                        elemClass		= firstErrorElem.val.replace( /wpsl-required|wpsl-error/g, "" );
                        currentTabClass = $( "." + elemClass + "" ).parents( ".wpsl-tab" ).attr( "class" );
                        $( "html, body" ).scrollTop( Math.round( $( "." + elemClass + "" ).offset().top - 100 ) );
                    }

                    currentTabClass = $.trim( currentTabClass.replace( /wpsl-tab|wpsl-active/g, "" ) );
                }

                // If we don't have a class of the tab that should be set to visible, we just show the first one.
                if ( !currentTabClass ) {
                    activateStoreTab( 'first' );
                } else {
                    activateStoreTab( currentTabClass );
                }

                /*
                 * If not all required fields contains data, and the user has
                 * clicked the submit button. Then an extra css class is added to the
                 * button that will disabled it. This only happens in WP 3.8 or earlier.
                 *
                 * We need to make sure this css class doesn't exist otherwise
                 * the user can never resubmit the page.
                 */
                $( "#publish" ).removeClass( "button-primary-disabled" );
                $( ".spinner" ).hide();

                return false;
            } else {
                return true;
            }
        });
    }

    /**
     * Set the correct tab to visible, and hide all other metaboxes
     *
     * @since	2.0.0
     * @param   {string} $target The name of the tab to show
     * @returns {void}
     */
    function activateStoreTab( $target ) {
        if ( $target == 'first' ) {
            $target = ':first-child';
        } else {
            $target = '.' + $target;
        }

        if ( !$( "#wpsl-meta-nav li" + $target + "-tab" ).hasClass( "wpsl-active" ) ) {
            $( "#wpsl-meta-nav li" + $target + "-tab" ).addClass( "wpsl-active" ).siblings().removeClass( "wpsl-active" );
            $( ".wpsl-store-meta > div" + $target + "" ).show().addClass( "wpsl-active" ).siblings( "div" ).hide().removeClass( "wpsl-active" );
        }
    }

    /**
     * Get the id or class of the first element that's an required field, but is empty.
     *
     * We need this to determine which tab we need to set active,
     * which will be the tab were the first error occured.
     *
     * @since	2.0.0
     * @param   {object} elem			The element the error occured on
     * @returns {object} firstErrorElem The id/class set on the first elem that an error occured on and the attr value
     */
    function getFirstErrorElemAttr( elem ) {
        var firstErrorElem = { "type": "id", "val" : elem.attr( "id" ) };

        // If no ID value exists, then check if we can get the class name.
        if ( typeof firstErrorElem.val === "undefined" ) {
            firstErrorElem = { "type": "class", "val" : elem.attr( "class" ) };
        }

        return firstErrorElem;
    }

    // If we have a store hours dropdown, init the event handler.
    if ( $( "#wpsl-store-hours" ).length ) {
        initHourEvents();
    }

    /**
     * Assign an event handler to the button that enables
     * users to remove an opening hour period.
     *
     * @since	2.0.0
     * @returns {void}
     */
    function initHourEvents() {
        $( "#wpsl-store-hours .wpsl-icon-cancel-circled" ).off();
        $( "#wpsl-store-hours .wpsl-icon-cancel-circled" ).on( "click", function() {
            removePeriod( $( this ) );
        });
    }

    // Add new openings period to the openings hours table.
    $( ".wpsl-add-period" ).on( "click", function( e ) {
        var newPeriod,
            hours		= {},
            returnList  = true,
            $tr			= $( this ).parents( "tr" ),
            periodCount = currentPeriodCount( $( this ) ),
            periodCss   = ( periodCount >= 1 ) ? "wpsl-current-period wpsl-multiple-periods" : "wpsl-current-period",
            day 	    = $tr.find( ".wpsl-opening-hours" ).attr( "data-day" ),
            selectName  = ( $( "#wpsl-settings-form" ).length ) ? "wpsl_editor[dropdown]" : "wpsl[hours]";

        newPeriod = '<div class="' + periodCss +'">';
        newPeriod += '<select autocomplete="off" name="' + selectName + '[' + day + '_open][]" class="wpsl-open-hour">' + createHourOptionList( returnList ) + '</select>';
        newPeriod += '<span> - </span>';
        newPeriod += '<select autocomplete="off" name="' + selectName + '[' + day + '_close][]" class="wpsl-close-hour">' + createHourOptionList( returnList ) + '</select>';
        newPeriod += '<div class="wpsl-icon-cancel-circled"></div>';
        newPeriod += '</div>';

        $tr.find( ".wpsl-store-closed" ).remove();
        $( "#wpsl-hours-" + day + "" ).append( newPeriod ).end();

        initHourEvents();

        if ( $( "#wpsl-editor-hour-format" ).val() == 24 ) {
            hours = {
                "open": "09:00",
                "close": "17:00"
            };
        } else {
            hours = {
                "open": "9:00 AM",
                "close": "5:00 PM"
            };
        }

        $tr.find( ".wpsl-open-hour:last option[value='" + hours.open + "']" ).attr( "selected", "selected" );
        $tr.find( ".wpsl-close-hour:last option[value='" + hours.close + "']" ).attr( "selected", "selected" );

        e.preventDefault();
    });

    /**
     * Remove an openings period
     *
     * @since  2.0.0
     * @param  {object} elem The clicked element
     * @return {void}
     */
    function removePeriod( elem ) {
        var periodsLeft	= currentPeriodCount( elem ),
            $tr			= elem.parents( "tr" ),
            day 	    = $tr.find( ".wpsl-opening-hours" ).attr( "data-day" );

        // If there was 1 opening hour left then we add the 'Closed' text.
        if ( periodsLeft == 1 ) {
            $tr.find( ".wpsl-opening-hours" ).html( "<p class='wpsl-store-closed'>" + wpslL10n.closedDate + "<input type='hidden' name='wpsl[hours][" + day + "_open]' value='' /></p>" );
        }

        // Remove the selected openings period.
        elem.parent().closest( ".wpsl-current-period" ).remove();

        // If the first element has the multiple class, then we need to remove it.
        if ( $tr.find( ".wpsl-opening-hours div:first-child" ).hasClass( "wpsl-multiple-periods" ) ) {
            $tr.find( ".wpsl-opening-hours div:first-child" ).removeClass( "wpsl-multiple-periods" );
        }
    }

    /**
     * Count the current opening periods in a day block
     *
     * @since  2.0.0
     * @param  {object} elem		   The clicked element
     * @return {string} currentPeriods The ammount of period divs found
     */
    function currentPeriodCount( elem ) {
        var currentPeriods = elem.parents( "tr" ).find( ".wpsl-current-period" ).length;

        return currentPeriods;
    }

    /**
     * Create an option list with the correct opening hour format and interval
     *
     * @since  2.0.0
     * @param  {string} returnList Whether to return the option list or call the setSelectedOpeningHours function
     * @return {mixed}  optionList The html for the option list of or void
     */
    function createHourOptionList( returnList ) {
        var openingHours, openingHourInterval, hour, hrFormat,
            pm   			   = false,
            twelveHrsAfternoon = false,
            pmOrAm			   = "",
            optionList		   = "",
            openingTimes 	   = [],
            openingHourOptions = {
                "hours": {
                    "hr12": [ 12, 1, 2, 3 ,4 ,5 ,6, 7, 8, 9, 10, 11, 12, 1, 2, 3 , 4, 5, 6, 7, 8, 9, 10, 11 ],
                    "hr24": [ 0, 1, 2, 3 ,4 ,5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 ,16, 17, 18, 19, 20, 21, 22, 23 ]
                },
                "interval": [ '00', '15', '30', '45' ]
            };

        if ( $( "#wpsl-editor-hour-format" ).length ) {
            hrFormat = $( "#wpsl-editor-hour-format" ).val();
        } else {
            hrFormat = wpslSettings.hourFormat;
        }

        $( "#wpsl-store-hours td" ).removeAttr( "style" );

        if ( hrFormat == 12 ) {
            $( "#wpsl-store-hours" ).removeClass().addClass( "wpsl-twelve-format" );
            openingHours = openingHourOptions.hours.hr12;
        } else {
            $( "#wpsl-store-hours" ).removeClass().addClass( "wpsl-twentyfour-format" );
            openingHours = openingHourOptions.hours.hr24;
        }

        openingHourInterval = openingHourOptions.interval;

        for ( var i = 0; i < openingHours.length; i++ ) {
            hour = openingHours[i];

            /*
             * If the 12hr format is selected, then check if we need to show AM or PM.
             *
             * If the 24hr format is selected and the hour is a single digit
             * then we add a 0 to the start so 5:00 becomes 05:00.
             */
            if ( hrFormat == 12 ) {
                if ( hour >= 12 ) {
                    pm = ( twelveHrsAfternoon ) ? true : false;

                    twelveHrsAfternoon = true;
                }

                pmOrAm = ( pm ) ? "PM" : "AM";
            } else if ( ( hrFormat == 24 ) && ( hour.toString().length == 1 ) ) {
                hour = "0" + hour;
            }

            // Collect the new opening hour format and interval.
            for ( var j = 0; j < openingHourInterval.length; j++ ) {
                openingTimes.push( hour + ":" + openingHourInterval[j] + " " + pmOrAm );
            }
        }

        // Create the <option> list.
        for ( var i = 0; i < openingTimes.length; i++ ) {
            optionList = optionList + '<option value="' + $.trim( openingTimes[i] ) + '">' + $.trim( openingTimes[i] ) + '</option>';
        }

        if ( returnList ) {
            return optionList;
        } else {
            setSelectedOpeningHours( optionList, hrFormat );
        }
    }

    /**
     * Set the correct selected opening hour in the dropdown
     *
     * @since  2.0.0
     * @param  {string} optionList The html for the option list
     * @param  {string} hrFormat   The html for the option list
     * @return {void}
     */
    function setSelectedOpeningHours( optionList, hrFormat ) {
        var splitHour, hourType, periodBlock,
            hours = {};

        /*
         * Loop over each open/close block and make sure the selected
         * value is still set as selected after changing the hr format.
         */
        $( ".wpsl-current-period" ).each( function() {
            periodBlock = $( this ),
                hours 		= {
                    "open": $( this ).find( ".wpsl-open-hour" ).val(),
                    "close": $( this ).find( ".wpsl-close-hour" ).val()
                };

            // Set the new hour format for both dropdowns.
            $( this ).find( "select" ).html( optionList ).promise().done( function() {

                // Select the correct start/end hours as selected.
                for ( var key in hours ) {
                    if ( hours.hasOwnProperty( key ) ) {

                        // Breakup the hour, so we can check the part before and after the : separately.
                        splitHour = hours[key].split( ":" );

                        if ( hrFormat == 12 ) {
                            hourType = "";

                            // Change the hours to a 12hr format and add the correct AM or PM.
                            if ( hours[key].charAt( 0 ) == 0 ) {
                                hours[key] = hours[key].substr( 1 );
                                hourType   = " AM";
                            } else if ( ( splitHour[0].length == 2 ) && ( splitHour[0] > 12 ) ) {
                                hours[key] = ( splitHour[0] - 12 ) + ":" + splitHour[1];
                                hourType   = " PM";
                            } else if ( splitHour[0] < 12 ) {
                                hours[key] = splitHour[0] + ":" + splitHour[1];
                                hourType   = " AM";
                            } else if ( splitHour[0] == 12 ) {
                                hours[key] = splitHour[0] + ":" + splitHour[1];
                                hourType   = " PM";
                            }

                            // Add either AM or PM behind the time.
                            if ( ( splitHour[1].indexOf( "PM" ) == -1 ) && ( splitHour[1].indexOf( "AM" ) == -1 ) ) {
                                hours[key] = hours[key] + hourType;
                            }

                        } else if ( hrFormat == 24 ) {

                            // Change the hours to a 24hr format and remove the AM or PM.
                            if ( splitHour[1].indexOf( "PM" ) != -1 ) {
                                if ( splitHour[0] == 12 ) {
                                    hours[key] = "12:" + splitHour[1].replace( " PM", "" );
                                } else {
                                    hours[key] = ( + splitHour[0] + 12 ) + ":" + splitHour[1].replace( " PM", "" );
                                }
                            } else if ( splitHour[1].indexOf( "AM" ) != -1 ) {
                                if ( splitHour[0].toString().length == 1 ) {
                                    hours[key] = "0" + splitHour[0] + ":" + splitHour[1].replace( " AM", "" );
                                } else {
                                    hours[key] = splitHour[0] + ":" + splitHour[1].replace( " AM", "" );
                                }
                            } else {
                                hours[key] = splitHour[0] + ":" + splitHour[1]; // When the interval is changed
                            }
                        }

                        // Set the correct value as the selected one.
                        periodBlock.find( ".wpsl-" + key + "-hour option[value='" + $.trim( hours[key] ) + "']" ).attr( "selected", "selected" );
                    }
                }

            });
        });
    }

    // Update the opening hours format if one of the dropdown values change.
    $( "#wpsl-editor-hour-format, #wpsl-editor-hour-interval" ).on( "change", function() {
        createHourOptionList();
    });

    // Show the tooltips.
    $( ".wpsl-info" ).on( "mouseover", function() {
        $( this ).find( ".wpsl-info-text" ).show();
    });

    $( ".wpsl-info" ).on( "mouseout", function() {
        $( this ).find( ".wpsl-info-text" ).hide();
    });

    // If the start location is empty, then we color the info icon red instead of black.
    if ( $( "#wpsl-latlng" ).length && !$( "#wpsl-latlng" ).val() ) {
        $( "#wpsl-latlng" ).siblings( "label" ).find( ".wpsl-info" ).addClass( "wpsl-required-setting" );
    }

    /**
     * Try to apply the custom style data to the map.
     *
     * If the style data is invalid json we show an error.
     *
     * @since  2.0.0
     * @return {void}
     */
    function tryCustomMapStyle() {
        var validStyle = "",
            mapStyle   = $.trim( $( "#wpsl-map-style" ).val() );

        $( ".wpsl-style-preview-error" ).remove();

        if ( mapStyle ) {

            // Make sure the data is valid json.
            validStyle = tryParseJSON( mapStyle );

            if ( !validStyle ) {
                $( "#wpsl-style-preview" ).after( "<div class='wpsl-style-preview-error'>" + wpslL10n.styleError + "</div>" );
            }
        }

        map.setOptions({ styles: validStyle });
    }

    // Handle the map style changes on the settings page.
    if ( $( "#wpsl-map-style" ).val() ) {
        tryCustomMapStyle();
    }

    // Handle clicks on the map style preview button.
    $( "#wpsl-style-preview" ).on( "click", function() {
        tryCustomMapStyle();

        return false;
    });

    /**
     * Make sure the JSON is valid.
     *
     * @link   http://stackoverflow.com/a/20392392/1065294
     * @since  2.0.0
     * @param  {string} jsonString The JSON data
     * @return {object|boolean}	   The JSON string or false if it's invalid json.
     */
    function tryParseJSON( jsonString ) {

        try {
            var o = JSON.parse( jsonString );

            /*
             * Handle non-exception-throwing cases:
             * Neither JSON.parse(false) or JSON.parse(1234) throw errors, hence the type-checking,
             * but... JSON.parse(null) returns 'null', and typeof null === "object",
             * so we must check for that, too.
             */
            if ( o && typeof o === "object" && o !== null ) {
                return o;
            }
        }
        catch ( e ) { }

        return false;
    }

    // Make sure the custom error notices can be removed
    $( "#wpsl-wrap" ).on( "click", "button.notice-dismiss", function() {
        $( this ).closest( 'div.notice' ).remove();
    });

    /**
     * Handle the red warning that's shown next to the
     * force zipcode search option if the autocomplete
     * value is changed.
     *
     * The autocomplete option itself doesn't support
     * zip only searches, so having both of them enabled
     * gives the user the wrong expectation.
     */
    $( "#wpsl-search-autocomplete, #wpsl-force-postalcode" ).change( function() {
        var $info = $( "#wpsl-force-postalcode" ).parent( "p" ).find( ".wpsl-info-zip-only" );

        if ( $( "#wpsl-search-autocomplete" ).is( ":checked" ) && $( "#wpsl-force-postalcode" ).is( ":checked" ) ) {
            $info.show();
        } else {
            $info.hide();
        }
    });

    $( "#wpsl-delay-loading" ).change( function() {
        if ( $( this ).is( ":checked" ) ) {
            $( this ).parent( "p" ).find( ".wpsl-info" ).trigger( "mouseover" );
        } else {
            $( this ).parent( "p" ).find( ".wpsl-info" ).trigger( "mouseout" );
        }
    });

    $( "#wpsl-wrap" ).on( "click", function( e ) {
        $( ".wpsl-info-text" ).hide();
    });
});