
/**
* (c)opy[2007-2009] rafal.zaczynski@gmail.com :: http://baton.pop.e-wro.pl
* tweaks by rafal.zaczynski@gmail.com
*/



var EWeb = {};




/**
 *
 */
EK_NEW_COMMENT_ID = -1;
EWeb.Photos = {


	_LABEL_COMMENT_EMPTY : 'Enter valid comment before submitting it!',
	_LABEL_DELETE_COMMENT_SUMMARY : 'Comment successfully deleted',
	_LABEL_CLOSE_PREVIEW : '[ CLICK TO CLOSE ]',

	
	
	addComment : function ( formE, event ) {
		//prevent normal submit
		new Event( event ).stop();
		formE = $( formE );
		
		// validate if any comment was entered
		if ( Validation.notEmpty( formE, 'comment', EWeb.Photos._LABEL_COMMENT_EMPTY ) ) {
			formE.ekSend( {
				busyIndicator: formE,
				evalScripts: true,
				onComplete: function( responseValue ) {
					EWeb.Photos._addCommentEntry( EK_NEW_COMMENT_ID, responseValue );
					formE.elements['comment'].value = '';
				}
			});
		}
		
		return false;
	},
	
	_addCommentEntry: function( cId, contents ) {
		var divE = new Element( "div", 
			{ "class" : "comment", "id" : "c_" + cId } );
		divE.setHTML( contents );
		divE.injectTop( 'commentsContainer' );
	},


	deleteComment : function ( formE, event, commentId ) {
		//prevent normal submit
		new Event( event ).stop();
		formE = $( formE );

		formE.ekSend( {
			busyIndicator : formE,
			onComplete: function( responseValue ) {
				$('confirmation').remove(); // force removal of popup
				var commentE = $( "c_" + commentId );
				if ( commentE ) {
					commentE.remove();
					Site.showMessage( EWeb.Photos._LABEL_DELETE_COMMENT_SUMMARY );
				}
			}
		});
		
		return false;
	},
	
	
	displayFull : function ( imgSrc, imgWidth, imgHeight ) {
		var PREV_ID = 'pageHider';
		var PREV_IMG_ID = 'photoPreview';
	
	
		var bodyE = $( document.body );
		bodyE.setStyle( "overflow", "hidden" );
		$( document.body ).getParent().setStyle( "overflow", "hidden" );
		
	
	
		var pp = new Element( "div", {id: PREV_ID} );
		
		var scrollT = window.getScrollTop();
		if ( !window.gecko ) {
			if ( scrollT > 0 ) pp.setStyle( "top", scrollT + "px" );
			else pp.setStyle( "top", "0px" );
		}
		if ( window.ie && !window.ie7 ) {
			pp.setStyle( "height", window.getHeight() + "px" );
		}
	
		pp.inject( document.body );
		
		
		var imgE = new Element( "div", {id: PREV_IMG_ID} );
		if ( !window.gecko ) {
			if ( scrollT > 0 ) imgE.setStyle( "top", scrollT + "px" );
			else imgE.setStyle( "top", "0px" );
		}
		if ( window.ie && !window.ie7 ) {
			imgE.setStyle( "height", window.getHeight() + "px" );
		}
		
		var previewHTML = "<div>" + EWeb.Photos._LABEL_CLOSE_PREVIEW + "</div><img src='" + imgSrc + "'";
		if ( imgWidth > 1200 ) {
			previewHTML += " width='99%' ";
		}
		previewHTML += "/>";
		
		imgE.setHTML( previewHTML );
		imgE.addEvent( 'click', function(){
			$('photoPreview').remove();
			$('pageHider').remove();
	
			var bodyE = $( document.body );
			bodyE.setStyle( "overflow", "auto" );
			$( document.body ).getParent().setStyle( "overflow", "auto" );
		});
		imgE.inject( document.body );
	}
	
};





/**
 *
 */
EWeb.Photos.Tagging = new Class({


	_LABEL_TAG_IMAGE_TOO_SMALL : 'Photo is too small to tag people on it. Upload a bigger photo.',
	_LABEL_TAG_VALIDATE_EMAILS : 'First name, last name and e-mail need to be filled in to invite that person to view the photo',
	_URL_LOAD_LIST : '/photos/tagPerson/loadList.ek;jsessionid=7DE77C203248F95BF6A109E0993D33CC',
	_URL_RELOAD_TAGGED_LIST : '/photos/tagPerson/_loadTaggedPersons.ek;jsessionid=7DE77C203248F95BF6A109E0993D33CC',


	options: {
		spotOffset: { x: 0, y: 0 }
	},
	
	initialize: function( photoId, options ) {
		EWeb.Photos.Tagging._I = this; // singleton instance
		
		this.setOptions( options );
		
		this.photoId = photoId;
		this.imageSize = this.options.imageSize;
		this.canvasSize = $('imgHolder').getSize().size;
		this.spotOffset = this.options.spotOffset;
		this.imageHolderE = $('imgHolder');
		if ( this.options.containerId ) this.containerId = this.options.containerId;
		this._initSpotOffset();
	},
	
	_initSpotOffset: function() {
		if ( !this.spotOffsetNames ) {
			this.spotOffsetNames = {};
			for ( var z in this.spotOffset ) {
				if ( this.spotOffset[ z ] ) {
					if ( $type( this.spotOffset[ z ] ) == 'string' ) {
						this.spotOffsetNames[ z ] = this.spotOffset[ z ];
					}
				}
			}
		}
		for ( var z in this.spotOffsetNames ) {
			this.spotOffset[ z ] = $( this.spotOffsetNames[ z ] ).getSize().size[ z ];
		}
	},
	
	showTagging: function() {
		if ( this.imageSize[0] < 110 || this.imageSize[1] < 110 ) {
			Site.showMessage( this._LABEL_TAG_IMAGE_TOO_SMALL );
			return false;
		}
	
		var ptE = $('personTagger');
		if ( !ptE ) {
			ptE = new Element('div',{'id':'personTagger'});
			ptE.injectTop( $('slideShow') );
		}
		var url = this._URL_LOAD_LIST;
		var photoId = this.photoId;
		new EkAjax( url, {
			update: ptE,
			evalScripts: true,
			busyIndicator : ptE,
			initNewElements : ptE,
			onComplete: function( responseValue ) {
				// show HOWTO message
				//Site.showMessage( 'To tag a person just drag the square spot to the face of person you want to tag and then select the person from guest list.<br/>If the person is not on guest list you can invite him/her to see the photo he/she is on.' );
				//display spot
				EWeb.Photos.Tagging._I._initSpot();
				// copy photo id to inner form
				var fE = EWeb.Photos.Tagging._I._getForm();
				if ( fE ) fE.elements['photoId'].value = photoId;
			}
		}).request();
		return false;
	},
	
	hideTagging: function() {
		var ptE = $('personTagger');
		if ( ptE ) ptE.remove();
		this._killSpot();
		if ( EWeb.Photos.Tagging.SpotDrag._I ) {
			EWeb.Photos.Tagging.SpotDrag._I.detach();
			EWeb.Photos.Tagging.SpotDrag._I = null;
		}
		return false;
	},
	
	
	tagGuest: function( guestId, contactId ) {
		var f = this._getForm();
		f.elements['guestId'].value = guestId;
		f.elements['contactId'].value = contactId;
		this._tagSubmit( f );
	},

	tagContact: function( contactId ) {
		var f = this._getForm();
		f.elements['contactId'].value = contactId;
		this._tagSubmit( f );
	},


	tagInvite: function( submitEvent ) {
		var fE = this._getForm();
		// check if form is visible - if not behave like cancel
		var tF = fE.getElement( 'div.inviteForm' );
		if ( !tF.showed ) {
			this.hideTagging();
		} else {
			var msg = this._LABEL_TAG_VALIDATE_EMAILS;
			// validate fields
			if ( Validation.notEmpty( fE, 'firstName', msg ) && Validation.notEmpty( fE, 'lastName', msg ) 
					&& Validation.notEmpty( fE, 'email', msg ) ) {
				
				if ( submitEvent ) {
					//prevent normal submit
					new Event( submitEvent ).stop();
				}
					
				// and submit if valid
				fE.elements['contactId'].value = 0;
				this._tagSubmit( fE );
			}
		}
		return false;
	},


	confirmTagging: function() {
		var fE = this._getForm();
		fE.elements['confirmation'].value = 'false';
		this._tagSubmit( fE );
	},
	
	
	_tagSubmit: function( fE ) {
		if ( !fE ) fE = this._getForm();
		var ptE = $('personTagger');
		
		if ( fE.elements['confirmation'].value == 'true' ) {

			Popups.reloadContent( 'tagConfirmation', { form4Send : fE });
			Site.showPopupCentered( 'tagConfirmation', true );
		
		} else {
		
			// update the Y position with the scroll of container
			var scroll = this.imageHolderE.getSize().scroll;
			if ( scroll.y.toInt() > 0 ) fE.elements[ 'tagY' ].value = fE.elements[ 'tagY' ].value.toInt() + scroll.y;
			
			if ( this.containerId ) {
				fE.elements[ 'containerId' ].value = this.containerId;
			}
			
			this._recalculateScale( fE );
			
			// reset flags
			EK_TAGGED_PERSONS_COUNT = -1;
			EK_NEW_COMMENT_ID = -1;
			
			var _T = this;
			fE.ekSend( {
				busyIndicator : ptE,
				evalScripts: true,
				onComplete: function( responseValue ) {
					EWeb.Photos.Tagging._I.hideTagging();
					
					if ( EK_NEW_COMMENT_ID > 0 ) {
						EWeb.Photos._addCommentEntry( EK_NEW_COMMENT_ID, responseValue );
						// as well refresh the tagged persons list
						EWeb.Photos.Tagging._I._reloadTaggedPersons();
					} else {
						// refresh tagged person container
						if ( EK_TAGGED_PERSONS_COUNT > 0 ) {
							$('taggedPersons').empty().setHTML( responseValue );
							_T._initSpotOffset();
						}
					}
				}
			});
		}
	},
	
	
	_reloadTaggedPersons: function() {
		var url = this._URL_RELOAD_TAGGED_LIST + "?photoId=" + this.photoId;
		var container = $('taggedPersons');
		var _T = this;
		new EkAjax( url, {
			evalScripts: true,
			busyIndicator : container,
			initNewElements : container,
			onComplete: function( responseValue ) {
				$('taggedPersons').empty().setHTML( responseValue );
				_T._initSpotOffset();
			}
		}).request();
	},
	
	
	toggleTagInvitationForm: function() {
		var formE = this._getForm();
		var tF = formE.getElement( 'div.inviteForm' );
		if ( tF ) {
			if ( !tF.showed ) {
				tF.setStyle( 'height', 'auto' );
				formE.elements['firstName'].focus();
			} else tF.setStyle( 'height', 1 );
			tF.showed = !tF.showed;
		}
		return false;
	},
	
	
	
	confirmUnTaggingMyself: function() {
		var link = $( 'untagMyselfLink' );
		var container = $('taggedPersons');
		if ( link ) {
			var _T = this;
			new EkAjax( link, {
				evalScripts: true,
				busyIndicator : container,
				initNewElements : container,
				onComplete: function( responseValue ) {
					$('taggedPersons').empty().setHTML( responseValue );
					_T._initSpotOffset();
				}
			}).request();
			link.remove();
		}
	},
		
	
	/**
	 * used for mouseover the tagged person name
	 */
	showTag: function( x, y ) {
		if ( EWeb.Photos.Tagging.SpotDrag._I == null ) {
			this._ensureSpot();

			var realImgHeight = this.imageSize[1];
			if ( this.imageSize[0] > this.canvasSize.x ) { // rescale
				var scaleRatio = this.imageSize[0] / this.canvasSize.x;
				x /= scaleRatio;
				y /= scaleRatio;
				
				realImgHeight /= scaleRatio;
			}

			// fix scrolling on container - to have spot always visible
			if ( realImgHeight > this.canvasSize.y ) { // if there is scrolling at all
				var maxScroll = realImgHeight - this.canvasSize.y;
				var centerH = y - this.canvasSize.y / 2
				var sY = Math.max( Math.min( centerH.toInt(), maxScroll.toInt() ), 0 );
				//this.imageHolderE.scrollTo( 0, sY );
				if ( !this.scroller ) this.scroller = new Fx.Scroll( this.imageHolderE );
				this.scroller.stop();
				this.scroller.scrollTo( 0, sY );
				y -= sY;
			}
			
			this._setSpotPos( 	x - this.spotSize.x/2, 
								y - this.spotSize.y/2 );
		}
	},
	
	hideTag: function() {
		if ( EWeb.Photos.Tagging.SpotDrag._I == null ) {
			this._killSpot();
		}
	},
		
	
		
		
	_killSpot: function() {
		if ( this.spot ) {
			this.spot.remove();
			this.spot = null;
		}
	},
		
	_getForm: function() {
		var ptE = $('personTagger');
		if ( ptE ) {
			return ptE.getElement('form');
		}
		return null;
	},
	
	
	_recalculateScale: function( fE ) {
		var x = fE.elements[ 'tagX' ].value.toInt();
		var y = fE.elements[ 'tagY' ].value.toInt();
		var spotX = this.spotSize.x/2;
		var spotY = this.spotSize.y/2;
		if ( this.imageSize[0] > this.canvasSize.x ) { // rescale
			var scaleRatio = this.imageSize[0] / this.canvasSize.x;
			x *= scaleRatio;
			y *= scaleRatio;
			spotX *= scaleRatio;
			spotY *= scaleRatio;
		}
		// now find center of spot
		fE.elements[ 'tagX' ].value = x.toInt() + spotX.toInt();
		fE.elements[ 'tagY' ].value = y.toInt() + spotY.toInt();
	},
	
	
	_ensureSpot: function() {
		var container = $('slideShow');
		var created = false;
		if ( !$defined( this.spot ) ) {
			this.spot = $('spot');
			if ( !this.spot ) {
				this.spot = new Element('div',{'id':'spot'});
				this.spot.setHTML( "<img src='/img/spacer.gif'/>" );
				if ( container ) {
					//this.imageHolderE.scrollTo( 0, 0 );
					this.spot.injectTop( container );
				}
				created = true;
			}
		}
		if ( !$defined( this.spotSize ) ) {
			this.spotSize = this.spot.getSize().size;
		}
		
		return created;
	},
	
	_setSpotPos: function( x, y ) {
		if ( this.spot ) {
			this.spot.setStyle( "margin-left", x.toInt() + this.spotOffset.x );
			this.spot.setStyle( "margin-top", y.toInt() + this.spotOffset.y );
		}
	},
	
	_initSpot: function() {
		var noReset = !this._ensureSpot();
		var sizes = this.imageSize;
		var canvasSize = this.canvasSize;
		
		// init all the dragging
		var sS = this.spotSize;
		var spotOffset = this.spotOffset;
		new EWeb.Photos.Tagging.SpotDrag( this.spot, {
			'noReset' : noReset,
			walls: { x: { 
				pos: 200, 
				call: function( isBefore ) {
					var ptE = $('personTagger');
					if ( ptE ) {
						if ( !ptE.origML ) ptE.origML = ptE.getStyle( 'margin-left' );
						if ( isBefore ) {
							ptE.setStyle( 'margin-left', ptE.origML );
						} else {
							ptE.setStyle( 'margin-left', '10px' );
						}
					}
				}
			}},
			valueSetter: function( nV ) {
				var fE = EWeb.Photos.Tagging._I._getForm();
				if ( fE ) {
					if ( $chk(nV['x']) && fE.elements['tagX'] ) fE.elements[ 'tagX' ].value = nV['x'];
					if ( $chk(nV['y']) && fE.elements['tagY'] ) fE.elements[ 'tagY' ].value = nV['y'];
				}
			},
			offset: spotOffset,
			limit: { 
				'x': [ 0, Math.min( canvasSize.x, sizes[0] ) - sS.x ],
				'y': [ 0, Math.min( canvasSize.y, sizes[1] ) - sS.y ]
			}
		} );
	}
});
EWeb.Photos.Tagging.implement(new Options);



/**
 * Draggable image inside smaller canvas - used e.g. for user profile photo.
 */
EWeb.Photos.Tagging.SpotDrag = new Class({
	options: {
		unit: 'px',
		limit: true,
		noReset: false,
		modifiers: { x: 'margin-left', y: 'margin-top' },
		offset: { x: 0, y: 0 },
		grid: false
	},
	
	initialize: function(el, options){
		var elE = $( el );
		if ( EWeb.Photos.Tagging.SpotDrag._I ) { // handle singleton (is really needed?)
			EWeb.Photos.Tagging.SpotDrag._I.detach();
			EWeb.Photos.Tagging.SpotDrag._I = null;
		}
		EWeb.Photos.Tagging.SpotDrag._I = this;
		
		this.setOptions(options);
		this.handle = elE;
		
		this.element = elE;
		this.mouse = {'now': {}, 'pos': {}};
		this.value = {'start': {}, 'now': {}};
		this.bound = {
			'start': this.start.bindWithEvent(this),
			'drag': this.drag.bindWithEvent(this),
			'stop': this.stop.bindWithEvent(this)
		};
		
		if ( !this.options.noReset ) this.reset();
		this.attach();
	},

	reset: function() {
		this.element.setStyle( 'margin-left', 20 + this.options.offset.x + this.options.unit );
		this.element.setStyle( 'margin-top', 20 + this.options.offset.y + this.options.unit );
		this.setNewPos( [ 20 + this.options.offset.x, 20 + this.options.offset.y ] );
		return this;
	},
		
	attach: function(){
		this.handle.addEvent('mousedown', this.bound.start);
		return this;
	},

	detach: function(){
		this.handle.removeEvent('mousedown', this.bound.start);
		return this;
	},

	start: function(event){
		this.mouse.start = event.page;
		var limit = this.options.limit;
		this.limit = {'x': [], 'y': []};
		var walls = this.options.walls;
		this.walls = {};
		for (var z in this.options.modifiers){
			if (!this.options.modifiers[z]) continue;
			this.value.now[z] = this.element.getStyle(this.options.modifiers[z]).toInt() - this.options.offset[z];
			this.mouse.pos[z] = event.page[z] - this.value.now[z];
			if ( limit && limit[z] ){
				for (var i = 0; i < 2; i++){
					if ($chk(limit[z][i])) this.limit[z][i] = limit[z][i];
				}
			}
			if ( walls && walls[z] ) {
				this.walls[z] = { 
					pos: walls[z].pos, 
					before: this.value.now[z] < walls[z].pos,
					call: walls[z].call
				};
			}
			if ( this.options.offset && !$chk( this.options.offset[z] ) ) this.options.offset[z] = 0;
		}
		document.addListener('mousemove', this.bound.drag);
		document.addListener('mouseup', this.bound.stop);
		event.stop();
	},

	drag: function(event){
		this.out = false;
		this.mouse.now = event.page;
		for (var z in this.options.modifiers){
			if (!this.options.modifiers[z]) continue;
			this.value.now[z] = this.mouse.now[z] - this.mouse.pos[z];
			if (this.limit[z]){
				if ($chk(this.limit[z][1]) && (this.value.now[z] > this.limit[z][1])){
					this.value.now[z] = this.limit[z][1];
					this.out = true;
				} else if ($chk(this.limit[z][0]) && (this.value.now[z] < this.limit[z][0])){
					this.value.now[z] = this.limit[z][0];
					this.out = true;
				}
			}
			
			if ( this.walls[z] ){
				if ( this.walls[z].before && this.value.now[z] > this.walls[z].pos ) {
					this.walls[z].call( false );
					this.walls[z].before = false;
				} else if ( !this.walls[z].before && this.value.now[z] <= this.walls[z].pos ) {
					this.walls[z].call( true );
					this.walls[z].before = true;
				}
			}
			
			this.element.setStyle(this.options.modifiers[z], this.value.now[z] + this.options.offset[z] + this.options.unit);
		}
		event.stop();
	},

	stop: function(event){
		// set the value of current drag
		this.setNewPos( this.value.now );
	
		document.removeListener('mousemove', this.bound.drag);
		document.removeListener('mouseup', this.bound.stop);
		event.stop();
	},
	
	setNewPos: function( newPos ) {
		if ( this.options.valueSetter ) {
			if ( $type( this.options.valueSetter ) == 'function' ) {
				this.options.valueSetter( newPos );
			}
		}
	}
});
EWeb.Photos.Tagging.SpotDrag.implement(new Events, new Options);
EWeb.Photos.Tagging.SpotDrag._I = null; // instance


