
if( typeof( rit ) == 'undefined' )
	var rit = {};

// image to trail the mouse
// active spots above the image
// image maps?

jQuery.fn.ImageMarker = function()
{
	this.each( function( i,o )
	{  
		new rit.ImageMarker( o );
	} );
}


rit.ImageMarker = function( image )
{
	var that = this,
		$image = jQuery( image ),
		mask = jQuery( '<div class="ImageMarkerSelector">' ),// jQuery.create( 'div', {className:'ImageMarkerSelector'} ),
		selection, 
		$editButton;
	
	mask.insertAfter( $image ).hide();
	
	var createMarker = function( x, y, id, name, url, vcard )
	{
		// add Marker
		var marker = jQuery('<div id="ImageMarkerPoint_'+ id +'" class="ImageMarkerPoint" style="top:'+ y +'px; left:'+ x +'px;"></div>').appendTo( $image.parent() );
		var vcard = jQuery( vcard ).appendTo( marker );
		
	
		if( x > $image.width() / 2 )
		{
			//console.log( 'right!' );
			marker.addClass( 'ImageMarkerPointRight' );			
		}
		
		// add Name
		jQuery( 'a', jQuery( '<li><a href="'+ url +'" rel="ImageMarkerPoint_'+ id +'"></a></li>' ).insertBefore( $editButton.parent() ).bind( 'mouseover', function(e){
			marker.addClass( 'ImageMarkerPointHover' );
		} ).bind( 'mouseout', function(e){
			marker.removeClass( 'ImageMarkerPointHover' );
		} ) ).text( name );

	};
	var createSelected = function( x, y )
	{
		var ds = jQuery( '<div class="ImageMarkerSelected"></div>' ).appendTo( $image.parent() );
		var $selection = jQuery( '<form></form>' ).appendTo( ds );

		var $input = jQuery( jQuery( '<div class="ImageMarkerInput">' ) ).appendTo( $selection )
			.bind( 'mouseenter', hideSelector ).bind( 'mouseleave', showSelector );
		

		jQuery( '<p>Wer ist auf der Markierung zu sehen?</p>' ).appendTo( $input );

		$user = jQuery( '<select name="user">' ).appendTo( jQuery('<p></p>').appendTo($input) );
		if( typeof( RS ) != 'undefined' && typeof( RS.user ) != 'undefined' )
			$user.append( jQuery( '<option value="'+ RS.user.id +'">Ich</option>' ) ); 

		if( typeof( RodocsContacts ) != 'undefined' )
			RodocsContacts.fill( jQuery( '<optgroup label="Meine Kontakte">' ).appendTo( $user ) );
			

		var $buttons = jQuery('<p></p>').appendTo($input);
		jQuery( '<input type="submit" name="submit" value="speichern">' ).appendTo( $buttons );
		jQuery( '<button>abbrechen</button>' ).appendTo( $buttons ).bind( 'click', toggleEditing );

		$selection.bind( 'submit', saveHandler );

		ds.css( 'top', y + 'px' ).css( 'left', x + 'px' );
		
		return ds[0];
	};
	
	var containPosition = function( e )
	{
		var o = $image.offset(),
			x = (e.pageX - o.left), 
			y = (e.pageY - o.top),
			radius = Math.ceil( mask.width() / 2);
		
		// minimum
		x = x < radius ? radius : x;
		y = y < radius ? radius : y;
		
		var w = $image.width(),
			h = $image.height();

		// maximum
		x = x > w - radius ? w - radius : x;
		y = y > h - radius ? h - radius : y;
		
		return { x:x, y:y };
	};
	var mouseListener = function( e )
	{
		var p = containPosition( e );
		mask.css( 'top', p.y + 'px' ).css( 'left', p.x + 'px' );
	};
	var clickListener = function( e )
	{
		// abort if click did not happen on Selector
		if( !jQuery( e.target ).hasClass( 'ImageMarkerSelector' ) && !jQuery(e.target).hasClass( 'ImageMarkerSelected' ) )
			return;
		
		var p = containPosition( e );
	
        if( selection )
        {
			//console.log( 'existing' );
        	selection.style.top = p.y + 'px';
        	selection.style.left = p.x + 'px';
        }
        else
        {
			//console.log( 'new' );
        	selection = createSelected( p.x, p.y );
        }

	};
	var escListener = function( e )
	{
		if( e.which == 27 )
		{
			toggleEditing();
		}
	};
	
	var saveHandler = function( e )
	{
		e.stopPropagation();
		e.preventDefault();
		
		var $user = jQuery( 'select', jQuery(this) );
		
		
		// TODO: this is where rodocs should be called via ajax
		// parseInt( selection.style.left ), 
		// parseInt( selection.style.top ),
		// $user.val()
		var xhr, 
			url = jQuery('a[rel=ImageMarkerTarget]').attr('href') || location.pathname;
		url += '/marker/neu?format=json'
				+'&benutzer='+ $user.val()
				+'&left='+ parseInt( selection.style.left ) 
				+'&top=' + parseInt( selection.style.top );
			
		xhr = jQuery.getJSON(
			url,
			function( data )
			{
				// show error Bubble
				// terminate interval if session transparently died
				if( xhr.status != 200 )
				{
					if( typeof(RodocsBubble) != 'undefined'  )
						RodocsBubbles.ajaxError( xhr );
					
					return;
				}
				
				if( data.error )
				{
					var d = new DialogBox( 'Fehler', jQuery( '<div class="ImageMarkerDialog error">' ).html( data.error )[0] );
					d.box().type( AnyBox.MODAL ).visualizer( AnyBox.fadeVisualizer ).show();
					return;
				}
				
				// create marker if response successful, otherwise show error
				createMarker( 
					data.left, 
					data.top, 
					data.id,  //id, 
					data.user.name, //name, 
					data.user.uri,  //url, 
					'<div class="controls">'
						+'<a href="'+ data.uri +'/entfernen"><img src="/styles/default/img/global/loeschen.png" alt="entfernen" title="entfernen"></a> '
						+'<a href="'+ data.uri +'/melden"><img src="/styles/default/img/global/melden.png" alt="melden" title="melden"></a>'
					+'</div>'
					+'<div class="vcard">'
						+'<span class="avatar ' + ( data.user.online ? 'online' : 'offline' ) + '"><a href="' + data.user.uri + '" class="user"><img style="width: 80px; height: 80px;" src="' + data.user.avatar.small + '" alt=""></a></span> '
						+'<h4><a href="' + data.user.uri + '" class="user" title="Zum Profil von ' + data.user.name + '">' + data.user.name + '</a></h4> '
						+'<p>'+ (data.user.gender == 'M' ? 'männlich' : 'weiblich') +', '+ data.user.age +' Jahre</p> '
						+'<p>aus '+ data.user.location +'</p> '
						+'<p class="activity"><img src="/styles/default/img/activity/small_'+ data.user.activity +'.gif" alt="Aktivitätsanzeige '+ data.user.activity +'/6"></p> '
					+'</div>' );

				var d = new DialogBox( 'Erfolgreich verlinkt!', jQuery( '<div class="ImageMarkerDialog"></div>' ).text( "Benutzer wurde erfolgreich hinzugefügt" )[0] );
				d.box().type( AnyBox.MODAL ).visualizer( AnyBox.fadeVisualizer ).show();
			} 
		);
		

		
		// stop editing
		toggleEditing();

		return false;
	};

	var showSelector = function( e )
	{
		mask.show();
		jQuery( document ).bind( 'mousemove', mouseListener );
		
		if( e )
		{
			e.preventDefault();
			e.stopPropagation();
		}
	};
	var hideSelector = function( e )
	{
		mask.hide();
		jQuery( document ).unbind( 'mousemove', mouseListener );
		
		if( e )
		{
			e.preventDefault();
			e.stopPropagation();
		}
	};
	var toggleEditing = function( e )
	{
		if( $image.parent().hasClass( 'ImageMarkerEditing' ) )
		{
			jQuery( document ).unbind( 'mousemove', mouseListener );
			jQuery( document ).unbind( 'keydown.imageMarkerEscapeListener', escListener );
			$image.parent().unbind( 'click', clickListener ).unbind( 'mouseenter', showSelector ).unbind( 'mouseleave', hideSelector );
			jQuery( 'div.ImageMarkerPoint', $image.parent() ).unbind( 'mouseenter', hideSelector ).unbind( 'mouseleave', showSelector );

			$image.parent().removeClass( 'ImageMarkerEditing' )
			$editButton.text( 'hinzufügen' );
			
			if( selection )
			{
				jQuery(selection).remove();
				selection = null;
			}
			
			hideSelector();
		}
		else
		{
			jQuery( document ).bind( 'mousemove', mouseListener );
			jQuery( document ).bind( 'keydown.imageMarkerEscapeListener', escListener );
			$image.parent().bind( 'click', clickListener ).bind( 'mouseenter', showSelector ).bind( 'mouseleave', hideSelector );
			jQuery( 'div.ImageMarkerPoint', $image.parent() ).bind( 'mouseenter', hideSelector ).bind( 'mouseleave', showSelector );

			$image.parent().addClass( 'ImageMarkerEditing' )
			$editButton.text( 'abbrechen' );
		}
	};

	that.init = function()
	{
		// link Legend-Items to ImageMarkerPoints
		jQuery( 'div.ImageMarkerLegend ul li a', $image.parent().parent() ).each( function( i, o )
		{
			var marker = jQuery( '#' + o.rel );
			
			jQuery(o).parent().bind( 'mouseover', function(e){
				marker.addClass( 'ImageMarkerPointHover' );
			} ).bind( 'mouseout', function(e){
				marker.removeClass( 'ImageMarkerPointHover' );
			} );
			
			marker.bind( 'click', function( e )
			{
				location.href = o.href;
			} );
		} );
		
		
		$editButton = jQuery( 'button', jQuery( '<li class="edit"><button>hinzufügen</button></li>' ).appendTo( jQuery( 'div.ImageMarkerLegend ul', $image.parent().parent() ) )
			.bind( 'click', toggleEditing ) );

	};
	
	that.init();
};

jQuery( function(){ jQuery('img.ImageMarker').ImageMarker(); } );