var AvatarFragment = Class.create({

	initialize: function(editor, element_id, image_path) {
		this.id = element_id;
		this.editor = editor;
		this.image_path = image_path;
		this.y = null;
		this.x = null;
		this.element_id = element_id;
		this.active = false;
		this.img = new Element('img', {id: element_id, name: element_id});
		this.img.setStyle( {
			position: 'absolute',
			visibility: 'hidden',
			top: '0px',
			left: '0px'
		} );

		this.img.onload = this.setup.bindAsEventListener(this);
		this.controls = new AvatarFragmentControls(this);
		this.img.src = image_path;
	},

	serialize: function() {
		var base = "fragments[#{id}]".interpolate({ id: this.id });
		// HACK
		var ee = this.editor.editor_element;

		return "#{b}[x]=#{x}&#{b}[y]=#{y}&#{b}[w]=#{w}&#{b}[h]=#{h}&#{b}[z]=#{z}&#{b}[path]=#{path}".interpolate({
			b: base,
			x: this.x - ee.offsetLeft,
			y: this.y - ee.offsetTop,
			w: this.getWidth(),
			h: this.getHeight(),
			z: this.getZIndex(),
			path: this.image_path
		});
	},

	destroy: function() {
		this.controls.destroy();
		this.img.remove();
	},

	setup: function(ev) {
		// HACK

		if(this.x == null || this.y == null) {
			var ee = this.editor.editor_element;

			this.setPosition(
				ee.offsetLeft + (this.editor.getWidth() - this.getWidth())/2,
				ee.offsetTop + (this.editor.getHeight() - this.getHeight())/2
			);
		}
		this.img.onload = null;
		this.img.pngFix();
		this.img.style.visibility = 'visible';
	},

	deleteClick: function(ev) {
		this.editor.removeFragment(this);
	},

	appendTo: function(target) {
		this.parent = target;
		target.appendChild(this.img);
		target.appendChild(this.controls.getContainer());
	},

	hideControls: function() {
		this.controls.hide();
	},

	showControls: function() {
		this.controls.show();
	},

	offsetPosition: function(dx, dy, dw, dh) {
		var x = this.getX() + dx;
		var y = this.getY() + dy;
		var w = this.getWidth() + dw;
		var h = this.getHeight() + dh;
		this.setPosition(x,y,w,h);
	},

	setPosition: function(x, y, w, h) {
		this.x = x;
		this.y = y;
		this.img.setStyle({left: x+'px', top: y+'px'});
		//Log({left: x+'px', top: y+'px'});
		if (w && h) {
			this.img.setStyle({width: w+'px', height: h+'px'});
		}
		this.controls.syncPosition();

		//HACK
		this.editor.was_changed = true;
	},

	bringToTop: function() {
		this.img.style.zIndex = this.editor.nextIndex();
		this.controls.syncPosition();
	},

	getX: function() {
		return this.x;
	},

	getZIndex: function(){
		return this.img.style.zIndex
	},
	
	getY: function() {
		return this.y;
	},

	getHeight: function() {
		return this.img.height;
	},

	getWidth: function() {
		return this.img.width;
	},

	getZIndex: function() {
		return this.img.style.zIndex;
	},

	activate: function() {
		if(this.active) return;
		this.active = true;
		this.controls.activate();
	},

	deactivate: function() {
		if(!this.active) return;
		this.active = false;
		this.controls.deactivate();
	}

});
