Array.prototype.in_array = function(needle) {
	for(var i=0; i < this.length; i++) if(this[ i] === needle) return true;
	return false;
}

	var ImagesPositions = Class.create({
		
		LightBox:				null,	// reference to lightbox
		
		domImagesPositions:		null, // layser over image, there markers have to be attachged, and positioned absolutely
		domInfoWindow:			null,	// 
		domImageNav:			null, // reference to lightbox ImageNav div
		
		domNavPersonen: 		null, // hier werden die Personen eines Bildes gelistet
		domNavButton:	 		null, // hier kommt der Button zum verlinken rein
		
		hash:					null,
		positions:				null,
		
		names:					[], // names actually on image, to restrict to use them again to position
		
		linkDims:				[43,42],
		
		initialize: function(LightBox) {
			this.LightBox = LightBox;
			this.domImageNav = $('imageNav');
			this.domImagesPositions = $('imagesPositions');
			this.domNavPersonen 	= $('EventsImagesPersonen');
			this.domNavButton 		= $('EventsImagesButton');
			
			var divButton = Builder.node('div',{'class': 'button'}); //Builder.node('div', {class: 'button'});
			var button = Builder.node('input', {type:'button',value:'Verlinken'});
			divButton.appendChild(button);
			this.domNavButton.appendChild(divButton);
			this.domNavButton.appendChild(Builder.node('br', {'class':'clear'}));
			
			/*if(!__logedin)
			{
				$(button).hide();
				$(divButton).hide();
			}*/
			
			Event.observe(button, 'click', this.createMarker.bind(this));
			
			this.domInfoWindow = Builder.node('div', {
				id: 'infoWindow'
			});
			
			this.domInfoWindow.dontdelete = true;
			this.domImagesPositions.appendChild(this.domInfoWindow);
			
			Element.hide(this.domInfoWindow);
			
			
			Event.observe(this.domInfoWindow, 'mouseover', this.clearTimeout.bind(this));
			Event.observe(this.domInfoWindow, 'mouseout', this.markerMouseOut.bind(this));
			
		},
		setImage: function(image_url) {
			this.hash = this.parseHash(image_url);
			this.loadData();
		},
		parseHash: function(image_url) {
			var img_parts = image_url.split("/");
   			var hash = img_parts[img_parts.length - 1].split(".")[0];
   			return hash;
		},
		loadData: function() {
			if(this.editor)
			{
			this.editor.hide();
			} 
			new Ajax.Request('/events/giveImagePositions/' + this.hash, {
				method: 'get',
				onSuccess: function(transport) {
					this.positions = eval(transport.responseText);
					this.updateImage();
				}.bind(this)
			});
		},
		clearImage: function() {
			var elems = this.domImagesPositions.childElements();
			elems.each(function(elem) {
				if (!elem.dontdelete) {
					this.listenOffElem(elem);
					Element.remove(elem);
				}
			}.bind(this));
			
			this.domNavPersonen.update('');
		},
		updateImage: function() {
			// erstmal loeschen
			this.clearImage();
			
			this.domNavPersonen.update("Verlinkte Personen: ");
			
			var test = test;
			
			this.names = [];
			
			// setze marker und co
			this.positions.each(function(marker, n){
				pos = {
					x: Math.round(marker.x - (this.linkDims[0]/2)),
					y: Math.round(marker.y - (this.linkDims[1]/2))
				};
				var elem = Builder.node('div',{
					style:'position: absolute; left: ' + pos.x + 'px; top: ' + pos.y + 'px;'
				});
				elem.marker = marker;
				this.domImagesPositions.appendChild(elem);
				this.listenOnElem(elem);
				
				// namen unten anzeigen
				this.domNavPersonen.insert(Builder.node('a', {
					href: '/profile/' + marker.user.nickname 
				}, [(n>0?', ':'') + marker.user.nickname]));
				
				// namen dazu
				this.names.push(marker.user.nickname);
			}.bind(this));
		},
		listenOnElem: function(elem) {
			Event.observe(elem, 'click', this.markerClick.bind(this));
			Event.observe(elem, 'mouseover', this.markerMouseOver.bind(this));
			Event.observe(elem, 'mouseout', this.markerMouseOut.bind(this));
		},
		listenOffElem: function(elem) {
			Event.stopObserving(elem, 'click', this.markerClick.bind(this));
			Event.stopObserving(elem, 'mouseover', this.markerMouseOver.bind(this));
			Event.stopObserving(elem, 'mouseout', this.markerMouseOut.bind(this));
		},
		markerClick: function(evt){
			this.clearTimeout();
			if( evt.currentTarget ) {
				elem = evt.currentTarget;
			}
			else {
				elem = evt.target;
			}
			evt.stop();
			this.clearTimeout();
			location.href= '/profile/' + elem.marker.user.nickname + '/';
		},
		markerMouseOut: function(evt) {
			this.timeout = setTimeout(this.closeMarkerInfo.bind(this), 500);
		},
		markerMouseOver: function(evt) {
			this.clearTimeout();
			if( evt.currentTarget ) {
				elem = evt.currentTarget;
			}
			else {
				elem = evt.target;
			}
			evt.stop();
			this.clearTimeout();
			this.showMarkerInfo(elem);
		},
		clearTimeout: function() {
			clearTimeout(this.timeout);
		},
		closeMarkerInfo: function() {
			new Effect.Fade(this.domInfoWindow, { duration: 0.5 });
		},
		showMarkerInfo: function(elem) {			
			var code = Builder.node('div', {}, [
				Builder.node('a', {
					href: '/profile/' + elem.marker.user.nickname + '/'
				}, [
					elem.marker.user.nickname
				]), Builder.node('br'),
				elem.marker.user.age + ' Jahre alt', Builder.node('br'),
				'aus ' + elem.marker.user.city, Builder.node('br'),
				Builder.node('br'),
				'verlinkt von:', Builder.node('br'),
				Builder.node('a', {
					href: '/profile/' + elem.marker.from_user.nickname + '/'
				}, [
					elem.marker.from_user.nickname
				]),
			]);
			this.domInfoWindow.update(code.innerHTML);
			
			pos = {
				x: Math.round(elem.marker.x*1 + (this.linkDims[0]/2) + 4),
				y: Math.round(elem.marker.y*1 - (this.linkDims[1]/2))
			};
			
			this.domInfoWindow.setStyle({
				position: 'absolute',
				left: pos.x + 'px',
				top: pos.y + 'px',
				zIndex: 12
			});
			
			new Effect.Appear(this.domInfoWindow, { duration: 0.5 });
		},
		hide: function() {
			this.clearImage();
			Element.hide(this.domImagesPositions);
		},
		show: function() {
			Element.show(this.domImagesPositions);
		},
		// called by "verlinken" button
		createMarker: function() {

			pos = {
				x: 200,
				y: 200
			};
			this.draggable = Builder.node('div', {
				style: ('position: absolute; left: ' + (pos.x*1) + 'px; top: ' + (pos.y*1) + 'px;'),
				className:	'edit',
				id:		'EventsImagesPositionsDraggable'
			},[]);
			this.domImagesPositions.appendChild(this.draggable);
			
			var x = new Draggable('EventsImagesPositionsDraggable', {
				onEnd: this.onMarkerEndDrag.bind(this)
			});
			
			// editor
			this.editor = Builder.node('div',{
				style:'position: absolute; left: ' + (pos.x*1 + this.linkDims[0]*1 + 5) + 'px; top: ' + (pos.y*1) + 'px;',
				id:'PositionsEditor' }, [
				Builder.node('input', {type:'text',className:'text'}),
				Builder.node('select', {name:'friends',size:6,className:'friends'}),
				Builder.node('input', {type:'button',value:'OK',className:'button_ok'}),
				Builder.node('input', {type:'button',value:'Abbrechen',className:'button_cancel'})
			]);
			this.domImagesPositions.appendChild(this.editor);
			
			var textfield = $$('div#PositionsEditor input.text')[0];
			Event.observe(textfield, 'keyup', this.editorSetFriends.bind(this));
			
			var button_ok = $$('div#PositionsEditor input.button_ok')[0];
			Event.observe(button_ok, 'click', this.editorSavePosition.bind(this));
			
			var button_cancel = $$('div#PositionsEditor input.button_cancel')[0];
			Event.observe(button_cancel, 'click', this.loadData.bind(this));
			
			// load friends the user has
			new Ajax.Request('/events/giveUserFriends/' + Math.random(), {
				method: 'get',
				onSuccess: function(transport) {
					this.friends = transport.responseText.evalJSON();
					if(this.friends.error && this.friends.error == 'notlogedin'){
						$(this.editor).innerHTML = '<p style="background-color:#FFF; margin-right:10px;padding:5px">Zum verlinken <a href="/community">logge</a> dich bitte bei Vplusfriends.de ein.</p>';
						$(this.draggable).remove();
					}
					else{this.editorSetFriends();}
				}.bind(this)
			});
		},
		onMarkerEndDrag: function(draggable) {
			var pos = this.draggable.positionedOffset();
			this.editor.setStyle({
				left: pos[0] + this.linkDims[0]*1 + 5 + 'px',
				top: pos[1] + 'px'
			});
		},
		editorSetFriends: function(friends) {
			var select = $$('div#PositionsEditor select.friends')[0];
			select.update('');
			var restrict = $$('div#PositionsEditor input.text')[0].getValue();			
			for (i = 0; i < this.friends.length; i++) {
				if (this.friends[i].indexOf(restrict) > -1 && !this.names.in_array(this.friends[i])) {
					elem = Builder.node('option', {value:this.friends[i]}, [this.friends[i]]);
					select.appendChild(elem);
				}
			}
		},
		// speichern wa?
		editorSavePosition: function() {
			var name = $$('div#PositionsEditor select.friends')[0].getValue();
			if (!name) {
				alert('Bitte wähle erst einen Deiner Freunde aus');
				return false;
			}
			
			var postmp =this.draggable.positionedOffset();
			var pos = {
				x: Math.round(postmp[0]*1 + (this.linkDims[0]/2)),
				y: Math.round(postmp[1]*1 + (this.linkDims[1]/2))
			};
			
			// save entry
			new Ajax.Request('/events/savePosition/', {
				method: 'post',
				parameters: {
					username: name,
					x: pos.x,
					y: pos.y,
					hash: this.hash
				},
				onSuccess: function(transport) {
					
					//console.log(transport.responseText);
					
				}.bind(this)
			});
			this.loadData();
		}
	});