/**
 * @author Andrey Lugovtsov
 */

var taggerPhotoClass = Class.create(taggerBaseClass, {
	init: function() {
		this.createCropper();
		
		this.initTagInputBox();
		
		this.initObjectsAutoCompleter();
		
		// при добавлении тэга закроем кроппер
		this.listenAddTagEvent();

		this.trigger.observe('click', this.onTriggerClick.bindAsEventListener(this));
	},
	
	closeTagInputBox: function($super) {
		$super();
		this.cropper.remove();
		this.createCropper();
	},
	
	listenAddTagEvent: function() {
		this.element.observe('container:add-element', function(e) {
			this.closeTagInputBox();
		}.bind(this));
	},
	
	onTriggerClick: function(e) {
		e.preventDefault();
		
		with (this.cropper) {
			// если кроппер уже был создан и инициализирован
			if (selArea.visible()) {
				return this.closeTagInputBox();
			}
			this.element.fire('element:start-dragging');
			selArea.show();
			var w = calcW(), h = calcH();
			var x1 = this.element.getWidth()/2 - w/2, y1 = this.element.getHeight()/2 - h/2;
			setAreaCoords({'x1': x1, 'y1': y1, 'x2': x1 + w, 'y2': y1 + h}, false, false, null);
			drawArea();
			endCrop();
		}
	}
});

var photoTagListClass = Class.create(tagListClass, {
	initialize: function($super, el, c, options) {
		// контейнер готовых тэгов
		$super(el, c, options);
	},
	
	init: function($super) {
		$super();
		
		this.tagsSquaresAreSuspended = 0;
		this.streamSquaresTarget = this.element.parentNode.parentNode;
		
		// при наведении мышки на фото нужно отобразить рамки всех существующих тэгов
		// причем при дальнейшем попадании в рамку, в ней внизу повляется содержимое (note) тэга
		this.createTagsSquares();
		
		this.element.observe('element:start-dragging', this.suspendTagsSquares.bind(this));
		this.element.observe('element:cropper-move', this.suspendTagsSquares.bind(this));
		this.element.observe('element:cropper-resize', this.suspendTagsSquares.bind(this));
		this.element.observe('element:cropper-end', this.trainTagsSquares.bind(this));
	},
	
	suspendTagsSquares: function() {
		this.layTagsSquares();
		this.hideTagsSquares();
	},
	
	createTagsSquares: function() {
		with (this) {
			this.squares = [];
			options.tagsContainer.select('div.tag-info').each(function(div) {
				this.createInnerTagSquare(div);
			}.bind(this));
			this.elementMouseOverBind = showTagsSquares.bindAsEventListener(this);
			this.elementMouseOutBind = hideTagsSquares.bindAsEventListener(this);
			trainTagsSquares();
			
		}
	},
	
	createInnerTagSquare: function(div) {
		var frameInfo = div.down('.frame-data');
		if (frameInfo) {
			frameInfo = frameInfo.innerHTML.split(',');
			
			this.t = 0;
			
			var s = this.createStreamSquare(frameInfo),
				note = s.down('.tag-note'),
				com = s.down('.tag-comment'),
				d = s.down('.tag-data');
		
			function delayHideBig() {
				clearTimeout(this.t);
				this.t = Effect.BlindUp.delay(0.3, d);
				//window.console.log('спрятал рамку отложил');
			}
			
			function tryShowNote() {
				clearTimeout(this.t);
				if (! d.visible() && Effect.Queue.size() < 1) {
					//d.show();
					new Effect.BlindDown(d);
				}
			}

			var squareDims = s.getDimensions();
			var desc = s.descendants();
			desc.push(s);
			desc.each(function(el) {
				el.observe('mouseout', function(e) {
					if (this.checkRealMouseOut(s.cumulativeOffset(), squareDims, e)) {
						delayHideBig.call(this);
//						window.console.log('mouseout', el)
					}
					//e.stop();
				}.bind(this));
				
				el.observe('mouseover', function(e) {
//					window.console.log('mouseover', el)
					tryShowNote.call(this);
				}.bind(this));
			}.bind(this));
			
			
			// note
			var n = div.down('.tag-note');
			if (n) {
				note.update(n.innerHTML);
			}
			
			// comment
			var n = div.down('.tag-comment');
			if (n) {
				com.update(n.innerHTML);
			}
			
			// finally
			this.squares.push(s);
		}
	},
	
	trainTagsSquares: function() {
		with (this) {
			tagsSquaresAreSuspended = 0;
			streamSquaresTarget.observe('mouseover', elementMouseOverBind);
			streamSquaresTarget.observe('mouseout', elementMouseOutBind);
		}
	},
	
	layTagsSquares: function() {
		with (this) {
			if (tagsSquaresAreSuspended)
				return true;
			tagsSquaresAreSuspended = 1;
			Event.stopObserving(streamSquaresTarget, 'mouseover', elementMouseOverBind);
			Event.stopObserving(streamSquaresTarget, 'mouseout', elementMouseOutBind);
		}
	},
	
	showTagsSquares: function() {
		this.squares.invoke('show');
	},
	
	hideTagsSquares: function(e) {
		if (! e) {
			return this.squares.invoke('hide');
		}
		if (this.checkRealMouseOut(this.cos, this.dim, e)) {
//			window.console.log('hideTagsSquares: ниче не знаю, у меня сработал mouseout')
			this.squares.invoke('hide');
		}
	},
	
	checkRealMouseOut: function(el1cos, el2dim, e) {
		var a = el1cos, d = [a[0] + el2dim.width, a[1] + el2dim.height];
//		window.console.log(a, d, [e.pointerX(), e.pointerY()]);  
		return ((e.pointerX() <=  a[0] || e.pointerX() >= d[0]) || (e.pointerY() <= a[1] || e.pointerY() >= d[1]));
	},
	
	createStreamSquare: function(c) {
		var s = $(this.element.getAttribute('id') + '-sframe').cloneNode(true);
		with (s) {
			hide();
			addClassName(this.options.sqclass);
			setAttribute('id', null);
			setStyle({
				'position': 'absolute',
				'zIndex': 1005,
				'left': parseInt(c[0]) + parseInt(this.cos[0]) + 'px',
				'top': parseInt(c[1]) + parseInt(this.cos[1]) + 'px',
				'width': c[2] - c[0] + 'px',
				'height': c[3] - c[1] + 'px'
			});
		}
		Element.insert(document.body, s);
//		Element.insert(this.element.parentNode, s);
		return s;
	},
	
	addTagEventHandler: function($super, e) {
		$super(e);
		this.createInnerTagSquare($(this.options.tagsContainer).select('div.tag-info').last());
	},
	
	removeTagEventHandler: function($super, e) {
		$super(e);
		this.layTagsSquares();
		this.squares.each(function(el) {el.remove();});
		this.createTagsSquares();
	}
});
