(function($){
	if(document.getElementById("ffl-dealer-container")){
		
		let modalSelector = document.getElementById("ffl-dealer-modal");
		if (modalSelector != null && modalSelector.id != '') {
			//let modalSelector = document.getElementById("ffl-dealer-modal");
			//modalSelector.style.display = "none";
		}
		
		document.getElementById("ffl-dealer-container").innerHTML = '<div class="ffl-content">\n    <h3 class="ffl-dealer-heading">Select FFL Dealer</h3>\n <p class="notice">\n        Firearms can only be shipped to an authorized FFL dealer. You are responsible for contacting your FFL dealer to\n        discuss their fees and pickup processes. Please enter a zip code below for a list of FFL dealers in your area.\n        Then, select an FFL dealer you\n        wish the firearms to be shipped to.\n    </p>\n     <div class="columns">\n        <div class="column">\n            <label for="ffl-dealer-zip-code">Zip Code : </label>\n            <input autocomplete="off" type="text" id="ffl-dealer-zip-code" placeholder="Zip Code" class="">\n        </div>\n\n        <div class="column">\n            <label for="ffl-radius">Radius : </label>\n            <select id="ffl-radius">\n                <option value="5" selected="">5 Miles</option>\n                <option value="10">10 Miles</option>\n                <option value="25">25 Miles</option>\n                <option value="50">50 Miles</option>\n                <option value="100">100 Miles</option>\n            </select>\n        </div>\n\n        <div class="column">\n            <a id="ffl-search" class="button alt">Find Nearby</a>\n        </div>\n    </div>\n\n\n</div>\n<span id="selected-notification"></span>\n<div class="ffl-list-container">\n    <div id="ffl-list" class="ffl-hide">\n\n    </div>\n</div>\n';
	}
	var n = FFLDELAERSCRIPT.rest_url,
        h = $("#ffl-search"),
        o = $("#ffl-dealer-zip-code"),
        p = $("#ffl-radius"),
        d = $("#ffl-list"),
        apiKey = typeof FFLDELAERSCRIPT.apiKey === "undefined" ? "" : FFLDELAERSCRIPT.apiKey;
    
    h.on("click", function(t) {
        if (o.val().length !== 5) {
            alert("Enter valid zip code!");
            t.preventDefault();
            return false;
        }
        if (p.val() === "0") {
            alert("Enter valid radius!");
            t.preventDefault();
            return false;
        }
      //  h.addClass("dsbSearch");
        d.addClass("ffl-hide").html("");
        var e = {
            zipcode: o.val(),
            radius: p.val()
        };
        
        $.ajax({
            url: n + "ffl-dealers",
            type: "POST",
            data: JSON.stringify(e),
            contentType: "application/json",
            headers: {
                "X-Requested-With": "XMLHttpRequest"
            },
            success: function(t) {
				if(t.original){
				 if (t.original.message && 400 === t.original.status){
					  alert('zipcode is not available');
					  return false;
				 }
				}
                                       
				var n = t;
				$.each(n, function(r, s) {
					var a = s.premise_street + ", " + s.premise_city + ", " + s.premise_state + ", " + s.premise_zip_code;
					
					var u = encodeURIComponent(JSON.stringify(s));
					var business_name = s.business_name ? s.business_name : s.license_name;
					var a = "<div class='list-wrapper' id='" + s.license_number + "'><div class='ffl-list-div' >" + business_name + " " + a + " </div><div class='select-button'><button class='dealer-button' type='button' data-marker-id='" + s.license_number + "' data-content='" + u + "'>Select Dealer</button></div></div>";
				
					$(d).append(a);
				});

				$(document).on("click", ".dealer-button", function(t) {
					if(FFLDELAERSCRIPT.modal_hide ===1){
						var modalSelector = $("#ffl-dealer-modal");
						if (modalSelector.length > 0 && modalSelector.attr("id") !== "") {
							modalSelector.hide();
						}
					}
					return false;
				});
				for (var f = document.getElementsByClassName("dealer-button"), c = 0; c < f.length; c++){
					f[c].addEventListener("click", function (t) {
						let content = $(this).data('content');
						var decodedData = decodeURIComponent(content);
						var jsonData = JSON.parse(decodedData);
						getSelected(jsonData);
					});
				}
				$("#ffl-list").removeClass("ffl-hide");
				
            },
            error: function(xhr, status, error) {
                if (xhr.status === 422 || xhr.status === 400) {
                    alert(xhr.responseJSON.message);
                    return false;
                } else {
                    console.log(xhr);
                }
            }
        });
    });
	const defaultDealers = 	FFLDELAERSCRIPT.default_dealers;
	if(defaultDealers){
		
		$.each(defaultDealers, function(r, s) {
			var a = s.premise_street + ", " + s.premise_city + ", " + s.premise_state + ", " + s.premise_zip_code;
			var u = encodeURIComponent(JSON.stringify(s));
			var business_name = s.business_name ? s.business_name : s.license_name;
			var a = "<div class='list-wrapper' id='" + s.license_number + "'><div class='ffl-list-div' >" + business_name + " " + a + " </div><div class='select-button'><button class='dealer-button' type='button' data-marker-id='" + s.license_number + "' data-content='" + u + "'>Select Dealer</button></div></div>";
		
			$(d).append(a);
		});
		
		$("#ffl-list").removeClass("ffl-hide");
		for (var f = document.getElementsByClassName("dealer-button"), c = 0; c < f.length; c++){
			f[c].addEventListener("click", function (t) {
				let content = $(this).data('content');
				var decodedData = decodeURIComponent(content);
				if(decodedData){
					var jsonData = JSON.parse(decodedData);
					getSelected(jsonData);
				}
			});
		}
	}
	function getSelected(data) {
		$("#shipping_country").prop("disabled",false);
		$("#shipping_state").prop("disabled",false);

		$("#shipping_country").val("US"); // Change the value or make some change to the internal state
		$("#shipping_country").trigger("change");
		$("#shipping_country").prop("disabled",true);

		var elemsActive = document.querySelectorAll(".selectedFFLDivButton");

		[].forEach.call(elemsActive, function(el) {
			el.classList.remove("selectedFFLDivButton");
		});

		document.getElementById(data.license_number).childNodes[0].classList.add('selectedFFLDivButton');
		localStorage.setItem("selectedFFL",data.license_number);
		
		document.getElementById( "place_order" ).disabled = false
		
		let business_name = data.business_name?data.business_name:data.license_name;
		var company = document.getElementsByName("shipping_company")[0];
		setNativeValue(company,business_name);
		company.readOnly = true;

		var address1 = document.getElementsByName("shipping_address_1")[0];
		setNativeValue(address1,data.premise_street);
		address1.readOnly = true;

		var city = document.getElementsByName("shipping_city")[0];
		setNativeValue(city,data.premise_city);
		city.readOnly = true;
		
		var city = document.getElementsByName("shipping_city")[0];
		setNativeValue(city,data.premise_city);
		city.readOnly = true;
		
		var postalCode = document.getElementsByName("shipping_postcode")[0];
		setNativeValue(postalCode,data.premise_zip_code);
		postalCode.readOnly = true;

		var orderComment = document.getElementsByName("order_comments")[0];
		var orderCommentText = 'FFL Number : ' + data.license_number + ' - ' +
			'FFL : ' + business_name + ' - ' +
			'Street : ' + data.premise_street + ' - ' +
			'City : ' + data.premise_city + ' - ' +
			'State : ' + data.premise_state + ' - ' +
			'Zip and Phone: ' + data.premise_zip_code + ' - ' + data.voice_phone;

		orderComment.readOnly = true;
		setNativeValue(orderComment,orderCommentText);
		
		$("#shipping_state").val(data.premise_state);
		
		
		$("#shipping_state option[value='"+data.premise_state+"']").prop('selected', true);
		$("#shipping_state").trigger("change");
		$("#shipping_country").prop("disabled",true);
		//$("#shipping_state").prop("disabled",true);
		$('#selected-notification').notify("Dealer has been added as a shipping address", "success",{ position:"left" });
		return false;
	}
	function setNativeValue(element, value) {
		var _ref = Object.getOwnPropertyDescriptor(element, 'value') || {},
			valueSetter = _ref.set;

		var prototype = Object.getPrototypeOf(element);

		var _ref2 = Object.getOwnPropertyDescriptor(prototype, 'value') || {},
			prototypeValueSetter = _ref2.set;

		if (prototypeValueSetter && valueSetter !== prototypeValueSetter) {
			prototypeValueSetter.call(element, value);
		} else if (valueSetter) {
			valueSetter.call(element, value);
		} else {}
	}
})(jQuery)