function ViewState(url) {
    this.searchView = $("#add_place_search");
    this.reviewView = $("#add_place_review");
    this.addView = $("#add_place");
    this.d = $("#add_place_dialog");
    this.url = url;
    this.deactivate();

}

ViewState.prototype = {
    searchView: null,
    reviewView: null,
    addView: null,
    d: null,
    url: null,
    deactivate: function (params) {}
};

function SearchState(settings) {
    ViewState.call(this, null);
}

SearchState.inheritsFrom(ViewState, {
    searchLabel: "Zobacz czy miejsce istnieje",
    dialogTitle: "Dodaj ocenę lub nowe miejsce",
    activate: function () {
        $("#add_place_search > h3").text(this.searchLabel);
         this.d.dialog("option", "title", this.dialogTitle);
        this.searchView.show();

    },
    deactivate:function () {
        this.searchView.hide();
    }
});

function SearchQState(settings) {
    SearchState.call(this, null);
}

SearchQState.inheritsFrom(SearchState, {
    searchLabel: "Wpisz nazwę miejsca które chcesz polecić",
    dialogTitle: "Znajdź lub dodaj miejsce które chcesz polecić",
    activate: function (item) {
        this.__super__.activate.call(this, item);
    },
    deactivate: function () {
        this.__super__.deactivate.call(this);
    }
});

function AddPlaceState(settings) {
    ViewState.call(this, settings.add_place);
}

AddPlaceState.inheritsFrom(ViewState, {
    activate: function (item) {
        this.addView.show();
        this.d.dialog("option", "title", 'Dodaj nowe miejsce');
        this.d.dialog("option", "position", 'center');
        $("#add_place .place-name").focus();
        $("#add_place .place-name").val(item.value);
    },
    deactivate: function () {
        this.addView.hide();
    }
});

function AddReviewState(settings) {
    ViewState.call(this, settings.add_review);
}

AddReviewState.inheritsFrom(ViewState, {
    activate: function (item) {
        this.reviewView.show();
        $("#add_place_review .place-name").text(item.label);
        $("#add_place_id").val(item.id);
        $("#add_place_review textarea").focus();
        this.d.dialog("option", "title", 'Dodaj opinię');
        this.d.dialog("option", "position", 'center');
    },
    deactivate: function () {
        this.reviewView.hide();
    }
});


function AddPlaceQState(settings) {
    AddPlaceState.call(this, settings);
    this.url = settings.recommend_and_add;
}

AddPlaceQState.inheritsFrom(AddPlaceState, {
    activate: function (item) {
        this.__super__.activate.call(this, item);
        var d = AddPlaceDialog.get();
        this.addView.find(".question").val(d.question_id);
        $(".personal-note", this.addView).show();
        $(".ownership").hide()

    },
    deactivate: function (item) {
        this.__super__.deactivate.call(this, item);
        $(".personal-note", this.addView).hide();
        $(".ownership").show()
    }

});





var AddPlaceDialog = function (settings) {
    var self = this;


    this.states = {
        add_place: new AddPlaceState(settings)
    };

    this.addView = $("#add_place");
    this.place_id = $("#add_place_id");


    this.d = $("#add_place_dialog");
    this.d.dialog({
        autoOpen: false,
        title:'Chcę dodać miejsce lub ocenić istniejące',
        width:460,
        maxHeight:600,
        minHeight:300,
        //height:200,
        modal:true
    });

    this.citySearch = new SearchBox({
        el: $(".city-autocomplete"),
        url:settings.city_url,
        change: $.proxy(self.city_change, this),
        action_handler: $.proxy(self.city_action_handler, this),
        build_label: $.proxy(self.city_label, this),
        build_value: $.proxy(self.city_value, this),
        select: function(event, ui) {
            if (ui.item) {
                this.action_handler(ui.item.action, ui.item);
            }
            return true;
        }
    });

    var place_name = $("#add_place  .place-name");
    place_name.focus(function () {
        var self = $(this);
        var place_url = $("#add_place .place-url");
        self.stopTime("generate-url");
        self.everyTime(100, 'generate-url', function () {
            place_url.text("noclegowicze.pl/" + $.slug(self.val()))
        });
    });
    place_name.blur(function () {
        $(this).stopTime("generate-url");
    });


    var form = this.addView.find("form");
    form.submit(function () {
        var f = $(this);
        var d = AddPlaceDialog.get();
        $.post(d.getCurrentState().url, f.serialize(), function (data) {
            if (data.success) {
                d.hide();
                if (!data.is_authenticated) {
                    AuthDialog.get().register(msgs["registration_required"]);
                } else {
                    window.location.reload();
                }
            } else {
                show_errors(f, data);
            }
        }, 'json');
        return false;
    });

    this.addView.find("input.is_owned").click(function () {
        self.addView.find(".rating-section").toggle();
    });

    $(".add-place").click(function () {
        var owner = $(this).data("owner");
         AddPlaceDialog.get().show(owner);
    });
    this.setState("add_place", {});
};


AddPlaceDialog.instance = null;

AddPlaceDialog.get = function (settings) {
    if (AddPlaceDialog.instance == null) {
        AddPlaceDialog.instance = new AddPlaceDialog(settings);
    }
    return AddPlaceDialog.instance;
};

AddPlaceDialog.prototype = {
    currentState: 'add_place',
    states :{},
    question: false,

    setState: function (name, options) {
        this.states[this.currentState].deactivate(options);
        var newState = this.question ? "q_" + name : name;
        this.states[newState].activate(options);
        this.currentState = newState;
    },
    getCurrentState: function () {
        return this.states[this.currentState];
    },
    action_handler : function(action, item) {
        this[action].call(this, item);
    },
    //end actions
    city_action_handler: function(action, item) {
        //empty
    },
    city_change: function (event, ui) {
        $("#add_place input.city ").val(ui.item ? ui.item.id : '');
    },
    city_label: function (item) {
        return item.path;
    },
    city_value: function (item) {
        return item.name;

    },
    hide: function () {
        this.d.dialog("close");
    },
    show: function (owner) {
        this.d.dialog("open");
        if (owner) {
            this.addView.find(".rating-section").hide();
            $("input.is_owned", this.d).prop("checked", true);
        } else {
            self.addView.find(".rating-section").show();
            $("input.is_owned", this.d).prop("checked", false);
        }

    }
};



var UploadPhoto = function (options) {

    var settings = {
        url: null,
        uploadButton: null,
        uploadList: null,
        flash_url: "/js/swfupload/swfupload.swf",
        csrf_token: null,
        place: null,
        dialogCloseHandler: null
    };

    $.extend(settings, options);

    this.needsAuth = true;
    this.queueSize = 0;
    var self = this;
    this.fileUpload  = fileUpload({
        url: settings.url,
        uploadButton: settings.uploadButton,
        uploadList: settings.uploadList,
        button_width : settings.buttonWidth,
        button_height : settings.buttonHeight,
        flash_url : settings.flash_url,
        button_action: SWFUpload.BUTTON_ACTION.SELECT_FILE,
        file_queue_limit: 1,
        file_dialog_start_handler: function () {
            self.fileUpload.cancelUpload();
            if (settings.uploadList) {
                settings.uploadList.html("");
            }
        },
        dialogCloseHandler: function (selected, queued, total) {
            self.queueSize = total;
        },
        params: {
            csrfmiddlewaretoken: settings.csrf_token,
            place: settings.place
        },
        success: function (file, json) {
            self.needsAuth = !json.is_authenticated;
        },
        complete: function (numFiles) {
            if (self.needsAuth) {
                AuthDialog.get().register(msgs["registration_required"]);
                self.queueSize = 0;
                self.needsAuth = false;
            } else {
                window.location.reload();
            }
        }
    });
};


UploadPhoto.prototype = {
    fileUpload: null,
    needsAuth:false,
    queueSize: 0,
    addData : function (data) {
        for (var d in data) {
            this.fileUpload.addPostParam(d, data[d]);
        }
    },
    start: function (form) {
        if (this.queueSize > 0) {
            this.fileUpload.startUpload();
        } else {
            var settings = this.fileUpload.settings;
            $.post(settings.upload_url, settings.post_params, function (data) {
                if (data.success) {
                    if (!data.is_authenticated) {
                        AuthDialog.get().register(msgs["registration_required"]);
                    } else {
                        window.location.reload();
                    }
                } else {
                    show_errors(form, data);
                }
            }, "json");
        }
    }
};


var VisitPlaceDialog = function (settings) {
    var self = this;
    var d = $("#visit_dialog");
    d.dialog({
        title: 'Odwiedź miejsce',
        modal: true,
        width: 350,
        autoOpen: false,
        position: 'center',
        close: function () {
            self.fileUpload.removePostParam("place");
            self.needsAuth = false;
        }
    });

    $(".visit-place").each(function () {
        $(this).click(function () {
            d.dialog("open");
            self.place = $(this).data("place-id");
        });
    });




    $("#visit_dialog_start_upload").click(function () {
         self.setPlace(self.place);
         self.fileUpload.startUpload();
    });
};

VisitPlaceDialog.prototype = {
    fileUpload: null,
    needsAuth:false,
    place:null,
    setPlace: function(place) {
        this.fileUpload.addPostParam("place", place);
    }
};


