Rkns.Renderer = {
    _MINIMAP_MARGIN_X: 20,
    _MINIMAP_MARGIN_Y: 20,
    _MIN_DRAG_DISTANCE: 2,
    _NODE_SIZE_BASE: 25,
    _NODE_BUTTON_WIDTH: 40,
    _EDGE_BUTTON_INNER: 2,
    _EDGE_BUTTON_OUTER: 40,
    _NODE_FONT_SIZE: 10,
    _EDGE_FONT_SIZE: 9,
    _EDGE_DISTANCE: 3,
    _NODE_MAX_CHAR: 50,
    _EDGE_MAX_CHAR: 40,
    _ARROW_LENGTH: 16,
    _ARROW_WIDTH: 8,
    _EDITOR_ARROW_LENGTH : 20,
    _EDITOR_ARROW_WIDTH : 40,
    _EDITOR_MARGIN : 15,
    _EDITOR_PADDING : 10,
    _EDITOR_GRADIENT : new paper.Gradient(['#f0f0f0', '#d0d0d0']),
    _CLICKMODE_ADDNODE : 1,
    _CLICKMODE_STARTEDGE : 2,
    _CLICKMODE_ENDEDGE : 3,
    _IMAGE_MAX_KB : 500,
    _NODE_SIZE_STEP: Math.LN2/4,
    _MINIMAP_WIDTH: 160,
    _MINIMAP_HEIGHT: 120,
    _USER_PLACEHOLDER : {
        color: "#000000",
        title: "(unknown user)",
        get: function(attr) {
            return this[attr] || false;
        }
    },
    _BOOKMARKLET_CODE: function(_renkan) {
    	return "(function(a,b,c,d,e,f,h,i,j,k,l,m,n,o,p,q,r){a=document;b=a.body;c=a.location.href;j='draggable';m='text/x-iri-';d=a.createElement('div');d.innerHTML='<p_style=\"position:fixed;top:0;right:0;font:bold_18px_sans-serif;color:#fff;background:#909;padding:10px;z-index:100000;\">"
	    + _renkan.translate("Drag items from this website, drop them in Renkan").replace(/ /g,"_")
	    + "</p>'.replace(/_/g,String.fromCharCode(32));b.appendChild(d);e=[{r:/https?:\\/\\/[^\\/]*twitter\\.com\\//,s:'.tweet',n:'twitter'},{r:/https?:\\/\\/[^\\/]*google\\.[^\\/]+\\//,s:'.g',n:'google'},{r:/https?:\\/\\/[^\\/]*lemonde\\.fr\\//,s:'[data-vr-contentbox]',n:'lemonde'}];f=false;e.forEach(function(g){if(g.r.test(c)){f=g;}});if(f){h=function(){Array.prototype.forEach.call(a.querySelectorAll(f.s),function(i){i[j]=true;k=i.style;k.borderWidth='2px';k.borderColor='#909';k.borderStyle='solid';k.backgroundColor='rgba(200,0,180,.1)';})};window.setInterval(h,500);h();};a.addEventListener('dragstart',function(k){l=k.dataTransfer;l.setData(m+'source-uri',c);l.setData(m+'source-title',a.title);n=k.target;if(f){o=n;while(!o.attributes[j]){o=o.parentNode;if(o==b){break;}}}if(f&&o.attributes[j]){p=o.cloneNode(true);l.setData(m+'specific-site',f.n)}else{q=a.getSelection();if(q.type==='Range'||!q.type){p=q.getRangeAt(0).cloneContents();}else{p=n.cloneNode();}}r=a.createElement('div');r.appendChild(p);l.setData('text/x-iri-selected-text',r.textContent.trim());l.setData('text/x-iri-selected-html',r.innerHTML);},false);})();"
    }
}

Rkns.Renderer.Utils = {
    drawEditBox : function(_coords, _path, _width, _xmargin, _selector) {
        _selector.css({
            width: (_width - 2* Rkns.Renderer._EDITOR_PADDING),
        })
        var _height = _selector.outerHeight() + 2* Rkns.Renderer._EDITOR_PADDING,
            _isLeft = (_coords.x < paper.view.center.x ? 1 : -1),
            _left = _coords.x + _isLeft * ( _xmargin + Rkns.Renderer._EDITOR_ARROW_LENGTH ),
            _right = _coords.x + _isLeft * ( _xmargin + Rkns.Renderer._EDITOR_ARROW_LENGTH + _width ),
            _top = _coords.y - _height / 2;
        if (_top < Rkns.Renderer._EDITOR_MARGIN) {
            _top = Math.min( Rkns.Renderer._EDITOR_MARGIN, _coords.y - Rkns.Renderer._EDITOR_ARROW_WIDTH / 2 );
        }
        var _bottom = _top + _height;
        if (_bottom > (paper.view.size.height - Rkns.Renderer._EDITOR_MARGIN)) {
            _bottom = Math.max( paper.view.size.height - Rkns.Renderer._EDITOR_MARGIN, _coords.y + Rkns.Renderer._EDITOR_ARROW_WIDTH / 2 );
            _top = _bottom - _height;
        }
        _path.segments[0].point
            = _path.segments[7].point
            = _coords.add([_isLeft * _xmargin, 0]);
        _path.segments[1].point.x
            = _path.segments[2].point.x
            = _path.segments[5].point.x
            = _path.segments[6].point.x
            = _left;
        _path.segments[3].point.x
            = _path.segments[4].point.x
            = _right;
        _path.segments[2].point.y
            = _path.segments[3].point.y
            = _top;
        _path.segments[4].point.y
            = _path.segments[5].point.y
            = _bottom;
        _path.segments[1].point.y = _coords.y - Rkns.Renderer._EDITOR_ARROW_WIDTH / 2;
        _path.segments[6].point.y = _coords.y + Rkns.Renderer._EDITOR_ARROW_WIDTH / 2;
        _path.closed = true;
        _path.fillColor = new paper.GradientColor(Rkns.Renderer._EDITOR_GRADIENT, [0,_top], [0, _bottom]);
        _selector.css({
            left: (Rkns.Renderer._EDITOR_PADDING + Math.min(_left, _right)),
            top: (Rkns.Renderer._EDITOR_PADDING + _top)
        });
    },
    sector : function(_repr, _inR, _outR, _startAngle, _endAngle, _padding, _imgsrc, _caption) {
        var _startRads = _startAngle * Math.PI / 180,
            _endRads = _endAngle * Math.PI / 180,
            _img = new Image(),
            _span = _endRads - _startRads,
            _k = .0879 * _span,
            _kin = _k * _inR,
            _kout = _k * _outR,
            _startdx = - Math.sin(_startRads),
            _startdy = Math.cos(_startRads),
            _startXIn = Math.cos(_startRads) * _inR + _padding * _startdx,
            _startYIn = Math.sin(_startRads) * _inR + _padding * _startdy,
            _startXOut = Math.cos(_startRads) * _outR + _padding * _startdx,
            _startYOut = Math.sin(_startRads) * _outR + _padding * _startdy,
            _enddx = - Math.sin(_endRads),
            _enddy = Math.cos(_endRads),
            _endXIn = Math.cos(_endRads) * _inR - _padding * _enddx,
            _endYIn = Math.sin(_endRads) * _inR - _padding * _enddy,
            _endXOut = Math.cos(_endRads) * _outR - _padding * _enddx,
            _endYOut = Math.sin(_endRads) * _outR - _padding * _enddy,
            _centerR = (_inR + _outR)/2,
            _centerRads = (_startRads + _endRads) / 2,
            _centerX = Math.cos(_centerRads) * _centerR,
            _centerY = Math.sin(_centerRads) * _centerR,
            _centerXIn = Math.cos(_centerRads) * _inR,
            _centerXOut = Math.cos(_centerRads) * _outR,
            _centerYIn = Math.sin(_centerRads) * _inR,
            _centerYOut = Math.sin(_centerRads) * _outR,
            _textX = Math.cos(_centerRads) * (_outR + 3),
            _textY = Math.sin(_centerRads) * (_outR + 3),
            _segments = [];
    	_repr.renderer.buttons_layer.activate();
        var _path = new paper.Path();
        _path.add([_startXIn, _startYIn]);
        _path.arcTo([_centerXIn, _centerYIn], [_endXIn, _endYIn]);
        _path.lineTo([_endXOut,  _endYOut]);
        _path.arcTo([_centerXOut, _centerYOut], [_startXOut, _startYOut]);
        _path.fillColor = "#333333";
        _path.opacity = .5;
        _path.closed = true;
        _path.__representation = _repr;
        if (_textX >= -2 && _textX <= 2) {
            if (_textY > 0) {
                _textY += 6;
            }
        }
        var _text = new paper.PointText(_textX,_textY);
        _text.characterStyle = {
            fontSize: 9,
            fillColor: '#c000c0'
        };
        if (_textX > 2) {
            _text.paragraphStyle.justification = 'left';
        } else if (_textX < -2) {
            _text.paragraphStyle.justification = 'right';
        } else {
            _text.paragraphStyle.justification = 'center';
        }
        _text.visible = false;
        var _visible = false,
            _restPos = new paper.Point(-200, -200),
            _grp = new paper.Group([_path, _text]),
            _delta = _grp.position,
            _imgdelta = new paper.Point([_centerX, _centerY]),
            _currentPos = new paper.Point(0,0);
        _text.content = _caption;
        _grp.visible = false;
        _grp.position = _restPos;
        var _res = {
            show: function() {
                _visible = true;
                _grp.position = _currentPos.add(_delta);
                _grp.visible = true;
            },
            moveTo: function(_point) {
                _currentPos = _point;
                if (_visible) {
                    _grp.position = _point.add(_delta);
                }
            },
            hide: function() {
                _visible = false;
                _grp.visible = false;
                _grp.position = _restPos;
            },
            select: function() {
                _path.opacity = .8;
                _text.visible = true;
            },
            unselect: function() {
                _path.opacity = .5;
                _text.visible = false;
            },
            destroy: function() {
                _grp.remove();
            }
        }
        _img.onload = function() {
            var _h = _img.height;
            var _raster = new paper.Raster(_img);
            _raster.position = _imgdelta.add(_grp.position).subtract(_delta);
            _grp.addChild(_raster);
        }
        _img.src = _imgsrc;
        return _res
    }
}

Rkns.Renderer._BaseRepresentation = function(_renderer, _model) {
    if (typeof _renderer !== "undefined") {
        this.renderer = _renderer;
        this.project = _renderer.renkan.project;
        this.model = _model;
        if (this.model) {
            var _this = this;
            this._changeBinding = function() {
                _this.redraw();
            }
            this._removeBinding = function() {
                _renderer.removeRepresentation(_this);
                _renderer.redraw();
            }
            this.model.on("change", this._changeBinding );
            this.model.on("remove", this._removeBinding );
        }
    }
}

Rkns.Renderer._BaseRepresentation.prototype.super = function(_func) {
    Rkns.Renderer._BaseRepresentation.prototype[_func].apply(this, Array.prototype.slice.call(arguments, 1));
}

Rkns.Renderer._BaseRepresentation.prototype.moveTo = function() {}

Rkns.Renderer._BaseRepresentation.prototype.show = function() {}

Rkns.Renderer._BaseRepresentation.prototype.hide = function() {}

Rkns.Renderer._BaseRepresentation.prototype.select = function() {}

Rkns.Renderer._BaseRepresentation.prototype.unselect = function() {}

Rkns.Renderer._BaseRepresentation.prototype.highlight = function() {}

Rkns.Renderer._BaseRepresentation.prototype.unhighlight = function() {}

Rkns.Renderer._BaseRepresentation.prototype.mouseup = function() {}

Rkns.Renderer._BaseRepresentation.prototype.destroy = function() {
    if (this.model) {
        this.model.off("change", this._changeBinding );
        this.model.off("remove", this._removeBinding );
    }
}

Rkns.Renderer._BaseRepresentation.prototype.resetCoords = function() {
    this.paper_coords = undefined;
}

Rkns.Renderer.Node = Rkns.Utils.inherit(Rkns.Renderer._BaseRepresentation);

Rkns.Renderer.Node.prototype._init = function() {
    this.renderer.node_layer.activate();
    this.type = "Node";
    this.circle = new paper.Path.Circle([0, 0], 1);
    this.circle.fillColor = '#ffffff';
    this.circle.__representation = this;
    this.circle.strokeWidth = 2;
    this.title = new paper.PointText([0,0]);
    this.title.characterStyle = {
        fontSize: Rkns.Renderer._NODE_FONT_SIZE,
        fillColor: 'black'
    };
    if (this.renderer.renkan.read_only) {
        this.edit_button = new Rkns.Renderer._BaseRepresentation(this.renderer, null);
        this.remove_button = new Rkns.Renderer._BaseRepresentation(this.renderer, null);
        this.link_button = new Rkns.Renderer._BaseRepresentation(this.renderer, null);
    } else {
        this.edit_button = new Rkns.Renderer.NodeEditButton(this.renderer, null);
        this.edit_button.node_representation = this;
        this.remove_button = new Rkns.Renderer.NodeRemoveButton(this.renderer, null);
        this.remove_button.node_representation = this;
        this.link_button = new Rkns.Renderer.NodeLinkButton(this.renderer, null);
        this.link_button.node_representation = this;
    }
    this.last_circle_radius = 1;
    this.title.paragraphStyle.justification = 'center';
    
    this.renderer.minimap.node_layer.activate();
    this.minimap_circle = new paper.Path.Circle([0, 0], 1);
    this.renderer.minimap.node_group.addChild(this.minimap_circle);
}

Rkns.Renderer.Node.prototype.redraw = function() {
    var _model_coords = new paper.Point(this.model.get("position")),
    	_baseRadius = Rkns.Renderer._NODE_SIZE_BASE * Math.exp((this.model.get("size") || 0) * Rkns.Renderer._NODE_SIZE_STEP);
    if (!this.paper_coords) {
        this.paper_coords = this.renderer.toPaperCoords(_model_coords);
    }
    this.circle_radius = _baseRadius * this.renderer.scale;
    if (this.last_circle_radius !== this.circle_radius) {
    	if (!this.renderer.renkan.read_only) {
	    	this.edit_button.setSectorSize();
	    	this.remove_button.setSectorSize();
	    	this.link_button.setSectorSize();
	    }
	    var square = new paper.Size(this.circle_radius, this.circle_radius),
	    	topleft = this.paper_coords.subtract(square),
	    	bounds = new paper.Rectangle(topleft, square.multiply(2));
	    this.circle.fitBounds(bounds);
	    if (this.node_image) {
	    	this.node_image.fitBounds(bounds);
	    }
    } else {
    	this.circle.position = this.paper_coords;
    	if (this.node_image) {
            this.node_image.position = this.paper_coords;
        }
    }
    this.last_circle_radius = this.circle_radius;
    
    var _text = this.model.get("title") || this.renderer.renkan.translate("(untitled)");
    this.title.content = _text.length > Rkns.Renderer._NODE_MAX_CHAR ? (_text.substr(0,Rkns.Renderer._NODE_MAX_CHAR) + '…') : _text;

    this.title.position = this.paper_coords.add([0, this.circle_radius + 1.5 *Rkns.Renderer._NODE_FONT_SIZE]);
    var _color = this.model.get("color") || (this.model.get("created_by") || Rkns.Renderer._USER_PLACEHOLDER).get("color");
    this.circle.strokeColor = _color;
    this.edit_button.moveTo(this.paper_coords);
    this.remove_button.moveTo(this.paper_coords);
    this.link_button.moveTo(this.paper_coords);
    var _img = this.model.get("image");
    if (_img && _img !== this.img) {
        var _image = new Image(),
            _this = this;
        _image.onload = function() {
            if (_this.node_image) {
                _this.node_image.remove();
            }
            _this.renderer.node_layer.activate();
            var _ratio = Math.min(2 / _image.width, 2 / _image.height );
            var _raster = new paper.Raster(_image);
            if (_this.renderer.renkan.clip_images) {
	            var _clip = new paper.Path.Circle([0, 0], 1);
	            _raster.scale(_ratio);
	            _this.node_image = new paper.Group(_clip, _raster);
	            _this.node_image.opacity = .9;
	            /* This is a workaround to allow clipping at group level
	             * If opacity was set to 1, paper.js would merge all clipping groups in one (known bug).
	            */
	            _this.node_image.clipped = true;
            } else {
            	_this.node_image = _raster;
            }
            _this.node_image.__representation = _this;
		    var square = new paper.Size(_this.circle_radius, _this.circle_radius),
		    	topleft = _this.paper_coords.subtract(square),
		    	bounds = new paper.Rectangle(topleft, square.multiply(2));
		    _this.node_image.fitBounds(bounds);
            _clip.__representation = _this;
            paper.view.draw();
        }
        _image.src = _img;
    }
    this.img = _img;
    if (this.node_image && !this.img) {
        this.node_image.remove();
        delete this.node_image;
    }
    
    this.minimap_circle.fillColor = _color;
    var minipos = this.renderer.toMinimapCoords(_model_coords),
    	miniradius = this.renderer.minimap.scale * _baseRadius,
    	minisize = new paper.Size([miniradius, miniradius]);
    this.minimap_circle.fitBounds(minipos.subtract(minisize), minisize.multiply(2));
        
    Rkns._.each(this.project.get("edges").filter(function (ed) { return ((ed.to === this.model) || (ed.from === this.model));}), function(edge, index, list){
        var repr = this.renderer.getRepresentationByModel(edge);
    	if(repr != null && typeof repr.from_representation.paper_coords !== "undefined" && typeof repr.to_representation.paper_coords !== "undefined") {
    		repr.redraw();
    	}
    }, this);
}

Rkns.Renderer.Node.prototype.paperShift = function(_delta) {
	if (!this.renderer.renkan.read_only) {
		this.paper_coords = this.paper_coords.add(_delta);
    	this.redraw();
	} else {
		this.renderer.paperShift(_delta);
	}
}

Rkns.Renderer.Node.prototype.openEditor = function() {
    this.renderer.removeRepresentationsOfType("editor");
    var _editor = this.renderer.addRepresentation("NodeEditor",null);
    _editor.node_representation = this;
    _editor.draw();
}

Rkns.Renderer.Node.prototype.select = function() {
    this.circle.strokeWidth = 4;
    this.edit_button.show();
    this.remove_button.show();
    this.link_button.show();
    var _uri = this.model.get("uri");
    if (_uri) {
    	Rkns.$('.Rk-Bin-Item').each(function() {
	        var _el = Rkns.$(this);
	        if (_el.attr("data-uri") == _uri) {
	            _el.addClass("selected");
	        }
	    });
    }
    if (this.renderer.renkan.read_only) {
        this.openEditor();
    }
    this.minimap_circle.fillColor = "#ff00fc";
}

Rkns.Renderer.Node.prototype.unselect = function(_newTarget) {
    if (!_newTarget || _newTarget.node_representation !== this) {
        this.edit_button.hide();
        this.remove_button.hide();
        this.link_button.hide();
        this.circle.strokeWidth = 2;
        Rkns.$('.Rk-Bin-Item').removeClass("selected");
    	this.minimap_circle.fillColor = this.circle.strokeColor;
    }
}

Rkns.Renderer.Node.prototype.highlight = function() {
    this.circle.fillColor = "#ffff80";
    if (this.node_image) {
        this.node_image.opacity = .5;
    }
}

Rkns.Renderer.Node.prototype.unhighlight = function(_newTarget) {
    this.circle.fillColor = "#ffffff";
    if (this.node_image) {
        this.node_image.opacity = .9;
    }
}

Rkns.Renderer.Node.prototype.saveCoords = function() {
    var _coords = this.renderer.toModelCoords(this.paper_coords),
        _data = {
            position: {
                x: _coords.x,
                y: _coords.y
            }
        };
    this.model.set(_data);
}

Rkns.Renderer.Node.prototype.mouseup = function(_event) {
    if (!this.renderer.renkan.read_only) {
        if (this.renderer.is_dragging) {
            this.saveCoords();
        }
        else {
            this.openEditor();
        }
    }
    this.renderer.click_target = null;
    this.renderer.is_dragging = false;
}

Rkns.Renderer.Node.prototype.destroy = function(_event) {
    this.super("destroy");
    this.edit_button.destroy();
    this.remove_button.destroy();
    this.link_button.destroy();
    this.circle.remove();
    this.title.remove();
    this.minimap_circle.remove();
    if (this.node_image) {
        this.node_image.remove();
    }
}

/* */

Rkns.Renderer.Edge = Rkns.Utils.inherit(Rkns.Renderer._BaseRepresentation);

Rkns.Renderer.Edge.prototype._init = function() {
    this.renderer.edge_layer.activate();
    this.type = "Edge";
    this.from_representation = this.renderer.getRepresentationByModel(this.model.get("from"));
    this.to_representation = this.renderer.getRepresentationByModel(this.model.get("to"));
    this.bundle = this.renderer.addToBundles(this);
    this.line = new paper.Path();
    this.line.add([0,0],[0,0],[0,0]);
    this.line.__representation = this;
    this.line.strokeWidth = 2;
    this.arrow = new paper.Path();
    this.arrow.add([0,0],[Rkns.Renderer._ARROW_LENGTH,Rkns.Renderer._ARROW_WIDTH / 2],[0,Rkns.Renderer._ARROW_WIDTH]);
    this.arrow.__representation = this;
    this.text = new paper.PointText();
    this.text.characterStyle = {
        fontSize: Rkns.Renderer._EDGE_FONT_SIZE,
        fillColor: 'black'
    };
    this.text.paragraphStyle.justification = 'center';
    this.text_angle = 0;
    this.arrow_angle = 0;
    if (this.renderer.renkan.read_only) {
        this.edit_button = new Rkns.Renderer._BaseRepresentation(this.renderer, null);
        this.remove_button = new Rkns.Renderer._BaseRepresentation(this.renderer, null);
    } else {
        this.edit_button = new Rkns.Renderer.EdgeEditButton(this.renderer, null);
        this.edit_button.edge_representation = this;
        this.remove_button = new Rkns.Renderer.EdgeRemoveButton(this.renderer, null);
        this.remove_button.edge_representation = this;
    }
}

Rkns.Renderer.Edge.prototype.redraw = function() {
    var _p0a = this.from_representation.paper_coords,
        _p1a = this.to_representation.paper_coords,
        _v = _p1a.subtract(_p0a),
        _r = _v.length,
        _u = _v.divide(_r),
        _ortho = new paper.Point([- _u.y, _u.x]),
        _group_pos = this.bundle.getPosition(this),
        _delta = _ortho.multiply( 12 * _group_pos ),
        _p0b = _p0a.add(_delta), /* Adding a 4 px difference */
        _p1b = _p1a.add(_delta), /* to differentiate inbound and outbound links */
        _a = _v.angle,
        _textdelta = _ortho.multiply(-Rkns.Renderer._EDGE_DISTANCE),
        _handle = _v.divide(3),
        _color = this.model.get("color") || this.model.get("color") || (this.model.get("created_by") || Rkns.Renderer._USER_PLACEHOLDER).get("color");
    this.paper_coords = _p0b.add(_p1b).divide(2);
    this.line.strokeColor = _color;
    this.line.segments[0].point = _p0a;
    this.line.segments[1].point = this.paper_coords;
    this.line.segments[1].handleIn = _handle.multiply(-1);
    this.line.segments[1].handleOut = _handle;
    this.line.segments[2].point = _p1a;
    this.arrow.rotate(_a - this.arrow_angle);
    this.arrow.fillColor = _color;
    this.arrow.position = this.paper_coords.subtract(_u.multiply(4));
    this.arrow_angle = _a;
    if (_a > 90) {
        _a -= 180;
        _textdelta = _textdelta.multiply(-1);
    }
    if (_a < -90) {
        _a += 180;
        _textdelta = _textdelta.multiply(-1);
    }
    this.text.rotate(_a - this.text_angle);
    var _text = this.model.get("title");
    this.text.content = _text.length > Rkns.Renderer._EDGE_MAX_CHAR ? (_text.substr(0,Rkns.Renderer._EDGE_MAX_CHAR) + '…') : _text;
    this.text.position = this.paper_coords.add(_textdelta);
    this.text_angle = _a;
    this.edit_button.moveTo(this.paper_coords);
    this.remove_button.moveTo(this.paper_coords);
}

Rkns.Renderer.Edge.prototype.openEditor = function() {
    this.renderer.removeRepresentationsOfType("editor");
    var _editor = this.renderer.addRepresentation("EdgeEditor",null);
    _editor.edge_representation = this;
    _editor.draw();
}

Rkns.Renderer.Edge.prototype.select = function() {
    this.line.strokeWidth = 4;
    this.edit_button.show();
    this.remove_button.show();
    if (this.renderer.renkan.read_only) {
        this.openEditor();
    }
}

Rkns.Renderer.Edge.prototype.unselect = function(_newTarget) {
    if (!_newTarget || _newTarget.edge_representation !== this) {
        this.edit_button.hide();
        this.remove_button.hide();
        this.line.strokeWidth = 2;
    }
}

Rkns.Renderer.Edge.prototype.mouseup = function(_event) {
    if (!this.renderer.renkan.read_only) {
        if (this.renderer.is_dragging) {
            this.from_representation.saveCoords();
            this.to_representation.saveCoords();
        } else {
            this.openEditor();
        }
    }
    this.renderer.click_target = null;
    this.renderer.is_dragging = false;
}

Rkns.Renderer.Edge.prototype.paperShift = function(_delta) {
	if (!this.renderer.renkan.read_only) {
	    this.from_representation.paperShift(_delta);
	    this.to_representation.paperShift(_delta);
	} else {
		this.renderer.paperShift(_delta);
	}
}

Rkns.Renderer.Edge.prototype.destroy = function() {
    this.super("destroy");
    this.line.remove();
    this.arrow.remove();
    this.text.remove();
    this.edit_button.destroy();
    this.remove_button.destroy();
    var _this = this;
    this.bundle.edges = Rkns._(this.bundle.edges).reject(function(_edge) {
        return _edge === _this;
    });
}

/* */

Rkns.Renderer.TempEdge = Rkns.Utils.inherit(Rkns.Renderer._BaseRepresentation);

Rkns.Renderer.TempEdge.prototype._init = function() {
    this.renderer.edge_layer.activate();
    this.type = "temp-edge";
    
    var _color = (this.project.get("users").get(this.renderer.renkan.current_user) || Rkns.Renderer._USER_PLACEHOLDER).get("color");
    this.line = new paper.Path();
    this.line.strokeColor = _color;
    this.line.add([0,0],[0,0]);
    this.line.__representation = this;
    this.arrow = new paper.Path();
    this.arrow.fillColor = _color;
    this.arrow.add([0,0],[Rkns.Renderer._ARROW_LENGTH,Rkns.Renderer._ARROW_WIDTH / 2],[0,Rkns.Renderer._ARROW_WIDTH]);
    this.arrow.__representation = this;
    this.arrow_angle = 0;
}

Rkns.Renderer.TempEdge.prototype.redraw = function() {
    var _p0 = this.from_representation.paper_coords,
        _p1 = this.end_pos,
        _a = _p1.subtract(_p0).angle,
        _c = _p0.add(_p1).divide(2);
    this.line.segments[0].point = _p0;
    this.line.segments[1].point = _p1;
    this.arrow.rotate(_a - this.arrow_angle);
    this.arrow.position = _c;
    this.arrow_angle = _a;
}

Rkns.Renderer.TempEdge.prototype.paperShift = function(_delta) {
    this.end_pos = this.end_pos.add(_delta);
    var _hitResult = paper.project.hitTest(this.end_pos);
    this.renderer.findTarget(_hitResult);
    this.redraw();
}

Rkns.Renderer.TempEdge.prototype.mouseup = function(_event) {
    var _hitResult = paper.project.hitTest(_event.point),
        _model = this.from_representation.model,
        _endDrag = true;
    if (_hitResult && typeof _hitResult.item.__representation !== "undefined") {
        var _target = _hitResult.item.__representation;
        if (_target.type === "Node" && _model !== _target.model) {
            var _data = {
                id: Rkns.Utils.getUID('edge'),
                created_by: this.renderer.renkan.current_user,
                from: _model.get("_id"),
                to: _target.model.get("_id")
            };
            this.project.addEdge(_data);
        }
        if (_model === _target.model || (_target.node_representation && _target.node_representation.model === _model)) {
            _endDrag = false;
            this.renderer.is_dragging = true;
        }
    }
    if (_endDrag) {
        this.renderer.click_target = null;
        this.renderer.is_dragging = false;
        this.renderer.removeRepresentation(this);
        paper.view.draw();
    }
}

Rkns.Renderer.TempEdge.prototype.destroy = function() {
    this.arrow.remove();
    this.line.remove();
}

/* */

Rkns.Renderer.NodeEditor = Rkns.Utils.inherit(Rkns.Renderer._BaseRepresentation);

Rkns.Renderer.NodeEditor.prototype._init = function() {
    this.renderer.buttons_layer.activate();
    this.type = "editor";
    this.editor_block = new paper.Path();
    var _pts = Rkns._(Rkns._.range(8)).map(function() {return [0,0]});
    this.editor_block.add.apply(this.editor_block, _pts);
    this.editor_block.strokeWidth = 2;
    this.editor_block.strokeColor = "#999999";
    this.editor_block.fillColor = "#e0e0e0";
    this.editor_block.opacity = .8;
    this.editor_$ = Rkns.$('<div>')
        .appendTo(this.renderer.editor_$)
        .css({
            position: "absolute",
            opacity: .8
        })
        .hide();
}

Rkns.Renderer.NodeEditor.prototype.template = Rkns._.template(
    '<h2><span class="Rk-CloseX">&times;</span><%-translate("Edit Node")%></span></h2>'
    + '<p><label><%-translate("Title:")%></label><input class="Rk-Edit-Title" type="text" value="<%-node.title%>"/></p>'
    + '<p><label><%-translate("URI:")%></label><input class="Rk-Edit-URI" type="text" value="<%-node.uri%>"/><a class="Rk-Edit-Goto" href="<%-node.uri%>" target="_blank"></a></p>'
    + '<p><label><%-translate("Description:")%></label><textarea class="Rk-Edit-Description"><%-node.description%></textarea></p>'
    + '<p><span class="Rk-Editor-Label"><%-translate("Size:")%></span><a href="#" class="Rk-Edit-Size-Down">-</a><span class="Rk-Edit-Size-Value"><%-node.size%></span><a href="#" class="Rk-Edit-Size-Up">+</a></p>'
    + '<div class="Rk-Editor-p"><span class="Rk-Editor-Label"><%-translate("Node color:")%></span><div class="Rk-Edit-ColorPicker-Wrapper"><span class="Rk-Edit-Color" style="background:<%-node.color%>;"><span class="Rk-Edit-ColorTip"></span></span><ul class="Rk-Edit-ColorPicker">'
    + '<% _(Rkns.pickerColors).each(function(c) { %><li data-color="<%=c%>" style="background: <%=c%>"></li><% }); %></ul><span class="Rk-Edit-ColorPicker-Text">Choose color</span></div></div>'
    + '<img class="Rk-Edit-ImgPreview" src="<%-node.image || node.image_placeholder%>" />'
    + '<p><label><%-translate("Image URL:")%></label><input class="Rk-Edit-Image" type="text" value="<%-node.image%>"/></p>'
    + '<p><label><%-translate("Choose Image File:")%></label><input class="Rk-Edit-Image-File" type="file" accept="image/*"/></p>'    
    + '<p><span class="Rk-Editor-Label"><%-translate("Created by:")%></span> <span class="Rk-UserColor" style="background:<%-node.created_by_color%>;"></span><%-node.created_by_title%></p>'
);

Rkns.Renderer.NodeEditor.prototype.readOnlyTemplate = Rkns._.template(
    '<h2><span class="Rk-CloseX">&times;</span><span class="Rk-UserColor" style="background:<%-node.color%>;"></span><%-node.title%></span></h2>'
    + '<p><a href="<%-node.uri%>" target="_blank"><%-node.uri%></a></p>'
    + '<p><%-node.description%></p>'
    + '<p><span class="Rk-Editor-Label"><%-translate("Created by:")%></span><span class="Rk-UserColor" style="background:<%-node.created_by_color%>;"></span><%-node.created_by_title%></p>'
);

Rkns.Renderer.NodeEditor.prototype.draw = function() {
    var _model = this.node_representation.model,
        _created_by = _model.get("created_by") || Rkns.Renderer._USER_PLACEHOLDER,
        _template = (this.renderer.renkan.read_only ? this.readOnlyTemplate : this.template),
        _image_placeholder = this.renderer.renkan.static_url + "img/image-placeholder.png",
        _size = (_model.get("size") || 0);
    this.editor_$
        .html(_template({
            node: {
                title: _model.get("title"),
                uri: _model.get("uri"),
                description: _model.get("description"),
                image: _model.get("image") || "",
                image_placeholder: _image_placeholder,
                color: _model.get("color") || _created_by.get("color"),
                created_by_color: _created_by.get("color"),
                created_by_title: _created_by.get("title"),
                size: (_size > 0 ? "+" : "") + _size
            },
            translate: this.renderer.renkan.translate
        }));
    this.redraw();
    var _this = this;
    this.editor_$.find(".Rk-CloseX").click(function() {
        _this.renderer.removeRepresentation(_this);
        paper.view.draw();
    });
    if (!this.renderer.renkan.read_only) {
    	
    	var onFieldChange = Rkns._(function() {
    		Rkns._(function() {
	            var _uri = _this.editor_$.find(".Rk-Edit-URI").val(),
	                _image = _this.editor_$.find(".Rk-Edit-Image").val();
	            _this.editor_$.find(".Rk-Edit-ImgPreview").attr("src", _image || _image_placeholder);
	            _this.editor_$.find(".Rk-Edit-Goto").attr("href",_uri);
	            var _data = {
	                title: _this.editor_$.find(".Rk-Edit-Title").val(),
	                description: _this.editor_$.find(".Rk-Edit-Description").val(),
	                uri: _uri,
	                image: _image
	            }
	            _model.set(_data);
	            _this.redraw();
    		}).defer();
    	}).throttle(500);
    	
    	this.editor_$.find("input, textarea").bind("change keyup paste", onFieldChange);
    	
        this.editor_$.find(".Rk-Edit-Image-File").bind("change", function() {
        	if (this.files.length) {
        		var f = this.files[0],
        			fr = new FileReader();
    			if (f.type.substr(0,5) !== "image") {
    				alert(_this.renderer.renkan.translate("This file is not an image"));
    				return;
    			}
    			if (f.size > (Rkns.Renderer._IMAGE_MAX_KB * 1024)) {
    				alert(_this.renderer.renkan.translate("Image size must be under ")+Rkns.Renderer._IMAGE_MAX_KB+_this.renderer.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();
        this.editor_$.find(".Rk-Edit-ColorPicker-Wrapper").hover(
            function() { _this.editor_$.find(".Rk-Edit-ColorPicker").show(); },
            function() { _this.editor_$.find(".Rk-Edit-ColorPicker").hide(); }
        );
        this.editor_$.find(".Rk-Edit-ColorPicker li").hover(
            function() { _this.editor_$.find(".Rk-Edit-Color").css("background", $(this).attr("data-color")); },
            function() { _this.editor_$.find(".Rk-Edit-Color").css("background", _model.get("color") || (_model.get("created_by") || Rkns.Renderer._USER_PLACEHOLDER).get("color")) }
        ).click(function() {
            _model.set("color", $(this).attr("data-color"));
        });
        
        function shiftSize(n) {
        	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();
        }
        
        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("img").load(function() {
        _this.redraw();
    });
}

Rkns.Renderer.NodeEditor.prototype.redraw = function() {
    var _coords = this.node_representation.paper_coords;
    Rkns.Renderer.Utils.drawEditBox(_coords, this.editor_block, 250, 20, this.editor_$);
    this.editor_$.show();
    paper.view.draw();
}

Rkns.Renderer.NodeEditor.prototype.destroy = function() {
    this.editor_block.remove();
    this.editor_$.detach();
}

/* */

Rkns.Renderer.EdgeEditor = Rkns.Utils.inherit(Rkns.Renderer._BaseRepresentation);

Rkns.Renderer.EdgeEditor.prototype._init = function() {
    this.renderer.buttons_layer.activate();
    this.type = "editor";
    this.editor_block = new paper.Path();
    var _pts = Rkns._(Rkns._.range(8)).map(function() {return [0,0]});
    this.editor_block.add.apply(this.editor_block, _pts);
    this.editor_block.strokeWidth = 2;
    this.editor_block.strokeColor = "#999999";
    this.editor_block.fillColor = "#e0e0e0";
    this.editor_block.opacity = .8;
    this.editor_$ = Rkns.$('<div>')
        .appendTo(this.renderer.editor_$)
        .css({
            position: "absolute",
            opacity: .8
        })
        .hide();
}

Rkns.Renderer.EdgeEditor.prototype.template = Rkns._.template(
    '<h2><span class="Rk-CloseX">&times;</span><%-translate("Edit Edge")%></span></h2>'
    + '<p><label><%-translate("Title:")%></label><input class="Rk-Edit-Title" type="text" value="<%-edge.title%>"/></p>'
    + '<p><label><%-translate("URI:")%></label><input class="Rk-Edit-URI" type="text" value="<%-edge.uri%>"/><a class="Rk-Edit-Goto" href="<%-edge.uri%>" target="_blank"></a></p>'
    + '<% if (properties.length) { %><p><label><%-translate("Choose from vocabulary:")%></label><select class="Rk-Edit-Vocabulary">'
    + '<% _(properties).each(function(ontology) { %><option class="Rk-Edit-Vocabulary-Class" value=""><%- translate(ontology.label) %></option>'
    + '<% _(ontology.properties).each(function(property) { var uri = ontology["base-uri"] + property.uri; %><option class="Rk-Edit-Vocabulary-Property" value="<%- uri %>'
    + '"<% if (uri === edge.uri) { %> selected<% } %>><%- translate(property.label) %></option>'
    + '<% }) %><% }) %></select></p><% } %>'
    + '<div class="Rk-Editor-p"><span class="Rk-Editor-Label"><%-translate("Edge color:")%></span><div class="Rk-Edit-ColorPicker-Wrapper"><span class="Rk-Edit-Color" style="background:<%-edge.color%>;"><span class="Rk-Edit-ColorTip"></span></span><ul class="Rk-Edit-ColorPicker">'
    + '<% _(Rkns.pickerColors).each(function(c) { %><li data-color="<%=c%>" style="background: <%=c%>"></li><% }); %></ul><span class="Rk-Edit-ColorPicker-Text">Choose color</span></div></div>'
    + '<p><span class="Rk-Editor-Label"><%-translate("From:")%></span><span class="Rk-UserColor" style="background:<%-edge.from_color%>;"></span><%-edge.from_title%></p>'
    + '<p><span class="Rk-Editor-Label"><%-translate("To:")%></span><span class="Rk-UserColor" style="background:<%-edge.to_color%>;"></span><%-edge.to_title%></p>'
    + '<p><span class="Rk-Editor-Label"><%-translate("Created by:")%></span><span class="Rk-UserColor" style="background:<%-edge.created_by_color%>;"></span><%-edge.created_by_title%></p>'
);

Rkns.Renderer.EdgeEditor.prototype.readOnlyTemplate = Rkns._.template(
    '<h2><span class="Rk-CloseX">&times;</span><span class="Rk-UserColor" style="background:<%-edge.color%>;"></span><%- edge.title %></span></h2>'
    + '<p><a href="<%-edge.uri%>" target="_blank"><%-edge.uri%></a></p>'
    + '<p><%-edge.description%></p>'
    + '<p><span class="Rk-Editor-Label"><%-translate("From:")%></span><span class="Rk-UserColor" style="background:<%-edge.from_color%>;"></span><%-edge.from_title%></p>'
    + '<p><span class="Rk-Editor-Label"><%-translate("To:")%></span><span class="Rk-UserColor" style="background:<%-edge.to_color%>;"></span><%-edge.to_title%></p>'
    + '<p><span class="Rk-Editor-Label"><%-translate("Created by:")%></span><span class="Rk-UserColor" style="background:<%-edge.created_by_color%>;"></span><%-edge.created_by_title%></p>'
);

Rkns.Renderer.EdgeEditor.prototype.draw = function() {
    var _model = this.edge_representation.model,
        _from_model = _model.get("from"),
        _to_model = _model.get("to"),
        _created_by = _model.get("created_by") || Rkns.Renderer._USER_PLACEHOLDER,
        _template = (this.renderer.renkan.read_only ? this.readOnlyTemplate : this.template);
    this.editor_$
        .html(_template({
            edge: {
                title: _model.get("title"),
                uri: _model.get("uri"),
                description: _model.get("description"),
                color: _model.get("color") || _created_by.get("color"),
                from_title: _from_model.get("title"),
                to_title: _to_model.get("title"),
                from_color: _from_model.get("color") || (_from_model.get("created_by") || Rkns.Renderer._USER_PLACEHOLDER).get("color"),
                to_color: _to_model.get("color") || (_to_model.get("created_by") || Rkns.Renderer._USER_PLACEHOLDER).get("color"),
                created_by_color: _created_by.get("color"),
                created_by_title: _created_by.get("title")
            },
            translate: this.renderer.renkan.translate,
            properties: this.renderer.renkan.properties
        }));
    this.redraw();
    var _this = this;
    this.editor_$.find(".Rk-CloseX").click(function() {
        _this.renderer.removeRepresentation(_this);
        paper.view.draw();
    });
    if (!this.renderer.renkan.read_only) {
    	
    	var onFieldChange = Rkns._(function() {
    		Rkns._(function() {
    			_this.editor_$.find(".Rk-Edit-Goto").attr("href",_this.editor_$.find(".Rk-Edit-URI").val());
	            var _data = {
	                title: _this.editor_$.find(".Rk-Edit-Title").val(),
	                uri: _this.editor_$.find(".Rk-Edit-URI").val()
	            }
	            _model.set(_data);
	            _this.edge_representation.redraw();
	            paper.view.draw();
    		}).defer();
    	}).throttle(500);
    	
        this.editor_$.find("input").bind("keyup change paste", onFieldChange);
        this.editor_$.find(".Rk-Edit-Vocabulary").change(function() {
        	var e = $(this),
        		v = e.val();
        	if (v) {
        		_this.editor_$.find(".Rk-Edit-Title").val(e.find(":selected").text());
        		_this.editor_$.find(".Rk-Edit-URI").val(v);
        		onFieldChange();
        	}
        });
        this.editor_$.find(".Rk-Edit-ColorPicker-Wrapper").hover(
            function() { _this.editor_$.find(".Rk-Edit-ColorPicker").show(); },
            function() { _this.editor_$.find(".Rk-Edit-ColorPicker").hide(); }
        );
        this.editor_$.find(".Rk-Edit-ColorPicker li").hover(
            function() { _this.editor_$.find(".Rk-Edit-Color").css("background", $(this).attr("data-color")); },
            function() { _this.editor_$.find(".Rk-Edit-Color").css("background", _model.get("color") || (_model.get("created_by") || Rkns.Renderer._USER_PLACEHOLDER).get("color")); }
        ).click(function() {
            _model.set("color", $(this).attr("data-color"));
            _this.redraw();
        });
    }
}

Rkns.Renderer.EdgeEditor.prototype.redraw = function() {
    var _coords = this.edge_representation.paper_coords;
    Rkns.Renderer.Utils.drawEditBox(_coords, this.editor_block, 250, 5, this.editor_$);
    this.editor_$.show();
    paper.view.draw();
}

Rkns.Renderer.EdgeEditor.prototype.destroy = function() {
    this.editor_block.remove();
    this.editor_$.detach();
}

/* */

Rkns.Renderer.NodeEditButton = Rkns.Utils.inherit(Rkns.Renderer._BaseRepresentation);

Rkns.Renderer.NodeEditButton.prototype._init = function() {
    this.type = "Node-edit-button";
    this.lastSectorInner = 0;
}

Rkns.Renderer.NodeEditButton.prototype.setSectorSize = function() {
	var sectorInner = this.node_representation.circle_radius;
	if (sectorInner !== this.lastSectorInner) {
		if (this.sector) {
			this.sector.destroy();
		}
		this.sector = Rkns.Renderer.Utils.sector(this, 1 + sectorInner, Rkns.Renderer._NODE_BUTTON_WIDTH + sectorInner, - 90, 30, 1, this.renderer.renkan.static_url+'img/edit.png', this.renderer.renkan.translate("Edit"));
		this.lastSectorInner = sectorInner;
	}
}

Rkns.Renderer.NodeEditButton.prototype.moveTo = function(_pos) {
    this.sector.moveTo(_pos);
}

Rkns.Renderer.NodeEditButton.prototype.show = function() {
    this.sector.show();
}

Rkns.Renderer.NodeEditButton.prototype.hide = function() {
    this.sector.hide();
}

Rkns.Renderer.NodeEditButton.prototype.select = function() {
    this.sector.select();
}

Rkns.Renderer.NodeEditButton.prototype.unselect = function(_newTarget) {
    this.sector.unselect();
    if (!_newTarget || (_newTarget !== this.node_representation && _newTarget.node_representation !== this.node_representation)) {
        this.node_representation.unselect();
    }
}

Rkns.Renderer.NodeEditButton.prototype.mouseup = function() {
    if (!this.renderer.is_dragging) {
        this.node_representation.openEditor();
    }
}

Rkns.Renderer.NodeEditButton.prototype.destroy = function() {
    this.sector.destroy();
}

/* */

Rkns.Renderer.NodeRemoveButton = Rkns.Utils.inherit(Rkns.Renderer._BaseRepresentation);

Rkns.Renderer.NodeRemoveButton.prototype._init = function() {
    this.type = "Node-remove-button";
    this.lastSectorInner = 0;
}

Rkns.Renderer.NodeRemoveButton.prototype.setSectorSize = function() {
	var sectorInner = this.node_representation.circle_radius;
	if (sectorInner !== this.lastSectorInner) {
		if (this.sector) {
			this.sector.destroy();
		}
		this.sector = Rkns.Renderer.Utils.sector(this, 1 + sectorInner, Rkns.Renderer._NODE_BUTTON_WIDTH + sectorInner, - 210, - 90, 1, this.renderer.renkan.static_url+'img/remove.png', this.renderer.renkan.translate("Remove"));
		this.lastSectorInner = sectorInner;
	}
}

Rkns.Renderer.NodeRemoveButton.prototype.moveTo = function(_pos) {
    this.sector.moveTo(_pos);
}

Rkns.Renderer.NodeRemoveButton.prototype.show = function() {
    this.sector.show();
}

Rkns.Renderer.NodeRemoveButton.prototype.hide = function() {
    this.sector.hide();
}

Rkns.Renderer.NodeRemoveButton.prototype.select = function() {
    this.sector.select();
}

Rkns.Renderer.NodeRemoveButton.prototype.unselect = function(_newTarget) {
    this.sector.unselect();
    if (!_newTarget || (_newTarget !== this.node_representation && _newTarget.node_representation !== this.node_representation)) {
        this.node_representation.unselect();
    }
}

Rkns.Renderer.NodeRemoveButton.prototype.mouseup = function() {
    this.renderer.removeRepresentationsOfType("editor");
    if (confirm(this.renderer.renkan.translate('Do you really wish to remove node ') + '"' + this.node_representation.model.get("title") + '"?')) {
        this.project.removeNode(this.node_representation.model);
    }
}

Rkns.Renderer.NodeRemoveButton.prototype.destroy = function() {
    this.sector.destroy();
}

/* */

Rkns.Renderer.NodeLinkButton = Rkns.Utils.inherit(Rkns.Renderer._BaseRepresentation);

Rkns.Renderer.NodeLinkButton.prototype._init = function() {
    this.type = "Node-link-button";
    this.lastSectorInner = 0;
}

Rkns.Renderer.NodeLinkButton.prototype.setSectorSize = function() {
	var sectorInner = this.node_representation.circle_radius;
	if (sectorInner !== this.lastSectorInner) {
		if (this.sector) {
			this.sector.destroy();
		}
		this.sector = Rkns.Renderer.Utils.sector(this, 1 + sectorInner, Rkns.Renderer._NODE_BUTTON_WIDTH + sectorInner, 30, 150, 1, this.renderer.renkan.static_url+'img/link.png', this.renderer.renkan.translate("Link to another node"));
		this.lastSectorInner = sectorInner;
	}
}

Rkns.Renderer.NodeLinkButton.prototype.moveTo = function(_pos) {
    this.sector.moveTo(_pos);
}

Rkns.Renderer.NodeLinkButton.prototype.show = function() {
    this.sector.show();
}

Rkns.Renderer.NodeLinkButton.prototype.hide = function() {
    this.sector.hide();
}

Rkns.Renderer.NodeLinkButton.prototype.select = function() {
    this.sector.select();
}

Rkns.Renderer.NodeLinkButton.prototype.unselect = function(_newTarget) {
    this.sector.unselect();
    if (!_newTarget || (_newTarget !== this.node_representation && _newTarget.node_representation !== this.node_representation)) {
        this.node_representation.unselect();
    }
}

Rkns.Renderer.NodeLinkButton.prototype.destroy = function() {
    this.sector.destroy();
}

/* */

Rkns.Renderer.EdgeEditButton = Rkns.Utils.inherit(Rkns.Renderer._BaseRepresentation);

Rkns.Renderer.EdgeEditButton.prototype._init = function() {
    this.type = "Edge-edit-button";
    this.sector = Rkns.Renderer.Utils.sector(this, Rkns.Renderer._EDGE_BUTTON_INNER, Rkns.Renderer._EDGE_BUTTON_OUTER, - 90, 90, 1, this.renderer.renkan.static_url+'img/edit.png', this.renderer.renkan.translate("Edit"));
}

Rkns.Renderer.EdgeEditButton.prototype.moveTo = function(_pos) {
    this.sector.moveTo(_pos);
}

Rkns.Renderer.EdgeEditButton.prototype.show = function() {
    this.sector.show();
}

Rkns.Renderer.EdgeEditButton.prototype.hide = function() {
    this.sector.hide();
}

Rkns.Renderer.EdgeEditButton.prototype.select = function() {
    this.sector.select();
}

Rkns.Renderer.EdgeEditButton.prototype.unselect = function(_newTarget) {
    this.sector.unselect();
    if (!_newTarget || (_newTarget !== this.edge_representation && _newTarget.edge_representation !== this.edge_representation)) {
        this.edge_representation.unselect();
    }
}

Rkns.Renderer.EdgeEditButton.prototype.mouseup = function() {
    if (!this.renderer.is_dragging) {
        this.edge_representation.openEditor();
    }
}

Rkns.Renderer.EdgeEditButton.prototype.destroy = function() {
    this.sector.destroy();
}

/* */

Rkns.Renderer.EdgeRemoveButton = Rkns.Utils.inherit(Rkns.Renderer._BaseRepresentation);

Rkns.Renderer.EdgeRemoveButton.prototype._init = function() {
    this.type = "Edge-remove-button";
    this.sector = Rkns.Renderer.Utils.sector(this, Rkns.Renderer._EDGE_BUTTON_INNER, Rkns.Renderer._EDGE_BUTTON_OUTER, - 270, -90, 1, this.renderer.renkan.static_url+'img/remove.png', this.renderer.renkan.translate("Remove"));
}
Rkns.Renderer.EdgeRemoveButton.prototype.moveTo = function(_pos) {
    this.sector.moveTo(_pos);
}

Rkns.Renderer.EdgeRemoveButton.prototype.show = function() {
    this.sector.show();
}

Rkns.Renderer.EdgeRemoveButton.prototype.hide = function() {
    this.sector.hide();
}

Rkns.Renderer.EdgeRemoveButton.prototype.select = function() {
    this.sector.select();
}

Rkns.Renderer.EdgeRemoveButton.prototype.unselect = function(_newTarget) {
    this.sector.unselect();
    if (!_newTarget || (_newTarget !== this.edge_representation && _newTarget.edge_representation !== this.edge_representation)) {
        this.edge_representation.unselect();
    }
}

Rkns.Renderer.EdgeRemoveButton.prototype.mouseup = function() {
    this.renderer.removeRepresentationsOfType("editor");
    if (confirm(this.renderer.renkan.translate('Do you really wish to remove edge ') + '"' + this.edge_representation.model.get("title") + '"?')) {
        this.project.removeEdge(this.edge_representation.model);
    }
}

Rkns.Renderer.EdgeRemoveButton.prototype.destroy = function() {
    this.sector.destroy();
}

/* */

Rkns.Renderer.MiniFrame = Rkns.Utils.inherit(Rkns.Renderer._BaseRepresentation);

Rkns.Renderer.MiniFrame.prototype.paperShift = function(_delta) {
	this.renderer.offset = this.renderer.offset.subtract(_delta.divide(this.renderer.minimap.scale).multiply(this.renderer.scale));
    this.renderer.resetCoords();
    this.renderer.redraw();
}

Rkns.Renderer.MiniFrame.prototype.mouseup = function(_delta) {
	this.renderer.click_target = null;
    this.renderer.is_dragging = false;
}

/* */

Rkns.Renderer.Scene = function(_renkan) {
    this.renkan = _renkan;
    this.$ = Rkns.$(".Rk-Render");
    this.representations = [];
    this.$.html(this.template(_renkan));
    this.canvas_$ = this.$.find(".Rk-Canvas");
    this.editor_$ = this.$.find(".Rk-Editor");
    this.notif_$ = this.$.find(".Rk-Notifications");
    paper.setup(this.canvas_$[0]);
    this.scale = 1;
    this.offset = paper.view.center;
    this.totalScroll = 0;
    this.click_target = null;
    this.selected_target = null;
    this.edge_layer = new paper.Layer();
    this.node_layer = new paper.Layer();
    this.buttons_layer = new paper.Layer();
    
    this.minimap = {
    	background_layer: new paper.Layer(),
    	node_layer: new paper.Layer(),
    	node_group: new paper.Group(),
    	size: new paper.Size( Rkns.Renderer._MINIMAP_WIDTH, Rkns.Renderer._MINIMAP_HEIGHT )
    }
    
    this.minimap.background_layer.activate();
    this.minimap.topleft = paper.view.bounds.bottomRight.subtract(this.minimap.size);
    this.minimap.rectangle = new paper.Path.Rectangle(this.minimap.topleft.subtract([2,2]), this.minimap.size.add([4,4]));
    this.minimap.rectangle.fillColor = '#ffffff';
    this.minimap.rectangle.strokeColor = '#cccccc';
    this.minimap.rectangle.strokeWidth = 4;
    this.minimap.offset = new paper.Point(this.minimap.size.divide(2));
    this.minimap.scale = .1;
    
    this.node_layer.activate();
    this.minimap.cliprectangle = new paper.Path.Rectangle(this.minimap.topleft, this.minimap.size);
    this.minimap.node_group.addChild(this.minimap.cliprectangle);
    this.minimap.node_group.clipped = true;
    this.minimap.miniframe = new paper.Path.Rectangle(this.minimap.topleft, this.minimap.size);
    this.minimap.node_group.addChild(this.minimap.miniframe);
    this.minimap.miniframe.fillColor = '#f0f0ff';
    this.minimap.miniframe.strokeColor = '#8080ff';
    this.minimap.miniframe.strokeWidth = 2;
    this.minimap.miniframe.__representation = new Rkns.Renderer.MiniFrame(this, null);
    
    this.bundles = [];
    this.click_mode = false;
    var _tool = new paper.Tool(),
        _this = this,
        _allowScroll = true;
    
    _tool.minDistance = Rkns.Renderer._MIN_DRAG_DISTANCE;
    _tool.onMouseMove = function(_event) {
        _this.onMouseMove(_event);
    }
    _tool.onMouseDown = function(_event) {
        _this.onMouseDown(_event);
    }
    _tool.onMouseDrag = function(_event) {
        _this.onMouseDrag(_event);
    }
    this.canvas_$.mouseup(function(_event) {
        _this.onMouseUp(_event);
    });
    this.canvas_$.mousewheel(function(_event, _delta) {
        if (_allowScroll) {
        	_this.onScroll(_event, _delta);
        }
    });
    this.canvas_$.dblclick(function(_event) {
        _this.onDoubleClick(_event);
    });
    this.canvas_$.on("dragover", function(_event) {
    	_event.stopPropagation();
    	_event.preventDefault();
    });
    this.canvas_$.on("dragenter", function(_e) {
    	_allowScroll = false;
    });
    this.canvas_$.on("dragleave", function(_e) {
    	_allowScroll = true;
    });
    this.canvas_$.on("drop", function(_event) {
    	_event.stopPropagation();
    	_event.preventDefault();
    	_allowScroll = true;
    	if (_this.renkan.read_only) {
    		return;
    	}
    	var res = {}
    	Rkns._(_event.originalEvent.dataTransfer.types).each(function(t) {
    		return res[t] = _event.originalEvent.dataTransfer.getData(t);
    	});
    	var newNode = {};
    	switch(res["text/x-iri-specific-site"]) {
    		case "twitter":
    			var snippet = Rkns.$('<div>').html(res["text/x-iri-selected-html"]),
    				tweetdiv = snippet.find(".tweet")
    			newNode.title = _renkan.translate("Tweet by ") + tweetdiv.attr("data-name");
    			newNode.uri = "http://twitter.com/" + tweetdiv.attr("data-screen-name") + "/status/" + tweetdiv.attr("data-tweet-id");
    			newNode.image = tweetdiv.find(".avatar").attr("src");
    			newNode.description = tweetdiv.find(".js-tweet-text:first").text();
    		break;
    		case "google":
    			var snippet = Rkns.$('<div>').html(res["text/x-iri-selected-html"]);
    			newNode.title = snippet.find("h3:first").text().trim();
    			newNode.uri = snippet.find("h3 a").attr("href");
    			newNode.description = snippet.find(".st:first").text().trim();
    		break;
    		case undefined:
	    	default:
		    	if (res["text/x-iri-source-uri"]) {
		    		newNode.uri = res["text/x-iri-source-uri"];
		    	}
		    	if (res["text/plain"] || res["text/x-iri-selected-text"]) {
		    		newNode.description = (res["text/plain"] || res["text/x-iri-selected-text"]).replace(/[\s\n]+/gm,' ').trim();
		    	}
		    	if (res["text/html"] || res["text/x-iri-selected-html"]) {
		    		var snippet = Rkns.$('<div>').html(res["text/html"] || res["text/x-iri-selected-html"]);
		    		newNode.image = snippet.find("img").attr("src") || '';
		    		newNode.uri = snippet.find("a").attr("href") || newNode.uri;
		    		newNode.title = snippet.find("[title]").attr("title");
		    		newNode.description = snippet.text().replace(/[\s\n]+/gm,' ').trim();
		    	}
		    	if (res["text/uri-list"]) {
		    		newNode.uri = res["text/uri-list"];
		    	}
		    	if (res["text/x-moz-url"] && !newNode.title) {
		    		newNode.title = (res["text/x-moz-url"].split("\n")[1] || "").trim();
		    		if (newNode.title === newNode.uri) {
		    			newNode.title = false;
		    		}
		    	}
		    	if (res["text/x-iri-source-title"] && !newNode.title) {
		    		newNode.title = res["text/x-iri-source-title"];
		    	}
    	}
    	var fields = ["title", "description", "uri", "image"];
    	for (var i = 0; i < fields.length; i++) {
    		var f = fields[i];
    		if (res["text/x-iri-" + f]) {
    			newNode[f] = res["text/x-iri-" + f];
    		}
    	}
    	if (newNode.title || newNode.description || newNode.uri) {
    		var _off = _this.canvas_$.offset(),
            _point = new paper.Point([
                _event.originalEvent.pageX - _off.left,
                _event.originalEvent.pageY - _off.top
            ]),
            _coords = _this.toModelCoords(_point),
            _data = {
                id: Rkns.Utils.getUID('node'),
                created_by: _this.renkan.current_user,
                uri: newNode.uri || "",
                title: newNode.title || _this.renkan.translate("Dragged resource"),
                description: newNode.description || "",
                image: newNode.image || "",
                color: newNode.color || undefined,
                position: {
                    x: _coords.x,
                    y: _coords.y
                }
            };
        	var _node = _this.renkan.project.addNode(_data);
            _this.getRepresentationByModel(_node).openEditor();
    	}
    })
    this.editor_$.find(".Rk-ZoomOut").click(function() {
        _this.offset = new paper.Point([
            _this.canvas_$.width(),
            _this.canvas_$.height()
        ]).multiply( .5 * ( 1 - Math.SQRT1_2 ) ).add(_this.offset.multiply( Math.SQRT1_2 ));
        _this.setScale( _this.scale * Math.SQRT1_2 );
        _this.redraw();
    });
    this.editor_$.find(".Rk-ZoomIn").click(function() {
        _this.offset = new paper.Point([
            _this.canvas_$.width(),
            _this.canvas_$.height()
        ]).multiply( .5 * ( 1 - Math.SQRT2 ) ).add(_this.offset.multiply( Math.SQRT2 ));
        _this.setScale( _this.scale * Math.SQRT2 );
        _this.redraw();
    });
    this.$.find(".Rk-CurrentUser").mouseenter(
        function() { _this.$.find(".Rk-UserList").slideDown() }
    );
    this.$.find(".Rk-Users").mouseleave(
        function() { _this.$.find(".Rk-UserList").slideUp(); }
    );
    this.$.find(".Rk-FullScreen-Button").click(function() {
        var _isFull = document.fullScreen || document.mozFullScreen || document.webkitIsFullScreen,
            _el = _this.renkan.$[0],
            _requestMethods = ["requestFullScreen","mozRequestFullScreen","webkitRequestFullScreen"],
            _cancelMethods = ["cancelFullScreen","mozCancelFullScreen","webkitCancelFullScreen"];
        if (_isFull) {
            for (var i = 0; i < _cancelMethods.length; i++) {
                if (typeof document[_cancelMethods[i]] === "function") {
                    document[_cancelMethods[i]]();
                    break;
                }
            }
        } else {
            for (var i = 0; i < _requestMethods.length; i++) {
                if (typeof _el[_requestMethods[i]] === "function") {
                    _el[_requestMethods[i]]();
                    break;
                }
            }
        }
    });
    this.$.find(".Rk-AddNode-Button").click(function() {
        if (_this.click_mode === Rkns.Renderer._CLICKMODE_ADDNODE) {
            _this.click_mode = false;
            _this.notif_$.hide();
        } else {
            _this.click_mode = Rkns.Renderer._CLICKMODE_ADDNODE;
            _this.notif_$.text(_renkan.translate("Click on the background canvas to add a node")).fadeIn();
        }
    });
    this.$.find(".Rk-AddEdge-Button").click(function() {
        if (_this.click_mode === Rkns.Renderer._CLICKMODE_STARTEDGE || _this.click_mode === Rkns.Renderer._CLICKMODE_ENDEDGE) {
            _this.click_mode = false;
            _this.notif_$.hide();
        } else {
            _this.click_mode = Rkns.Renderer._CLICKMODE_STARTEDGE;
            _this.notif_$.text(_renkan.translate("Click on a first node to start the edge")).fadeIn();
        }
    });
    this.$.find(".Rk-Bookmarklet-Button")
	    .attr("href","javascript:" + Rkns.Renderer._BOOKMARKLET_CODE(_renkan))
		.click(function(){
	    	_this.notif_$
	    		.text(_renkan.translate("Drag this button to your bookmark bar. When on a third-party website, click it to enable drag-and-drop from the website to Renkan."))
	    		.fadeIn()
	    		.delay(5000)
	    		.fadeOut();
			return false;
	    });
    this.$.find(".Rk-TopBar-Button").mouseover(function() {
        Rkns.$(this).find(".Rk-TopBar-Tooltip").show();
    }).mouseout(function() {
        Rkns.$(this).find(".Rk-TopBar-Tooltip").hide();
    });
    this.$.find(".Rk-Fold-Bins").click(function() {
    	var bins = _renkan.$.find(".Rk-Bins");
    	if (bins.offset().left < 0) {
    		bins.animate({left: 0},250);
    		_this.$.animate({left: 300},250,function() {
    			var w = _this.$.width();
    			paper.view.viewSize = new paper.Size([w, _this.canvas_$.height()]);
    		});
    		$(this).html("&laquo;");
    	} else {
    		bins.animate({left: -300},250);
    		_this.$.animate({left: 0},250,function() {
    			var w = _this.$.width();
    			paper.view.viewSize = new paper.Size([w, _this.canvas_$.height()]);
    		});
    		$(this).html("&raquo;");
    	}
    });
    
    paper.view.onResize = function(_event) {
    	_this.offset = _this.offset.add(_event.delta.divide(2));
        _this.resetCoords();
        _this.minimap.topleft = paper.view.bounds.bottomRight.subtract(_this.minimap.size)
        _this.minimap.rectangle.fitBounds(_this.minimap.topleft.subtract([2,2]), _this.minimap.size.add([4,4]));
        _this.minimap.cliprectangle.fitBounds(_this.minimap.topleft, _this.minimap.size);
        _this.redraw();
    }
    
    var _thRedraw = Rkns._.throttle(function() {
        _this.redraw();
    },50);
    
    this.addRepresentations("Node", this.renkan.project.get("nodes"));
    this.addRepresentations("Edge", this.renkan.project.get("edges"));
    this.renkan.project.on("change:title", function() {
        _this.$.find(".Rk-PadTitle").val(_renkan.project.get("title"));
    });
    
    this.$.find(".Rk-PadTitle").on("keyup input paste", function() {
        _renkan.project.set({"title": $(this).val()});
    })
    
    this.renkan.project.get("users").each(function(_user) {
        _this.addUser(_user);
    });
    
    this.renkan.project.on("add:users", function(_user) {
        _this.addUser(_user);
    });
    this.renkan.project.on("add:nodes", function(_node) {
        _this.addRepresentation("Node", _node);
        _thRedraw();
    });
    this.renkan.project.on("add:edges", function(_edge) {
        _this.addRepresentation("Edge", _edge);
        _thRedraw();
    });
    this.renkan.project.on("change:title", function(_model, _title) {
        var el = $(".Rk-PadTitle");
        if (el.is("input")) {
            if (el.val() !== _title) {
                el.val(_title);
            }
        } else {
            el.text(_title);
        }
    });
    
    this.redraw();
    window.setInterval(function() {
    	_this.rescaleMinimap()
    }, 2000);
}

Rkns.Renderer.Scene.prototype.template = Rkns._.template(
    '<div class="Rk-TopBar"><% if (read_only) { %><h2 class="Rk-PadTitle"><%- project.get("title") || translate("Untitled project")%></h2>'
    + '<% } else { %><input type="text" class="Rk-PadTitle" value="<%- project.get("title") || "" %>" placeholder="<%-translate("Untitled project")%>" /><% } %>'
    + '<div class="Rk-Users"><div class="Rk-CurrentUser"><span class="Rk-CurrentUser-Color"></span><span class="Rk-CurrentUser-Name">&lt;unknown user&gt;</span></div><ul class="Rk-UserList"></ul></div>'
    + '<div class="Rk-TopBar-Separator"></div><div class="Rk-TopBar-Button Rk-FullScreen-Button"><div class="Rk-TopBar-Tooltip"><div class="Rk-TopBar-Tooltip-Tip"></div><div class="Rk-TopBar-Tooltip-Contents"><%-translate("Full Screen")%></div></div></div>'
    + '<% if (!read_only) { %>'
    + '<div class="Rk-TopBar-Separator"></div><div class="Rk-TopBar-Button Rk-AddNode-Button"><div class="Rk-TopBar-Tooltip"><div class="Rk-TopBar-Tooltip-Tip"></div><div class="Rk-TopBar-Tooltip-Contents"><%-translate("Add Node")%></div></div></div>'
    + '<div class="Rk-TopBar-Separator"></div><div class="Rk-TopBar-Button Rk-AddEdge-Button"><div class="Rk-TopBar-Tooltip"><div class="Rk-TopBar-Tooltip-Tip"></div><div class="Rk-TopBar-Tooltip-Contents"><%-translate("Add Edge")%></div></div></div>'
    + '<div class="Rk-TopBar-Separator"></div><div class="Rk-TopBar-Button Rk-Save-Button"><div class="Rk-TopBar-Tooltip"><div class="Rk-TopBar-Tooltip-Tip"></div><div class="Rk-TopBar-Tooltip-Contents"><%-translate("Archive Project")%></div></div></div>'
    + '<div class="Rk-TopBar-Separator"></div><a class="Rk-TopBar-Button Rk-Bookmarklet-Button" href="#"><div class="Rk-TopBar-Tooltip"><div class="Rk-TopBar-Tooltip-Tip"></div><div class="Rk-TopBar-Tooltip-Contents">'
    + '<%-translate("Renkan \'Drag-to-Add\' bookmarklet")%></div></div></a>'
    + '<div class="Rk-TopBar-Separator"></div></div>'
    + '<% } %>'
    + '<canvas class="Rk-Canvas" resize></canvas><div class="Rk-Editor"><div class="Rk-Notifications"></div>'
    + '<% if (show_bins) { %><div class="Rk-Fold-Bins">&laquo;</div><% } %>'
    + '<div class="Rk-ZoomButtons"><div class="Rk-ZoomIn" title="<%-translate("Zoom In")%>"></div><div class="Rk-ZoomOut" title="<%-translate("Zoom Out")%>"></div></div>'
    + '</div>'
);

Rkns.Renderer.Scene.prototype.addToBundles = function(_edgeRepr) {
    var _bundle = Rkns._(this.bundles).find(function(_bundle) {
        return ( 
            ( _bundle.from === _edgeRepr.from_representation && _bundle.to === _edgeRepr.to_representation )
            || ( _bundle.from === _edgeRepr.to_representation && _bundle.to === _edgeRepr.from_representation )
        );
    });
    if (typeof _bundle !== "undefined") {
        _bundle.edges.push(_edgeRepr)
    } else {
        _bundle = {
            from: _edgeRepr.from_representation,
            to: _edgeRepr.to_representation,
            edges: [ _edgeRepr ],
            getPosition: function(_er) {
                var _dir = (_er.from_representation === this.from) ? 1 : -1;
                return _dir * ( Rkns._(this.edges).indexOf(_er) - (this.edges.length - 1) / 2 );
            }
        }
        this.bundles.push(_bundle);
    }
    return _bundle;
}

Rkns.Renderer.Scene.prototype.setScale = function(_newScale) {
    this.scale = _newScale;
    this.resetCoords();
    this.redraw();
}

Rkns.Renderer.Scene.prototype.redrawMiniframe = function() {
	var topleft = this.toMinimapCoords(this.toModelCoords(new paper.Point([0,0]))),
		bottomright = this.toMinimapCoords(this.toModelCoords(paper.view.bounds.bottomRight));
	this.minimap.miniframe.fitBounds(topleft, bottomright);
}

Rkns.Renderer.Scene.prototype.rescaleMinimap = function() {
    var nodes = this.renkan.project.get("nodes")
    if (nodes.length > 1) {
        var _xx = nodes.map(function(_node) { return _node.get("position").x }),
            _yy = nodes.map(function(_node) { return _node.get("position").y }),
            _minx = Math.min.apply(Math, _xx),
            _miny = Math.min.apply(Math, _yy),
            _maxx = Math.max.apply(Math, _xx),
            _maxy = Math.max.apply(Math, _yy);
        var _scale = Math.min(this.scale * .8 * Rkns.Renderer._MINIMAP_WIDTH / paper.view.bounds.width, this.scale * .8 * Rkns.Renderer._MINIMAP_HEIGHT / paper.view.bounds.height, (Rkns.Renderer._MINIMAP_WIDTH - 2 * Rkns.Renderer._MINIMAP_MARGIN_X) / (_maxx - _minx), (Rkns.Renderer._MINIMAP_HEIGHT - 2 * Rkns.Renderer._MINIMAP_MARGIN_Y) / (_maxy - _miny));
        this.minimap.offset = this.minimap.size.divide(2).subtract(new paper.Point([(_maxx + _minx) / 2, (_maxy + _miny) / 2]).multiply(_scale));
        this.minimap.scale = _scale;
    }
    if (nodes.length === 1) {
    	this.minimap.scale = .1;
        this.minimap.offset = this.minimap.size.divide(2).subtract(new paper.Point([nodes.at(0).get("position").x, nodes.at(0).get("position").y]).multiply(this.minimap.scale));
    }
    this.redraw();
}

Rkns.Renderer.Scene.prototype.resetCoords = function(_point) {
    _(this.representations).each(function(r) {
        r.resetCoords();
    });
}

Rkns.Renderer.Scene.prototype.toPaperCoords = function(_point) {
    return _point.multiply(this.scale).add(this.offset);
}

Rkns.Renderer.Scene.prototype.toMinimapCoords = function(_point) {
    return _point.multiply(this.minimap.scale).add(this.minimap.offset).add(this.minimap.topleft);
}

Rkns.Renderer.Scene.prototype.toModelCoords = function(_point) {
    return _point.subtract(this.offset).divide(this.scale);
}

Rkns.Renderer.Scene.prototype.addRepresentation = function(_type, _model) {
    var _repr = new Rkns.Renderer[_type](this, _model);
    this.representations.push(_repr);
    return _repr;
}

Rkns.Renderer.Scene.prototype.addRepresentations = function(_type, _collection) {
    var _this = this;
    _collection.forEach(function(_model) {
        _this.addRepresentation(_type, _model);
    });
}

Rkns.Renderer.Scene.prototype.userTemplate = Rkns._.template(
    '<li class="Rk-User"><span class="Rk-UserColor" style="background:<%=background%>;"></span><%=name%></li>'
);

Rkns.Renderer.Scene.prototype.addUser = function(_user) {
    if (_user.get("_id") === this.renkan.current_user) {
        this.$.find(".Rk-CurrentUser-Name").text(_user.get("title"));
        this.$.find(".Rk-CurrentUser-Color").css("background", _user.get("color"));
    } else {
        this.$.find(".Rk-UserList").append(
            Rkns.$(
                this.userTemplate({
                    name: _user.get("title"),
                    background: _user.get("color")
                })
            )
        );
    }
}

Rkns.Renderer.Scene.prototype.removeRepresentation = function(_representation) {
    _representation.destroy();
    this.representations = Rkns._(this.representations).reject(
        function(_repr) {
            return _repr == _representation
        }
    );
}

Rkns.Renderer.Scene.prototype.getRepresentationByModel = function(_model) {
    return Rkns._(this.representations).find(function(_repr) {
        return _repr.model === _model;
    });
}

Rkns.Renderer.Scene.prototype.removeRepresentationsOfType = function(_type) {
    var _representations = Rkns._(this.representations).filter(function(_repr) {
            return _repr.type == _type;
        }),
        _this = this;
    Rkns._(_representations).each(function(_repr) {
        _this.removeRepresentation(_repr);
    });
}

Rkns.Renderer.Scene.prototype.highlightModel = function(_model) {
    var _repr = this.getRepresentationByModel(_model);
    if (_repr) {
        _repr.highlight();
    }
}

Rkns.Renderer.Scene.prototype.unhighlightAll = function(_model) {
    Rkns._(this.representations).each(function(_repr) {
        _repr.unhighlight();
    });
}

Rkns.Renderer.Scene.prototype.redraw = function() {
    Rkns._(this.representations).each(function(_representation) {
        _representation.redraw();
    });
    this.redrawMiniframe();
    paper.view.draw();
}

Rkns.Renderer.Scene.prototype.addTempEdge = function(_from, _point) {
    var _tmpEdge = this.addRepresentation("TempEdge",null);
    _tmpEdge.end_pos = _point;
    _tmpEdge.from_representation = _from;
    _tmpEdge.redraw();
    this.click_target = _tmpEdge;
}

Rkns.Renderer.Scene.prototype.findTarget = function(_hitResult) {
    if (_hitResult && typeof _hitResult.item.__representation !== "undefined") {
        var _newTarget = _hitResult.item.__representation;
        if (this.selected_target !== _hitResult.item.__representation) {
            if (this.selected_target) {
                this.selected_target.unselect(_newTarget);
            }
            _newTarget.select(this.selected_target);
            this.selected_target = _newTarget;
        }
    } else {
        if (this.selected_target) {
            this.selected_target.unselect(null);
        }
        this.selected_target = null;
    }
}

Rkns.Renderer.Scene.prototype.paperShift = function(_delta) {
	this.offset = this.offset.add(_delta);
    this.resetCoords();
    this.redraw();
}

Rkns.Renderer.Scene.prototype.onMouseMove = function(_event) {
    var _hitResult = paper.project.hitTest(_event.point);
    if (this.is_dragging) {
        if (this.click_target && typeof this.click_target.paperShift === "function") {
            this.click_target.paperShift(_event.delta);
        } else {
            this.paperShift(_delta);
        }
    } else {
        this.findTarget(_hitResult);
    }
}

Rkns.Renderer.Scene.prototype.onMouseDown = function(_event) {
    if (!this.click_target || this.click_target.type !== "temp-edge") {
        this.removeRepresentationsOfType("editor");
        this.is_dragging = false;
        var _hitResult = paper.project.hitTest(_event.point);
        if (_hitResult && typeof _hitResult.item.__representation !== "undefined") {
            this.click_target = _hitResult.item.__representation;
            if (this.click_target.type === "Node-link-button") {
                this.removeRepresentationsOfType("editor");
                this.addTempEdge(this.click_target.node_representation, _event.point);
            }
        } else {
            this.click_target = null;
            if (this.click_mode === Rkns.Renderer._CLICKMODE_ADDNODE) {
                var _coords = this.toModelCoords(_event.point),
                    _data = {
                        id: Rkns.Utils.getUID('node'),
                        created_by: this.renkan.current_user,
                        position: {
                            x: _coords.x,
                            y: _coords.y
                        }
                    };
                    _node = this.renkan.project.addNode(_data);
                this.getRepresentationByModel(_node).openEditor();
            }
        }
    }
    if (this.click_mode) {
        if (this.click_mode === Rkns.Renderer._CLICKMODE_STARTEDGE && this.click_target && this.click_target.type === "Node") {
            this.removeRepresentationsOfType("editor");
            this.addTempEdge(this.click_target, _event.point);
            this.click_mode = Rkns.Renderer._CLICKMODE_ENDEDGE;
            this.notif_$.fadeOut(function() {
                Rkns.$(this).html(_renkan.translate("Click on a second node to complete the edge")).fadeIn();
            });
        } else {
            this.notif_$.hide();
            this.click_mode = false;
        }
    }
}

Rkns.Renderer.Scene.prototype.onMouseDrag = function(_event) {
    this.is_dragging = true;
    this.onMouseMove(_event);
}

Rkns.Renderer.Scene.prototype.onMouseUp = function(_event) {
    if (this.click_target) {
        var _off = this.canvas_$.offset();
        this.click_target.mouseup(
            {
                point: new paper.Point([
                    _event.pageX - _off.left,
                    _event.pageY - _off.top
                ])
            }
        );
    } else {
        this.click_target = null;
        this.is_dragging = false;
    }
}

Rkns.Renderer.Scene.prototype.onScroll = function(_event, _scrolldelta) {
    this.totalScroll += _scrolldelta;
    if (Math.abs(this.totalScroll) >= 1) {
        var _off = this.canvas_$.offset(),
            _delta = new paper.Point([
                _event.pageX - _off.left,
                _event.pageY - _off.top
            ]).subtract(this.offset).multiply( Math.SQRT2 - 1 );
        if (this.totalScroll > 0) {
            this.offset = this.offset.subtract(_delta);
            this.setScale( this.scale * Math.SQRT2 );
        } else {
            this.offset = this.offset.add(_delta.divide( Math.SQRT2 ));
            this.setScale( this.scale * Math.SQRT1_2);
        }
        this.totalScroll = 0;
        this.redraw();
    }
}

Rkns.Renderer.Scene.prototype.onDoubleClick = function(_event) {
    if (this.renkan.read_only) {
        return;
    }
    var _off = this.canvas_$.offset(),
        _point = new paper.Point([
            _event.pageX - _off.left,
            _event.pageY - _off.top
        ]);
    var _hitResult = paper.project.hitTest(_point);
    if (!_hitResult || typeof _hitResult.item.__representation === "undefined") {
        var _coords = this.toModelCoords(_point),
            _data = {
                id: Rkns.Utils.getUID('node'),
                created_by: this.renkan.current_user,
                position: {
                    x: _coords.x,
                    y: _coords.y
                }
            };
            _node = this.renkan.project.addNode(_data);
            this.getRepresentationByModel(_node).openEditor();
    }
    paper.view.draw();
}
