var LocationList = React.createClass({
    render: function () {
        var locations = this.props.locations.map((location) => {
            return (
                <window.RetailerLocation key={location.Id} location={location} />
            );
        })
        return (
            <div className="search-results custom-scrollbar" style={{ marginTop: 40 }} role="region" aria-label="Retailer search results">
                <ul className="list-group results-group">
                    {locations}
                </ul>
            </div>
        );
    }
});

var GoogleMap = React.createClass({

    getInitialState: function () {
        this.mapElement = {};
        return null;
    },
    render: function () {
        return (
            <div
                className="embed-responsive-item"
                ref={(mapRef) => this.mapElement = mapRef}
                role="region"
                aria-label="Interactive map of Delaware Lottery retailer locations">
            </div>
        );
    },
    componentDidMount() {
        this.componentWillUpdate({}, null);
    },
    componentWillUnmount: function () {
        if (this.mapAccessibilityObserver) {
            this.mapAccessibilityObserver.disconnect();
            this.mapAccessibilityObserver = null;
        }
    },
    shouldComponentUpdate(nextProps, nextState) {
        if (this.props.markers !== nextProps.markers || this.props.infoWindowContent !== nextProps.infoWindowContent) {
            return true;
        }
        return false;
    },
    applyMapAccessibility: function () {
        if (!this.mapElement) {
            return;
        }

        this.mapElement.setAttribute('role', 'region');
        this.mapElement.setAttribute('aria-label', 'Interactive map of Delaware Lottery retailer locations');

        var focusableElements = this.mapElement.querySelectorAll('[tabindex]');
        for (var idx = 0; idx < focusableElements.length; idx++) {
            var current = focusableElements[idx];
            var tabIndexValue = parseInt(current.getAttribute('tabindex'), 10);
            var tagName = (current.tagName || '').toLowerCase();

            if (isNaN(tabIndexValue) || tabIndexValue < 0) {
                continue;
            }
            if (current.getAttribute('role')) {
                continue;
            }
            if (tagName === 'a' || tagName === 'button' || tagName === 'input' || tagName === 'select' || tagName === 'textarea') {
                continue;
            }

            current.setAttribute('role', 'button');
        }

        var mapCanvases = this.mapElement.querySelectorAll('canvas');
        for (var canvasIndex = 0; canvasIndex < mapCanvases.length; canvasIndex++) {
            if (!mapCanvases[canvasIndex].getAttribute('aria-label')) {
                mapCanvases[canvasIndex].setAttribute('aria-label', 'Retailer locations map');
            }
        }
    },
    startMapAccessibilityObserver: function () {
        if (typeof MutationObserver === 'undefined' || !this.mapElement) {
            return;
        }
        if (this.mapAccessibilityObserver) {
            this.mapAccessibilityObserver.disconnect();
        }
        this.mapAccessibilityObserver = new MutationObserver(this.applyMapAccessibility);
        this.mapAccessibilityObserver.observe(this.mapElement, { childList: true, subtree: true });
    },
    componentWillUpdate: function (nextProps, nextState) {

        if (typeof window !== "undefined") {
            var $ = window.$;
            var markers = nextProps.markers;
            var infoWindowContent = nextProps.infoWindowContent;

            var google = window.google || {};
            var bounds = new google.maps.LatLngBounds(); //init to DE

            var mapOptions = {
                mapTypeId: 'roadmap'
            };
            var map = new google.maps.Map(this.mapElement, mapOptions);
            map.setTilt(45);
            google.maps.event.addListenerOnce(map, 'idle', function () {
                this.applyMapAccessibility();
                this.startMapAccessibilityObserver();
            }.bind(this));
            setTimeout(this.applyMapAccessibility, 250);
            setTimeout(this.applyMapAccessibility, 1000);

            // Display multiple markers on a map
            var infoWindow = new google.maps.InfoWindow(), marker, i;

            var image = {
                url: '/Content/images/map/map-marker.svg',
                size: new google.maps.Size(18, 22),
            }

            if (typeof markers !== "undefined" && markers.length !== 0) {
                // Loop through our array of markers & place each one on the map  

                for (i = 0; i < markers.length; i++) {
                    var id = markers[i][3];
                    var city = markers[i][4];
                    var street = markers[i][5];
                    var retailerName = markers[i][0];


                    var position = new google.maps.LatLng(markers[i][1], markers[i][2]);
                    bounds.extend(position);
                    marker = new google.maps.Marker({
                        position: position,
                        map: map,
                        title: markers[i][0],
                        icon: image,
                        animation: google.maps.Animation.DROP,

                    });

                    // Allow each marker to have an info window    
                    google.maps.event.addListener(marker,
                        'click',
                        (function (marker, i) {

                            function slugify(text) {
                                return text.toString().toLowerCase()
                                    .replace(/\s+/g, '-')           // Replace spaces with -
                                    .replace(/[^\w\-]+/g, '')       // Remove all non-word chars
                                    .replace(/\-\-+/g, '-')         // Replace multiple - with single -
                                    .replace(/^-+/, '')             // Trim - from start of text
                                    .replace(/-+$/, '');            // Trim - from end of text
                            }

                            return function () {
                                infoWindow.setContent(infoWindowContent[i]); // Can grab existing content, but not recommended: $(`#retailer-location-${i+1}`).html()
                                infoWindow.open(map, marker);
                                var ga = window.ga || {};
                                ga('send', 'pageview', `/Where-to-Buy/map-detail/de/${slugify(city)}/${slugify(retailerName)}/${slugify(street)}`);

                            }
                        })(marker, i));

                }
                // Automatically center the map fitting all markers on the screen
                map.fitBounds(bounds);
                map.panToBounds(bounds);
            } else {
                map.setZoom(8);
                map.panTo(new google.maps.LatLng(38.9108, -75.5277));
            }

        }
    }

});



var LocationSearch = React.createClass({
    allLocations: [],
    /*Code Changes :: WhereToBuy :: 06082018*/
    dataprint: [],
    parammsg: "",
    /*End*/
    componentWillMount: function () {

    },
    getInitialState: function () {
        return {
            data: [],
            searchValue: "",
            drawingInstantChecked: true,
            sportsChecked: true,
            kenoChecked: true,
            distanceChecked: false,
            currentLocation: null,
            infoWindowContent: [],
            markers: []
        }
    },
    getBrowserLocation: function () {
        var self = this;
        if (navigator.geolocation) {
            navigator.geolocation.getCurrentPosition(function (position) {
                var google = window.google || {};
                console.log('in navigator.geolocation.getCurrentPosition ')
                console.log(position)
                var currentLocation = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
                var previousLocation = self.state.currentLocation;

                self.setState({ currentLocation: currentLocation },
                    function () {

                        //console.log('(!previousLocation && !currentLocation) value is ' + (!previousLocation && !currentLocation));
                        //console.log('previousLocation instanceof google.maps.LatLng value is ' + previousLocation instanceof google.maps.LatLng);
                        //console.log('currentLocation instanceof google.maps.LatLng value is ' + currentLocation instanceof google.maps.LatLng);

                        if (
                            (!previousLocation && !currentLocation) ||
                            (previousLocation instanceof google.maps.LatLng &&
                                currentLocation instanceof google.maps.LatLng &&
                                previousLocation.equals(currentLocation))
                        ) {
                            console.log('running just searchLocations')
                            self.searchLocations();
                        } else {
                            console.log('about to run calculateDistances')
                            console.log('current location is ' + currentLocation)
                            self.calculateDistances(currentLocation);
                            self.searchLocations();
                            console.log('done with calculateDistances')
                        }

                    });

            }, function (error) {
                switch (error.code) {
                    case error.PERMISSION_DENIED:
                        console.error("User denied the request for Geolocation.");
                        break;
                    case error.POSITION_UNAVAILABLE:
                        console.error("Location information is unavailable.");
                        break;
                    case error.TIMEOUT:
                        console.error("The request to get user location timed out.");
                        break;
                    default:
                        console.error("An unknown geolocation error occurred.", error);
                        break;
                }
            });
        }
        else {
            return;
        }
    },


    getBrowserLocation_test: function () {
        var self = this;

        if (!navigator.geolocation) {
            console.warn("Geolocation is not supported by this browser.");
            return;
        }

        const fakePosition = {
            coords: {
                latitude: 39.43856187659509,
                longitude: -75.75249861731027,
                altitude: null,
                accuracy: 10,
                altitudeAccuracy: null,
                heading: null,
                speed: null
            },
            timestamp: Date.now()
        };

        const currentFakePositon = {
            coords: {
                latitude: 39.606393495053304,
                longitude: - 75.75214563218242,
                altitude: null,
                accuracy: 10,
                altitudeAccuracy: null,
                heading: null,
                speed: null
            },
            timestamp: Date.now()

        }

        console.log("FAKE GeolocationPosition:", fakePosition);
        console.log("Beginning getBrowserLocation function");

        var google = window.google || {};
        var currentLocation = new google.maps.LatLng(
            fakePosition.coords.latitude,
            fakePosition.coords.longitude
        );

        console.log("Full position object:", fakePosition);
        console.log("Latitude:", fakePosition.coords.latitude);
        console.log("Longitude:", fakePosition.coords.longitude);
        console.log("Accuracy (meters):", fakePosition.coords.accuracy);
        console.log("Timestamp:", new Date(fakePosition.timestamp));

        /*var previousLocation = self.state.currentLocation;*/
        var previousLocation = new google.maps.LatLng(
            currentFakePositon.coords.latitude,
            currentFakePositon.coords.longitude
        );

        ;
        // ✅ Log the raw position object
        console.log("Full position object:", currentFakePositon);
        console.log("Latitude:", currentFakePositon.coords.latitude);
        console.log("Longitude:", currentFakePositon.coords.longitude);
        console.log("Accuracy (meters):", currentFakePositon.coords.accuracy);
        console.log("Timestamp:", new Date(currentFakePositon.timestamp));

        console.log(!previousLocation && !currentLocation);
        console.log(previousLocation instanceof google.maps.LatLng &&
            currentLocation instanceof google.maps.LatLng &&
            previousLocation.equals(currentLocation));

        console.log(!previousLocation && !currentLocation) ||
            (previousLocation instanceof google.maps.LatLng &&
                currentLocation instanceof google.maps.LatLng &&
                previousLocation.equals(currentLocation));

        //No known location before or after ; both are Google Maps LatLng objects; coordinates are same

        self.setState({ currentLocation: currentLocation }, function () {
            if (
                (!previousLocation && !currentLocation) ||
                (previousLocation instanceof google.maps.LatLng &&
                    currentLocation instanceof google.maps.LatLng &&
                    previousLocation.equals(currentLocation))
            ) {
                console.log('running just searchLocations')
                self.searchLocations();
            } else {
                console.log('about to run calculateDistances')
                self.calculateDistances(currentLocation);
                self.searchLocations();
                }
                // self.searchLocations();            
        });
},

    calculateDistances: function (currentLocation) {
        var google = window.google || {};
        console.log('at calculating distances')
        _.each(this.allLocations, function (retailer) {
            if ((!retailer.Lat) || (!retailer.Long)) {
                var b = (!retailer.Lat) || (!retailer.Long)
                console.log('bool value is - ' + b);
                console.log('retailer is - ' + retailer);
                console.log('retailer.Lat - ' + retailer.Lat);
                console.log('retailer.Long - ' + retailer.Long);
                return retailer;
            }
            var retailerLocation = new google.maps.LatLng(retailer.Lat, retailer.Long);
            var metersBetweenLocations = google.maps.geometry.spherical.computeDistanceBetween(currentLocation, retailerLocation);
            console.log('metersBetweenLocations' + metersBetweenLocations)
            var milesBetweenLocations = metersBetweenLocations * 0.000621371192;
            retailer.Distance = milesBetweenLocations;
            console.log('milesBetweenLocations' + milesBetweenLocations);
            return retailer;
        });
    },
    initializeTypeAhead: function () {
        if (typeof window !== "undefined") {
            //console.log('@ beginning of initialization')
            //console.log(this.allLocations.length)
            var zipCodeItems = (_.uniq(_.filter(this.allLocations, function (location) { return location.Zip !== null }).map(function (location) { return location.Zip }))).sort();
            var cityItems = (_.uniq(_.filter(this.allLocations, function (location) { return location.City !== null }).map(function (location) { return location.City.trim() }))).sort();
            var $ = window.$;
            $(this.searchElement).typeahead({
                order: "asc",
                group: true,
                source: {
                    "Zip Codes": {
                        data: zipCodeItems
                    },
                    "Cities": {
                        data: cityItems
                    }
                },
                mustSelectItem: true
            });

            var applyTypeAheadAccessibility = function () {
                var searchLabel = 'Search by city or ZIP code';
                var container = this.searchElement ? $(this.searchElement).closest('.typeahead__container')[0] : null;
                if (!container) {
                    return;
                }

                var generatedInputs = container.querySelectorAll('input');
                for (var i = 0; i < generatedInputs.length; i++) {
                    if (!generatedInputs[i].getAttribute('aria-label') && !generatedInputs[i].getAttribute('aria-labelledby')) {
                        generatedInputs[i].setAttribute('aria-label', searchLabel);
                    }
                }

                var tabbableElements = container.querySelectorAll('[tabindex]');
                for (var tabIndex = 0; tabIndex < tabbableElements.length; tabIndex++) {
                    var current = tabbableElements[tabIndex];
                    var currentTabIndex = parseInt(current.getAttribute('tabindex'), 10);
                    var currentTagName = (current.tagName || '').toLowerCase();

                    if (isNaN(currentTabIndex) || currentTabIndex < 0) {
                        continue;
                    }
                    if (current.getAttribute('role')) {
                        continue;
                    }
                    if (currentTagName === 'a' || currentTagName === 'button' || currentTagName === 'input' || currentTagName === 'select' || currentTagName === 'textarea') {
                        continue;
                    }

                    current.setAttribute('role', 'button');
                }
            }.bind(this);

            setTimeout(applyTypeAheadAccessibility, 0);
            setTimeout(applyTypeAheadAccessibility, 250);
        }
        //console.log('@ end of initialization')
        //console.log(this.allLocations.length)
    },


    componentDidMount() {
        var xhr = new XMLHttpRequest();
        xhr.open('get', '/WhereToBuy/retailers', true);
        xhr.onload = function () {
            var data = JSON.parse(xhr.responseText);
            this.allLocations = data;
            this.initializeTypeAhead();
            this.searchLocations();
        }.bind(this);
        xhr.send();
    },



    drawingInstantCheckChange: function (event) {
        this.setState({ drawingInstantChecked: !this.state.drawingInstantChecked },
            function () { this.searchLocations() }
        );
    },

    sportsCheckChange: function (event) {
        this.setState({ sportsChecked: !this.state.sportsChecked },
            function () { this.searchLocations() }
        );
    },
    kenoCheckChange: function (event) {
        this.setState({ kenoChecked: !this.state.kenoChecked },
            function () { this.searchLocations() }
        );
    },
    distanceCheckChange: function (event) {
        var newState = !this.state.distanceChecked;

        this.setState({ distanceChecked: newState, searchValue: "" },

            function () {
                if (newState) {
                    this.getBrowserLocation();
                } else {
                    this.searchLocations();
                }

            }
        );
    },
    searchTextChange: function (event) {
        this.setState({ searchValue: event.target.value, distanceChecked: false });
    },
    searchTextBlur: function (event) {
        this.setState({ searchValue: this.searchElement.value, distanceChecked: false });
    },
    onSearchResetButtonClick: function (event) {
        if (this.state.searchValue.trim().length === 0) return;
        var intialState = this.getInitialState;
        this.setState(intialState);
    },
    /*Code Changes :: WhereToBuy :: 06082018*/
    printpage: function (event) {
        sessionStorage.setItem("printablecontent", JSON.stringify(this.dataprint));
        sessionStorage.setItem("printparam", this.parammsg);
        window.open("/Where-To-Buy/Print", "_blank");
    },
    /*End*/
    searchLocations: function () {
        var searchValue = this.state.searchValue;
        var distanceChecked = this.state.distanceChecked === true;
        var ga = window.ga || {};

        var data = _.filter(
            this.allLocations,
            function (locationItem) {
                if (distanceChecked) {
                    return locationItem.Distance !== null && locationItem.Distance <= 10;
                }
                if (searchValue === '') {
                    return (
                        (
                            distanceChecked
                            ||

                            (locationItem.IsDrawingInstantLocation && this.state.drawingInstantChecked) ||
                            (locationItem.IsSportsLottoLocation && this.state.sportsChecked) ||
                            (locationItem.IsKenoLocation && this.state.kenoChecked)
                        )

                    );
                }
                else {
                    return (
                        (
                            distanceChecked
                            ||

                            (
                                (
                                    locationItem.City !== null &&
                                    locationItem.City.toUpperCase() === searchValue.toUpperCase()
                                )
                                || locationItem.Zip === searchValue
                            )
                        )
                        &&
                        (
                            (locationItem.IsDrawingInstantLocation && this.state.drawingInstantChecked) ||
                            (locationItem.IsSportsLottoLocation && this.state.sportsChecked) ||
                            (locationItem.IsKenoLocation && this.state.kenoChecked)

                        )
                    );
                }
                //return (
                //        (
                //            distanceChecked ||
                //            (
                //                (
                //                    locationItem.City !== null &&
                //                    locationItem.City.toUpperCase() === searchValue.toUpperCase()
                //                ) ||
                //                locationItem.Zip === searchValue
                //            )
                //        )
                //        &&
                //        (
                //            (locationItem.IsDrawingInstantLocation && this.state.drawingInstantChecked) ||
                //            (locationItem.IsSportsLottoLocation && this.state.sportsChecked) ||
                //            (locationItem.IsKenoLocation && this.state.kenoChecked)
                //        )
                //    );
                //console.log(locationItem.City)

            },
            this
        );

        // Sort by distance if applicable
        if (distanceChecked) {
            data = _.sortBy(data, 'Distance');
        }

        var gaFilter = `/?instant=${this.state.drawingInstantChecked ? 'Y' : 'N'}&sports=${this.state.sportsChecked ? 'Y' : 'N'}&keno=${this.state.kenoChecked ? 'Y' : 'N'}`;

        var slugify = function (text) {
            return text.toString().toLowerCase()
                .replace(/\s+/g, '-') // Replace spaces with -
                .replace(/[^\w\-]+/g, '') // Remove all non-word chars
                .replace(/\-\-+/g, '-') // Replace multiple - with single -
                .replace(/^-+/, '') // Trim - from start of text
                .replace(/-+$/, ''); // Trim - from end of text
        };
        //console.log('after slugify')
        //if (this.state.distanceChecked) {
        //    data = _.sortBy(data, "Distance");
        //    data = _.first(data, 6);
        //    ga('send', 'pageview', `/Where-to-Buy/search/distance${gaFilter}`);
        //} else {
        //    data = _.sortBy(data, "RetailerName");
        //    ga('send', 'pageview', `/Where-to-Buy/search/${slugify(searchValue)}${gaFilter}`);
        //}
        /*Code Changes :: WhereToBuy :: 06082018*/
        this.dataprint = data;
        var selectretailers = "";
        if (this.state.drawingInstantChecked) {
            if (selectretailers === "") {
                selectretailers = "Drawing/Instant Games";
            }
            else {
                selectretailers = selectretailers + ", Drawing/Instant Games";
            }
        }


        if (this.state.sportsChecked) {
            if (selectretailers === "") {
                selectretailers = "Sports Lottery";
            }
            else {
                selectretailers = selectretailers + ", Sports Lottery";
            }
        }

        if (this.state.kenoChecked) {
            if (selectretailers === "") {
                selectretailers = "Keno©";
            }
            else {
                selectretailers = selectretailers + ", Keno©";
            }
        }
        if (searchValue === '') {
            this.parammsg = "You are trying to search " + selectretailers + " retailers for All location";
        }
        else {
            this.parammsg = "You are trying to search " + selectretailers + " retailers for " + searchValue + " location";

        }
        if (this.state.distanceChecked) {
            this.parammsg = "You are trying to search " + selectretailers + " retailers from your current location";
        }
        /*end*/
        var markers = _.map(data, function (location) { return [location.RetailerName, location.Lat, location.Long, location.Id, location.City, location.Street] });
        var infoWindowContent = _.map(data, function (location) {
            return `<div class="info_content container location-panel">
                        <h3 class="location-name text-uppercase">${location.RetailerName}</h3>
                    	<div class="location-info_full">
							<div class="row">
								<div class="col-xs-7">
									<div itemScope itemType="http://schema.org/Organization">
										<h3 class="location-name text-uppercase visible-xs-block" itemProp="name">{ location.RetailerName}</h3>
										<div itemProp="address" itemScope itemType="http://schema.org/PostalAddress">
											<span itemProp="streetAddress">${location.Street}</span><br />
											<span itemProp="addressLocality">${location.City}</span>, <span itemProp="addressRegion">DE</span> <span itemProp="postalCode">${location.Zip}</span>
										</div>
										<ul class="list-unstyled mbn">
											<li class="mbxs"><a href="https://maps.google.com?daddr=${location.Street} ${location.City} DE ${location.Zip}" target="_blank" ><i class="fa-fw fa fa-map-o"></i> Directions</a></li>
                                            ${(location.Phone) ?
                    (
                        `<li><i class="fa-fw fa fa-mobile"></i><span itemProp="telephone"> ${location.Phone} </span></li>`
                    ) : ('')}
                                            ${(location.Distance) ?
                    (
                        `<li><i class="fa-fw fa"></i><span itemProp="distance"> ${Math.round(location.Distance * 10) / 10} miles away </span></li>`
                    ) : ('')}
                                        </ul>
                                    </div>
                                </div>
                                <div class="col-xs-5">
                                    <ul class="list-unstyled location-gametypes text-nowrap">
                                        ${(location.IsDrawingInstantLocation === true) ?
                    (
                        `<li class="gametypes-drawing-instant mbxs">
                                                <i class="fa fa-circle icn color-primary mrxs" aria-hidden="true"></i>
                                                <span>Drawing/Instant</span>
                                            </li>`
                    ) : ('')}

                                        ${(location.IsSportsLottoLocation === true) ?
                    (`<li class="gametypes-sports mbxs">
                                                <i class="fa fa-circle icn color-secondary mrxs" aria-hidden="true"></i>
                                                <span>Sports</span>
                                            </li>`
                    ) : ('')}

                                        ${(location.IsKenoLocation === true) ?
                    (
                        `<li class="gametypes-keno mbxs">
												<i class="fa fa-circle icn color-keno mrxs" aria-hidden="true"></i>
												<span>Keno<sup>&reg;</sup></span>
											</li>`
                    ) : ('')}
									</ul>
                                </div>
                            </div>
                        </div>
                    </div>`
        });
        this.setState({ data: data });
        this.setState({ markers: markers });
        this.setState({ infoWindowContent: infoWindowContent });
    },
    render: function () {
        var resetButtonClass = this.state.searchValue.trim().length === 0 ? 'reset hidden' : 'reset';
        var searchButtonClass = this.state.searchValue.trim().length === 0 ? 'search' : 'search hidden';
        var drawingInstantCheckedClass = "checkbox checkbox-fancy checkbox-primary checkbox-control mvn" + (this.state.drawingInstantChecked ? " checked" : "");
        var sportsCheckedClass = "checkbox checkbox-fancy checkbox-secondary checkbox-control mvn" + (this.state.sportsChecked ? " checked" : "");
        var kenoCheckedClass = "checkbox checkbox-fancy checkbox-keno checkbox-control mvn" + (this.state.kenoChecked ? " checked" : "");
        var distanceChecked = this.state.distanceChecked === true;
        var distanceCheckedClass = distanceChecked
            ? "  checkbox-distance   mvn checked location selected checkbox-control-styleonly"
            : "  checkbox-distance checkbox-control-styleonly mvn location";
        
        // var locationSearchAreaClass = distanceChecked ? 'hidden form-group mbn paxs' : 'form-group mbn paxs';
        return (
            <div>
                <div className="locations-search">
                    <div className="search-panel">
                        <fieldset className="form-locations-search">
                            <legend className="sr-only">Search for where to play lotto games</legend>
                            <div className="form-group mbn paxs">
                                <label className="control-label sr-only" htmlFor="where-to-buy-search-input">City or ZIP code</label>
                                <div className="input-group">
                                    <span className="input-group-addon bg-white">
                                        <button type="button" className="btn btn-solid btn-solid-white" onClick={(event) => this.onSearchResetButtonClick(event)}>
                                            <span className={resetButtonClass}>
                                                <span className="sr-only">Reset</span><i className="fa fa-refresh color-secondary" aria-hidden="true"></i>
                                            </span>
                                            <span className={searchButtonClass}>
                                                <span className="sr-only">Search</span><i className="li li-search color-gray" aria-hidden="true"></i>
                                            </span>
                                        </button>
                                    </span>

                                    <form>
                                        <div className="typeahead__container">
                                            <div className="typeahead__field">

                                                <span className="typeahead__query">
                                                    <input className="js-typeahead form-control form-control-lg form-control-block"
                                                        id="where-to-buy-search-input"
                                                        name="q"
                                                        type="search"
                                                        aria-label="Search by city or ZIP code"
                                                        placeholder="Search by City or ZIP Code" value={this.state.searchValue}
                                                        onChange={this.searchTextChange}
                                                        onBlur={this.searchTextBlur}
                                                        autoComplete="off" ref={(searchRef) => this.searchElement = searchRef} />
                                                </span>

                                            </div>
                                        </div>
                                    </form>
                                </div>
                                <span className="field-validation-valid text-danger" data-valmsg-for="CityOrZip" data-valmsg-replace="true"></span>
                            </div>
                            <div>
                                <div className="list-justified unfixed">
                                    <div className="list-item">
                                        <div className={drawingInstantCheckedClass}>
                                            <label>
                                                <input type="checkbox" aria-label="Drawing or Instant games filter" checked={this.state.drawingInstantChecked} onChange={this.drawingInstantCheckChange} />
                                                <span>Drawing/Instant</span>
                                            </label>
                                        </div>
                                    </div>
                                    <div className="list-item">
                                        <div className={sportsCheckedClass}>
                                            <label>
                                                <input type="checkbox" aria-label="Sports filter" checked={this.state.sportsChecked} onChange={this.sportsCheckChange} />
                                                <span>Sports</span>
                                            </label>
                                        </div>
                                    </div>
                                    <div className="list-item">
                                        <div className={kenoCheckedClass}>
                                            <label>
                                                <input type="checkbox" aria-label="Keno filter" checked={this.state.kenoChecked} onChange={this.kenoCheckChange} />
                                                <span>Keno<sup>&reg;</sup></span>
                                            </label>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            <div className={distanceCheckedClass}>
                                <label>
                                    <input type="checkbox" aria-label="Locations nearby filter" checked={distanceChecked} onChange={this.distanceCheckChange} />
                                    <span>Locations Nearby</span>
                                </label>
                            </div>
                            <button type="submit" className="btn btn-block btn-solid btn-solid-primary" onClick={this.searchLocations}>Search</button>
                            <button type="submit" className="btn btn-block btn-solid btn-solid-primary" onClick={this.printpage}>Print Friendly</button>

                        </fieldset>
                        <LocationList locations={this.state.data} />

                    </div >
                    <div className="row mhn">
                        <div className="col-sm-6 col-sm-offset-6 col-md-7 col-md-offset-5 col-lg-8 col-lg-offset-4 phn hidden-xs">
                            <div className="map-panel">
                                <div className="embed-responsive embed-responsive-custom">
                                    <GoogleMap markers={this.state.markers} infoWindowContent={this.state.infoWindowContent} />
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        )
            ;
    }
});

ReactDOM.render(
    <LocationSearch />,
    document.getElementById('content')
);
