
define(['jquery', 'underscore', 'requtils', 'renderer/baseeditor'], function ($, _, requtils, BaseEditor) {
    'use strict';

    var Utils = requtils.getUtils();

    /* NodeEditor Begin */
    //var NodeEditor = Renderer.NodeEditor = Utils.inherit(Renderer._BaseEditor);
    var NodeEditor = Utils.inherit(BaseEditor);

    _(NodeEditor.prototype).extend({
        _init: function() {
            BaseEditor.prototype._init.apply(this);
            this.template = this.options.templates['templates/nodeeditor.html'];
            this.readOnlyTemplate = this.options.templates['templates/nodeeditor_readonly.html'];
        },
        draw: function() {
            var _model = this.source_representation.model,
            _created_by = _model.get("created_by") || Utils._USER_PLACEHOLDER(this.renkan),
            _template = (this.renderer.isEditable() ? this.template : this.readOnlyTemplate ),
            _image_placeholder = this.options.static_url + "img/image-placeholder.png",
            _size = (_model.get("size") || 0);
            this.editor_$
            .html(_template({
                node: {
                    has_creator: !!_model.get("created_by"),
                    title: _model.get("title"),
                    uri: _model.get("uri"),
                    short_uri:  Utils.shortenText((_model.get("uri") || "").replace(/^(https?:\/\/)?(www\.)?/,'').replace(/\/$/,''),40),
                    description: _model.get("description"),
                    image: _model.get("image") || "",
                    image_placeholder: _image_placeholder,
                    color: _model.get("color") || _created_by.get("color"),
                    clip_path: _model.get("clip_path") || false,
                    created_by_color: _created_by.get("color"),
                    created_by_title: _created_by.get("title"),
                    size: (_size > 0 ? "+" : "") + _size,
                    shape: _model.get("shape") || "circle"
                },
                renkan: this.renkan,
                options: this.options,
                shortenText: Utils.shortenText
            }));
            this.redraw();
            var _this = this,
            closeEditor = function() {
                _this.editor_$.off("keyup");
                _this.editor_$.find("input, textarea, select").off("change keyup paste");
                _this.editor_$.find(".Rk-Edit-Image-File").off('change');
                _this.editor_$.find(".Rk-Edit-ColorPicker-Wrapper").off('hover');
                _this.editor_$.find(".Rk-Edit-Size-Down").off('click');
                _this.editor_$.find(".Rk-Edit-Size-Up").off('click');
                _this.editor_$.find(".Rk-Edit-Image-Del").off('click');
                _this.editor_$.find(".Rk-Edit-ColorPicker").find("li").off('hover click');
                _this.editor_$.find(".Rk-CloseX").off('click');
                _this.editor_$.find(".Rk-Edit-Goto").off('click');

                _this.renderer.removeRepresentation(_this);
                paper.view.draw();
            };

            this.editor_$.find(".Rk-CloseX").click(closeEditor);

            this.editor_$.find(".Rk-Edit-Goto").click(function() {
                if (!_model.get("uri")) {
                    return false;
                }
            });

            if (this.renderer.isEditable()) {

                var onFieldChange = _.throttle(function() {
                  _.defer(function() {
                    if (_this.renderer.isEditable()) {
                        var _data = {
                            title: _this.editor_$.find(".Rk-Edit-Title").val()
                        };
                        if (_this.options.show_node_editor_uri) {
                            _data.uri = _this.editor_$.find(".Rk-Edit-URI").val();
                            _this.editor_$.find(".Rk-Edit-Goto").attr("href",_data.uri || "#");
                        }
                        if (_this.options.show_node_editor_image) {
                            _data.image = _this.editor_$.find(".Rk-Edit-Image").val();
                            _this.editor_$.find(".Rk-Edit-ImgPreview").attr("src", _data.image || _image_placeholder);
                        }
                        if (_this.options.show_node_editor_description) {
                            _data.description = _this.editor_$.find(".Rk-Edit-Description").val();
                        }
                        if (_this.options.change_shapes) {
                            if(_model.get("shape")!==_this.editor_$.find(".Rk-Edit-Shape").val()){
                                _data.shape = _this.editor_$.find(".Rk-Edit-Shape").val();
                            }
                        }
                        _model.set(_data);
                        _this.redraw();
                    } else {
                        closeEditor();
                    }
                  });
                }, 500);

                this.editor_$.on("keyup", function(_e) {
                    if (_e.keyCode === 27) {
                        closeEditor();
                    }
                });

                this.editor_$.find("input, textarea, select").on("change keyup paste", onFieldChange);

                if(_this.options.allow_image_upload) {
                    this.editor_$.find(".Rk-Edit-Image-File").change(function() {
                        if (this.files.length) {
                            var f = this.files[0],
                            fr = new FileReader();
                            if (f.type.substr(0,5) !== "image") {
                                alert(_this.renkan.translate("This file is not an image"));
                                return;
                            }
                            if (f.size > (_this.options.uploaded_image_max_kb * 1024)) {
                                alert(_this.renkan.translate("Image size must be under ") + _this.options.uploaded_image_max_kb + _this.renkan.translate("KB"));
                                return;
                            }
                            fr.onload = function(e) {
                                _this.editor_$.find(".Rk-Edit-Image").val(e.target.result);
                                onFieldChange();
                            };
                            fr.readAsDataURL(f);
                        }
                    });
                }
                this.editor_$.find(".Rk-Edit-Title")[0].focus();

                var _picker = _this.editor_$.find(".Rk-Edit-ColorPicker");

                this.editor_$.find(".Rk-Edit-ColorPicker-Wrapper").hover(
                        function(_e) {
                            _e.preventDefault();
                            _picker.show();
                        },
                        function(_e) {
                            _e.preventDefault();
                            _picker.hide();
                        }
                );

                _picker.find("li").hover(
                        function(_e) {
                            _e.preventDefault();
                            _this.editor_$.find(".Rk-Edit-Color").css("background", $(this).attr("data-color"));
                        },
                        function(_e) {
                            _e.preventDefault();
                            _this.editor_$.find(".Rk-Edit-Color").css("background", _model.get("color") || (_model.get("created_by") || Utils._USER_PLACEHOLDER(_this.renkan)).get("color"));
                        }
                ).click(function(_e) {
                    _e.preventDefault();
                    if (_this.renderer.isEditable()) {
                        _model.set("color", $(this).attr("data-color"));
                        _picker.hide();
                        paper.view.draw();
                    } else {
                        closeEditor();
                    }
                });

                var shiftSize = function(n) {
                    if (_this.renderer.isEditable()) {
                        var _newsize = n+(_model.get("size") || 0);
                        _this.editor_$.find(".Rk-Edit-Size-Value").text((_newsize > 0 ? "+" : "") + _newsize);
                        _model.set("size", _newsize);
                        paper.view.draw();
                    } else {
                        closeEditor();
                    }
                };

                this.editor_$.find(".Rk-Edit-Size-Down").click(function() {
                    shiftSize(-1);
                    return false;
                });
                this.editor_$.find(".Rk-Edit-Size-Up").click(function() {
                    shiftSize(1);
                    return false;
                });

                this.editor_$.find(".Rk-Edit-Image-Del").click(function() {
                    _this.editor_$.find(".Rk-Edit-Image").val('');
                    onFieldChange();
                    return false;
                });
            } else {
                if (typeof this.source_representation.highlighted === "object") {
                    var titlehtml = this.source_representation.highlighted.replace(_(_model.get("title")).escape(),'<span class="Rk-Highlighted">$1</span>');
                    this.editor_$.find(".Rk-Display-Title" + (_model.get("uri") ? " a" : "")).html(titlehtml);
                    if (this.options.show_node_tooltip_description) {
                        this.editor_$.find(".Rk-Display-Description").html(this.source_representation.highlighted.replace(_(_model.get("description")).escape(),'<span class="Rk-Highlighted">$1</span>'));
                    }
                }
            }
            this.editor_$.find("img").load(function() {
                _this.redraw();
            });
        },
        redraw: function() {
            var _coords = this.source_representation.paper_coords;
            Utils.drawEditBox(this.options, _coords, this.editor_block, this.source_representation.circle_radius * 0.75, this.editor_$);
            this.editor_$.show();
            paper.view.draw();
        }
    }).value();

    /* NodeEditor End */

    return NodeEditor;

});
