module('lively.PartsBinMorphs').requires('lively.PartsBin').toRun(function() {

Morph.subclass('lively.Scripting.PartsBin',
'default category', {
	m1: function() {},
});


BoxMorph.subclass('lively.Scripting.PartPinItem',
'settings', {
	defaultExtent: pt(100,100),
},
'initializing', {
	initialize: function($super, partsBinURL, targetName, partItem) {
		$super(pt(0,0).extent(this.defaultExtent));
		this.applyStyle({fill: Color.white, borderColor: Color.black, borderRadius: 6});
		this.partsBinURL = partsBinURL
		this.targetName = targetName;
		this.partItem = partItem;
		this.setupLogo();
		this.beClipMorph();
	},

	setupLogo: function() {
		var logoURL = this.partItem.getLogoURL(),
			logoSVG = new ImageMorph(new Rectangle(0,0,100,100), logoURL.withQuery({time: new Date().getTime()}).toString());
		logoSVG.setExtent(pt(100,100));
		logoSVG.setFill(null);
		logoSVG.ignoreEvents();
		this.addMorph(logoSVG)
		var nameLabel = new TextMorph(new Rectangle(10,10,100,20), this.targetName).beLabel();
		this.addMorph(nameLabel);
	},
},
'naming', {
	makeUpPartName: function() {
		if ($morph(this.targetName)){
			var i = 2
			while($morph(this.targetName + i)) { i++}
			return this.targetName + i;
		} else {
			return this.targetName;
		}
	},
},
'mouse events', {
	handlesMouseDown: function (evt) {return true},

	onMouseMove: function(evt) {
		// do nothing...
		return true
	},

	onMouseDown: function(evt) {
		if (!this.partItem) {
			alert('Cannot load Part because found no PartItem');
			return;
		}

		// FIXME put somewhere else			
		var waitRect = Morph.makeRectangle(this.getExtent().extentAsRectangle());
		waitRect.applyStyle({fill: Color.gray, fillOpacity: 0.6, suppressGrabbing: true})
		this.addMorph(waitRect);
		connect(this.partItem, 'part', waitRect, 'remove');
		connect(this.partItem, 'part', this, 'openLoadedPartsBinItem');
		
		this.partItem.loadPart(true)
		return true
	},
},
'menu', {
	morphMenu: function($super, evt) {
		var menu = $super(evt);
		menu.addItem(["delete item", this.interactiveDeleteOnServer.bind(this)])
		return menu
	},
},
'server interaction', {
	deleteOnServer: function() {
		if (this.partItem) this.partItem.del();
		else alert('Cannot delete')
	},
	interactiveDeleteOnServer: function() {
		this.world().confirm("really delete " + this.targetName + " in PartsBin?", function(answer) {
			if (answer) {
				this.deleteOnServer();
				this.remove();
				alertOK("deleted " + this.targetName + " in " + this.partsBinURL);
			}
		}.bind(this))
	},
},
'loading', {

	openLoadedPartsBinItem: function(partMorph) {
		partMorph.name = this.makeUpPartName();
		WorldMorph.current().firstHand().addMorph(partMorph);
		partMorph.setPosition(pt(0,0));
		partMorph.forceRestartAllActiveScripts();
	},

});

Trait('lively.PartsBin.PartTrait').applyTo(Morph)

}) // end of module