function cityProfile(options)
{
    var self = this;
    self.idSuffix = options["id"];
    
    self.cityProfileSelector = "div[id=cityProfile" + self.idSuffix + "]";
    self.cityPopupSelector = "div[id=cityProfilePopup" + self.idSuffix + "]";
    self.cutAutosuggestState = options["cutAutosuggestState"];
    self.showCreateNewControl = options["showCreateNewControl"];

    self.focusInValue = "";

    self.lastAutocompleteRequest = "";
    self.lastAutocompleteRequestNumber = 0;

    self.blurTimeout = null;

    self.selectCallBack = options["selectCallBack"];
    self.changeCallBack = options["changeCallBack"];

    self.inited = false;
    self.selectAutoSuggest = false;
    self.init = function()
    {
        if(self.inited) return;
        
        $(self.cityProfileSelector).ready(function(){
            
            $(self.cityProfileSelector + " input[id=cityName]:first").autocompleteNative(
                {
                    source:function(request, response) {
                        if(!self.lastAutocompleteRequest)
                            self.lastAutocompleteRequest = request.term;

                        request.requestNumber = ++self.lastAutocompleteRequestNumber;
                        $.ajax({
                            url: "/ScoutsCMS/ajax/autocomplete.php?t=city",
                            dataType: "json",
                            data: request,
                            success: function( data ) {
                                if(data.requestNumber != self.lastAutocompleteRequestNumber) {
                                    $(self.cityProfileSelector + " input[id=cityName]:first").removeClass( "ui-autocomplete-loading" );
                                    return false;
                                }

                                if(request.term.startsWith(self.lastAutocompleteRequest) && data.result.length < 1){
                                    $(self.cityProfileSelector + " input[id=cityName]:first").removeClass( "ui-autocomplete-loading" );
                                    return false;
                                }

                                self.lastAutocompleteRequest = "";
                                $(self.cityProfileSelector + " input[id=cityName]:first").removeClass( "ui-autocomplete-loading" );
                                response( data.result );
                            }
                        });
                    },
                    delay:10,
                    minLength:2,
                    select: function(event, ui)
                    {
                        self.setCityInfo(event, ui);
                        self.selectAutoSuggest = true;
                    }
                }
            ).bind("change",function(){if($(this).val() == ""){$(this).attr("retValue", "")}})
            //.focusout(function(){ $(self.cityProfileSelector + " input.cityEditControl").css("visibility", "visible");})
            .focusin(function(event){self.focusInValue = event.target.value;/*$(self.cityProfileSelector + " input.cityEditControl").css("visibility", "hidden");*/});

            if(options["showCreateNewControl"])
            {
                $(self.cityProfileSelector + " input[id=cityName]:first").bind("keyup", function(event){
                    if(event.keyCode == 13 && !self.selectAutoSuggest)
                        self.checkEnteredValue();

                    self.selectAutoSuggest = false;
                }).bind("blur", function(event){ self.blurTimeout = setTimeout(function(){self.checkEnteredValue();}, 200)});
            }
            

           $(self.cityPopupSelector).dialog({
                modal:true,
                autoOpen: false,
                width:550,
                buttons: {
                    "Save": function() {self.createNewCityFromPopup();},
                    "Close": function() {$(this).dialog("close");}
                    }
            });
            registerPopupEnterPress(self.cityPopupSelector, self.cityPopupSelector+ " ~ div.ui-dialog-buttonpane button:first");
        });
        self.inited = true;
    }

    self.setCityInfo = function(event, ui)
    {
        if( ui == null || ui.item == null) return;

        var sValue = ui.item.id;
	    var stateID = ui.item.stateID;
        var name = ui.item.value;
        if(self.cutAutosuggestState)
        {
            name = name.substr(0, name.indexOf("(") - 1);
        }

        $(self.cityProfileSelector + " input[id=cityName]:first").attr("retValue", sValue);
        $(self.cityProfileSelector + " input[id=cityName]:first").val(name);
        $(self.cityProfileSelector + " select[id=state]").val(stateID);

        self.callSelectCallBack();
    }

    self.createNewCityFromPopup = function()
    {
       var name = $(self.cityPopupSelector + " input[id=cityName]").val();
       var stateID = $(self.cityPopupSelector + " select[id=stateID]").val();

       if(name == null || name == '' || stateID == null || stateID == '')
       {
           jAlert('Enter name and state', "Error");
           return;
       }
       self.createNewCityCall(name, stateID, self.setNewCityID)
    }

    self.createNewCity = function(name)
    {
        if(self.blurTimeout)
        {
            self.closeBlurTimeout();
            if($(self.cityProfileSelector + " input[id=cityName]:first").val() != "")
            {
                self.checkEnteredValue();
                return;
            }
        }
        resetForm(self.cityPopupSelector + " .cityData");
        $(self.cityPopupSelector + " input[name=cityID]").val("");
        $(self.cityPopupSelector + " input[id=cityName]").val(name);

         $(self.cityPopupSelector).dialog("option", "title", "Create New City");
        $(self.cityPopupSelector).dialog("open");
    }

    self.createNewCityCall = function(name, stateID, successCallback)
    {
        $.ajax({
                url:"/ScoutsCMS/ajax/saveCityInfo.php",
                type: "post",
                dataType: 'json',
                data: GetFormValues(self.cityPopupSelector + " .cityData"),
                success: successCallback
            });
    }

    self.setNewCityID = function(id)
    {
        if(id)
        {
            $(self.cityProfileSelector + " input[id=cityName]:first").attr("retValue", id);
        }
        $(self.cityProfileSelector + " input[id=cityName]:first").val($(self.cityPopupSelector + " input[id=cityName]").val() + " (" +
                                                                  $(self.cityPopupSelector + " select[id=stateID] option:selected").text() + ")");
        $(self.cityProfileSelector + " select[id=state]").val($(self.cityPopupSelector + " select[id=stateID]").val());
        $(self.cityPopupSelector).dialog("close");

        self.callSelectCallBack();
    }

    self.setCityId = function(id)
    {
        $(self.cityProfileSelector + " input[id=cityName]:first").attr("retValue", id);
    }

    self.clearCityProfile = function()
    {
        $(self.cityProfileSelector + " input[id=cityName]:first").attr("retValue", "");
        $(self.cityProfileSelector + " input[id=cityName]:first").val( "");
        self.callSelectCallBack();
    }

    self.editCityInfo = function()
    {
        var id = $(self.cityProfileSelector + " input[id=cityName]:first").attr("retValue");
        
        if(!id) return;

        resetForm(self.cityPopupSelector + " .cityData");
        $(self.cityPopupSelector + " input[name=cityID]").val("");
        $.ajax({
                url:"/ScoutsCMS/ajax/cityInfo.php",
                type: "post",
                dataType: 'json',
                data: {"cityID":id},
                success: self.fillCityData
            });
    }

    self.fillCityData = function(data)
    {
        fillForm(self.cityPopupSelector + " .cityData", data);
        $(self.cityPopupSelector).dialog("option", "title", $(self.cityProfileSelector + " input[id=cityName]:first").val());
        $(self.cityPopupSelector).dialog("open");
    }

    self.checkEnteredValue = function()
    {
        self.closeBlurTimeout();
        var obj = $(self.cityProfileSelector + " input[id=cityName]:first");
        if(!self.selectAutoSuggest && obj.val() != "" && obj.is(":visible") &&
                (!obj.attr("retValue") || (obj.attr("retValue") && self.focusInValue != obj.val() && self.focusInValue)))
        {
            $.ajax({
                url:"/ScoutsCMS/ajax/checkAutocompleteValue.php?t=city",
                type: "get",
                dataType: 'json',
                data: {"term":$(self.cityProfileSelector + " input[id=cityName]:first").val()},
                success: function(data){
                    data = data.result
                    if(data.length == 0)
                    {
                        self.createNewCity($(self.cityProfileSelector + " input[id=cityName]:first").val());
                    }
                    else
                    {
                        if(data.length == 1)
                        {
                            self.setCityInfo(null, {item: data[0]});
                        }
                        else
                        {
                            var duplicateStr = "There are several cities named similarly to that you just entered. Please check the list below carefully and select one if it is among them. If it isn't, create a new one with the button at the bottom.\n";
                            for(var i in data)
                            {
                                duplicateStr += "<a class='a_button' onclick='cp" + self.idSuffix + ".setCityInfo(null, {item: " + txt2xml(JSON.stringify(data[i])) + "});$.alerts._hide();'>" + data[i].label + "</a>\n";
                            }
                            var backup = $.alerts.okButton;
                            $.alerts.okButton = "Create New";
                            jConfirm(duplicateStr, "Warning", function(r){
                                if(r)
                                {
                                     self.createNewCity($(self.cityProfileSelector + " input[id=cityName]:first").val());
                                }
                            });
                            $.alerts.okButton = backup;
                        }
                    }
                }
            });
        }
    }

    self.closeBlurTimeout = function()
    {
        if(self.blurTimeout)
        {
            clearTimeout(self.blurTimeout);
        }
        self.blurTimeout = null;
    }

    self.callSelectCallBack = function(){
        if(!self.selectCallBack) return;

        if(typeof(self.selectCallBack) == "function"){
            self.selectCallBack(self.getCurrentCityId);
        }else{
            eval(self.selectCallBack + "(" + self.getCurrentCityId + ")");            
        }
    }

    self.callChangeCallBack = function(){
        if(!self.changeCallBack) return;

        if(typeof(self.changeCallBack) == "function"){
            self.changeCallBack(self.getCurrentCityId);
        }else{
            eval(self.changeCallBack + "(" + self.getCurrentCityId + ")");
        }
    }

    self.getCurrentCityId = function()    {
        return $(self.cityProfileSelector + " input[id=cityName]:first").attr("retValue");
    }

    self.init();
}
