var AvatarEditor = Class.create({
	initialize: function(element_id) {
		this.editor_element = $(element_id);
		this.fragments = new Array();
		this.z_index = 100;
		this.was_changed = false;

		this.editor_element.onmousemove = this.mousemove.bindAsEventListener(this);
	},

	serialize: function(){
		var result = this.fragments.map(function(i){return i.serialize()}).join('&');
		this.was_changed = false;
		return result;
	},

	addFragment: function(path, no_current) {
		var element_id = 'fragment_' + (this.fragments.size()+1);
		var fragment = new AvatarFragment(this, element_id, path);
		this.fragments.push(fragment);
		fragment.appendTo(this.editor_element);
		if (!no_current) {
			this.setCurrent(fragment);
		}
		this.was_changed = true;
		return fragment;
	},

	initFragment: function(x, y, w, h, path) {
		var fragment = this.addFragment(path, 'no_current');
		var ee = this.editor_element;
		fragment.setPosition(ee.offsetLeft + x, ee.offsetTop + y, w, h);
		fragment.bringToTop();
	},

	removeFragment: function(fragment) {
		this.fragments = this.fragments.reject(function(v, i){ return v.id == fragment.id;} )
		this.was_changed = true;
		fragment.destroy();
	},

	nextIndex: function() {
		this.z_index++;
		return this.z_index;
	},

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

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

	setCurrent: function(fragment) {
		if (this.current_fragment) {
			this.current_fragment.deactivate();
		}
		fragment.bringToTop();
		this.current_fragment = fragment;
		this.current_fragment.activate();
	},

	mousemove: function(ev){
		if (this.current_fragment) {
			// HACK!!
			var current = this.current_fragment.controls;
			if (current.resizing || current.moving) {
				current.mousemove(ev);
			} else {
				this.current_fragment.hideControls();
			}
		}
	}
});
