﻿(function ($) {

    $.fn.LocationSelector = function (options) {
  
        var settings = {
            'city': '',
            'state': '',
            'zip': '',
            'SearchCount': 10,
            'SelectedCallBack': ''
        };



        if (options) {
            this.extend(settings, options);
        }

        $(this).focus(function () { this.select(); });

        this.autocomplete({
            source: function (request, response) {
                $.ajax({
                    url: "Services/locations.asmx/SearchLocations",
                    data: "{ 'prefixText': '" + request.term + "', 'count': '" + settings["SearchCount"] + " ' }",
                    dataType: "json",
                    type: "POST",
                    contentType: "application/json; charset=utf-8",
                    dataFilter: function (data) { return data; },
                    success: function (data) {
                        response($.map(data.d, function (item) {
                            return {
                                label: item.City + ", " + item.State + " " + item.Zip,
                                value: item.City + ", " + item.State + " " + item.Zip,
                                city: item.City,
                                state: item.State,
                                zip: item.Zip
                            }
                        }))
                    }
                });
            },
            minLength: 1,
            select: function (event, ui) {
                $(this).val(ui.item.label);
                if (typeof settings["SelectedCallBack"] == 'function') {
                    settings["SelectedCallBack"].call(this, ui);
                }
                //$(document).trigger('onLocationSelected', ui);

                return false;
            }
        });


        if ((settings["city"].length > 0) && (settings["state"].length > 0) && (settings["zip"].length > 0)) {
            this.val(settings["city"] + " " + settings["state"] + ", " + settings["zip"]);
        }



    };
})(jQuery);
