
Type.registerNamespace('MySpace.PhotoAlbums');

var CropObject = null;
var	PhotoNotes = new Array();
var DefaultNote = MySpaceRes.ViewMorePicsPage.NoteDefault;
var DefaultNoteNameOnly = MySpaceRes.ViewMorePicsPage.NoteDefaultName;
var SavingMessage = MySpaceRes.ViewMorePicsPage.Saving;
var DeletingMessage = MySpaceRes.ViewMorePicsPage.Deleting;
var ErrorMessage = MySpaceRes.ViewMorePicsPage.ErrorAjaxAction;
var CloseMessage = MySpaceRes.ViewMorePicsPage.Close;
var AcFriend = null;
	
//Waiting DIV Enum types
MySpace.PhotoAlbums.WaitingMessageType = function(){
	throw Error.notImplemented();
}
MySpace.PhotoAlbums.WaitingMessageType.prototype = {
	Save: 1,
	Delete: 2,
	Approve: 3,
	Deny: 4,
	Error: 5,
	EmailSent: 6,
	EmailError: 7,
	SingleNoteMode: 8,
	Load: 9,
	TooManyFriends: 10
}
MySpace.PhotoAlbums.WaitingMessageType.registerEnum('MySpace.PhotoAlbums.WaitingMessageType');

MySpace.PhotoAlbums.PhotoNoteController = function(element){
/// <summary>
///		This class controls the ability to add/save/delete geolocated notes(tags) to a photo
///		This classes uses a cropping javascript control that was written using Prototype, but altered for usage in this context
///		The cropper is used to select an area of the photo and returns back coordinates of the selected boxed area.
///		
///		Other dependent parts of this code are the WaitingMessageType enum, NoteUI class, and the CaptionList class
/// </summary>
///	<param name="element" domElement="true"></param>

    MySpace.PhotoAlbums.PhotoNoteController.initializeBase(this, [element]);
}
MySpace.PhotoAlbums.PhotoNoteController.prototype = {

	//Private Members
	NoteCounter:-1,
	ShowBoxes:true,
	_noteMode:false,
	_isEditMode:false,
	_captionList: null,
	_image: null,	
	_imageId: null,
	_noteUI: null,
	_noteCaptionList: null,	
	_profileURL: null,
	_saveNoteHandler: null,
	_cancelNoteHandler: null,
	_failedCallbackHandler: null,
	_coords: null,
	_currentUserId: 0,
	_displayFriendId: 0,
	_stillHideBoxes: true,
	_hideDelegate: null,
	_timeoutCookie: null,
	_imageLink: null,
	_imageAnchorHref: null,
	_elementLocation: null,
	_approveBtn: null,
	_denyBtn: null,
	_currentUserNoteId: null,
	_emailPhotoHandler: null,
	_processPhotoNoteHandler: null,
	_singleMode: false,
	_instructions: null,
	_redrawImageDivHandler: null,
	_isAlbumPrivate: false,	
	_privateAlbumDiv: null,
	_friendSuggest: null,
	_retrievedFriends: false,
	_scrollTop: 0,
	_canTagOwner: true,
	_friendsOnlyMode: false,
	_imageUserId: null,
	_noteTagMsg: null,
	
	//Properties
	get_noteMode: function(){
		return this._noteMode;
	},
	set_noteMode: function(value){
		if (this._noteMode !== value){
			this._noteMode = value;
			this.get_noteCaptionList().set_noteMode(value);
		}
	},
	
	get_isEditMode: function(){
		return this._isEditMode;
	},
	set_isEditMode: function(value){
		this._isEditMode = value;
	},
	
	get_noteUI: function(){
		return this._noteUI;
	},	
	set_noteUI: function(value){
		this._noteUI = value;
	},
	
	get_captionList: function(){
		return $get(this._captionList);
	},
	set_captionList: function(value){
		this._captionList = value;
	},	

	get_cancelNoteHandler: function(){
		return this._cancelNoteHandler;
	},
	add_cancelNoteHandler: function(value){
		this._cancelNoteHandler = value;
	},	
	
	get_changeNoteStyleHandler: function(){
		return this._changeNoteStyle;
	},
	add_changeNoteStyleHandler: function(value){
		this._changeNoteStyle = value;
	},
	
	get_profileURL: function(){
		return this._profileURL;
	},
	set_profileURL: function(value){
		this._profileURL = value;
	},
	
	get_noteCaptionList: function(){
		return this._noteCaptionList;
	},
	set_noteCaptionList: function(value){
		this._noteCaptionList = value;
	},
	
	get_coords: function(){
		return this._coords;
	},
	set_coords: function(x1,y1,x2,y2){
		this._coords = {x1:x1,y1:y1,x2:x2,y2:y2};
	},
	
	get_currentUserId: function(){
		return this._currentUserId;
	},
	set_currentUserId: function(value){
		this._currentUserId = value;
	},
	
	get_displayFriendId: function(){
		return this._displayFriendId;
	},
	set_displayFriendId: function(value){
		this._displayFriendId = value;
	},
	
	get_imageLink: function(){
		return this._imageLink;
	},
	set_imageLink: function(value){
		this._imageLink = value;
	},
	
	get_currentUserNoteId: function(){
		return this._currentUserNoteId;
	},
	set_currentUserNoteId: function(value){
		this._currentUserNoteId = value;
	},
	
	get_photoSrc: function(){
		return this.get_image().src;
	},	
	set_photoSrc: function(value){
		this.get_image().src = value;
	},
	
	get_photoLink: function(){
		return this._imageAnchor.src;
	},
	set_photoLink: function(value){
		this._imageAnchor.src = value;
	},
	
	get_imageId: function(){
		return this._imageId;
	},
	set_imageId: function(value){
		this._imageId = value;
	},
	
	get_singleMode: function(){
		return this._singleMode;
	},
	set_singleMode: function(value){
		this._singleMode = value;
	},
	
	get_instructions: function(){
		return this._instructions;
	},
	set_instructions: function(value){
		this._instructions = value;
	},
	
	get_friendSuggest: function(){
		return this._friendSuggest;
	},
	set_friendSuggest: function(value){
		this._friendSuggest = value;
	},
	
	get_image: function(){
		return this._image;
	},
	set_image: function(value){
		this._image = value;
	},
	
	get_isAlbumPrivate: function(){
		return this._isAlbumPrivate;
	},
	set_isAlbumPrivate: function(value){
		this._isAlbumPrivate = value;
	},
	
	get_privateAlbumDiv: function(){
		return this._privateAlbumDiv;
	},
	set_privateAlbumDiv: function(value){
		this._privateAlbumDiv = value;
	},
	
	get_retrievedFriends: function(){
		return this._retrievedFriends;
	},
	set_retrievedFriends: function(value){
		this._retrievedFriends = value;
	},
	
	get_canTagOwner: function(){
	    return this._canTagOwner;
	},
	set_canTagOwner: function(value){
	    this._canTagOwner = value;
	},
	
	get_friendsOnlyMode: function(){
		return this._friendsOnlyMode;
	},
	set_friendsOnlyMode: function(value){
		this._friendsOnlyMode = value
	},
	
	get_imageUserId: function(){
		return this._imageUserId;
	},
	set_imageUserId: function(value){
		this._imageUserId = value;
	},

    get_noteTagMsg: function(){
		return this._noteTagMsg;
	},
	set_noteTagMsg: function(value){
		this._noteTagMsg = value;
	},



	
	//EVENTS
	add_taggingDone: function(handler){
		this.get_events().addHandler("taggingDone", handler);
	},
	remove_taggingDone: function(handler){
		this.get_events().removeHandler("taggingDone", handler);	
	},
	
	_raiseEvent : function(eventName, eventArgs) {
		var handler = this.get_events().getHandler(eventName);
		if (handler) {
			if (!eventArgs) {
				eventArgs = Sys.EventArgs.Empty;
			}
			handler(this, eventArgs);
		}
	},
		
  	initialize: function(){
		//Instantiate the Note Caption List
		var noteCaptionListEvents = {deleteNoteHandler:Function.createDelegate(this, this.DeleteNote)};		
		var noteCaptionProps = {noteMode:this.get_noteMode(),isEditMode:this.get_isEditMode()};
		
		this.set_noteCaptionList($create(MySpace.PhotoAlbums.NoteCaptionList, noteCaptionProps, noteCaptionListEvents, null, this.get_captionList()));
		
		this.set_image(this.get_element().getElementsByTagName("img")[0]);
		this._imageAnchor = this.get_element().getElementsByTagName("a")[0];	
		this._elementLocation = Sys.UI.DomElement.getLocation(this.get_element());
		
		if (this.get_image().height > 0){
			this.get_element().style.width = this.get_image().width + "px";
			this.get_element().style.height = this.get_image().height + "px";
		}
		
		//Set NoteUI events for Save and Cancel
		if (this._noteUI !== null){
			this._noteUI.set_saveNoteHandler(Function.createDelegate(this, this.SaveStart));
			this._noteUI.set_resetNoterHandler(Function.createDelegate(this, this.ResetNoter));
			if (this.get_singleMode())
				this._noteUI.add_taggingDone(Function.createDelegate(this, this.EndNoteMode));
		}
		
		this._saveNoteHandler = Function.createDelegate(this, this._saveNote);
		this._saveNoteCallbackHandler = Function.createDelegate(this, this._saveNoteCallback);
		this._failedCallbackHandler = Function.createDelegate(this, this._failedCallback);
		this._processPhotoNoteHandler = Function.createDelegate(this, this._processPhotoNotes);
		this._redrawImageDivHandler = Function.createDelegate(this, this._redrawImageDiv);
		
		//Setup friends list loading event from FriendSuggest		
		var fs = this.get_friendSuggest();
		if (fs !== null){
			fs.add_friendsLoaded(Function.createDelegate(this, this.HideWaitingMessageAndShowFs));
		}
		
		this.set_noteMode(false);		
	},	
	
	_redrawImageDiv: function(){
		var photoBounds = Sys.UI.DomElement.getBounds(this.get_image());
		
		this.get_element().style.width = photoBounds.width + "px";
		this.get_element().style.height = photoBounds.height + "px";
		
		window.setTimeout(Function.createDelegate(this, this.StartNote), 1000);
	},	
	
	StartNote: function(){
		this.set_noteMode(true);
		
		//Check to make sure friendSuggest is here
		var fs = this.get_friendSuggest();
		if (fs === null)
			return;	
		
		//set the scrollTop to make sure we stay here later
		var pos;
		if (window.innerHeight){
			  pos = window.pageYOffset
		}
		else if (document.documentElement && document.documentElement.scrollTop){
			pos = document.documentElement.scrollTop
		}
		else if (document.body){
			  pos = document.body.scrollTop
		}
		else
			 pos = window.pageYOffset
		
		this._scrollTop = pos;
		
		//This retrieves the friends list since we're in single mode and we can't get it on load of the page
		if (!this.get_retrievedFriends()){
			this.ShowWaitingMessage(MySpace.PhotoAlbums.WaitingMessageType.Load);
			fs.RetrieveFriendList(this.get_canTagOwner());
			this.set_retrievedFriends(true);
			return;
		}
		
		//Remove all box events for IE z-index issue
		var photoNotesLength = PhotoNotes.length;
		for (var i=0;i<photoNotesLength;i++){
			PhotoNotes[i].RemoveEvents();
		}
		
		this.ShowNoter();
		fs.ShowHelp();
	},
	
	ShowNoter: function(){			
		
		//load image again if it's not loaded yet
		if (!this.get_image().complete){
			this.get_image().src = this.get_photoSrc();
			
			window.setTimeout(Function.createDelegate(this, this.ShowNoter), 0);
			return;
		}
		
		this.LoadCropper();
		
		this._imageAnchor.href = "javascript:void(0);";
		
		//Check to see if this is the first time we ran this
		var NotesCount = PhotoNotes.length;
		if (NotesCount > 0)
			this.NoteCounter = NotesCount-1;	
			
		//Turn on noting instructions
		if (this.get_instructions() !== null){
			if (this.get_instructions().style.display === "none")
			{
			   this.get_noteTagMsg().style.display = "none";
			   this.get_instructions().style.display = "";
			}
		}
		
		
		//Turn on Private Album alert
		if (this.get_isAlbumPrivate() === true){
			if (this.get_privateAlbumDiv().style.display === "none") this.get_privateAlbumDiv().style.display = "";			
		}			
	},
	
	EndNoteMode: function(){
		this.ResetNoter();
		this._raiseEvent("taggingDone", Sys.EventArgs.Empty);
	},
	
	LoadCropper: function(){		
		var cropperDims = {h:50,w:50};
		//Determine if we need to shrink the default cropper size based on images smaller than 50x50px
		if (this.get_image().width < 100 || this.get_image().height < 100){
			if(this.get_image().width < 100)
				cropperDims.w = this.get_image().width;
			
			if(this.get_image().height < 100)
				cropperDims.h = this.get_image().height;
		}
		
		//Need to figure out where the top center of the image is for initialization
		var cropperLoadCoords = {x1:0,y1:50,x2:100,y2:150};
		
		cropperLoadCoords.x1 = Math.round(((parseInt(this.get_image().width) / 2) - 100));
		cropperLoadCoords.x2 = cropperLoadCoords.x1 + 100;				
		
		//Reset before we make another one.
		if (CropObject !== null){
			CropObject.remove();
			CropObject = null;
		}
		
		//remove all cropper components just to be safe
		var imgParent = this.get_image().parentNode;
		imgParent.innerHTML = "";
		imgParent.appendChild(this.get_image());			
				
		
		CropObject = new Cropper.Img(
				this.get_image().id,
				{ 
					minWidth: cropperDims.w,
					minHeight: cropperDims.h,
					onEndCrop: Function.createDelegate(this,this._positionBox),
					onDragMove: Function.createDelegate(this,this._positionBox),
					onloadCoords: cropperLoadCoords,
					displayOnInit: true,
					captureKeys: false
				}
		);		
	},
	ResetNoter: function(){
		this.set_noteMode(false);
		
		//Remove the noting ui object
		if (this._noteUI !== null) {
			this._noteUI.get_element().style.display = "none";
		}
					
		CropObject.remove();
		CropObject = null;			
		
		this._imageAnchor.href = this.get_imageLink();
	},			
	
	DeleteNote: function(noteId){
	///	<param name="noteId" type="Number" integer="true">noteId of the note to delete</param>
	
		this.ShowWaitingMessage(MySpace.PhotoAlbums.WaitingMessageType.Delete);
			
		var imageid = this.get_imageId();			
		
		MySpace.Web.Modules.PhotoAlbums.Services.PhotoNotes.DeleteNote(this.get_imageUserId(), imageid, noteId, Function.createDelegate(this, this._deleteCallback), this._failedCallbackHandler);
	},
	
	_deleteCallback: function(deletedNoteId){
	///	<param name="deletedNoteId" type="Number" integer="true">noteId of the note just deleted.  It's needed to remove it from the NoteCaptionList</param>
	
		this.HideWaitingMessage();
		
		this._deleteNoteFromUI(deletedNoteId);		
	},
	
	_deleteNoteFromUI: function(noteId){
	///	<param name="noteId" type="Number" integer="true">NoteId of the note of the note to be deleted</param>
	
		//Remove all boxes
		this.DeleteAllNotes();
		
		//Adding the non deleted ones to the another array, so we can add those back
		var PeopleInPhotoCount = PhotoNotes.length;
		var oldNotes = new Array();
		for (var j=0;j<PeopleInPhotoCount;j++){
			if (PhotoNotes[j].get_noteId() !== noteId) 
				oldNotes.push(PhotoNotes[j]);
				
			PhotoNotes[j].dispose();
		}	
		
		//Clear the notes because we're just about to add the old ones
		Array.clear(PhotoNotes);
		
		var newLength = oldNotes.length;
		for (var j=0;j<newLength;j++){
			this.AddExistingNote(oldNotes[j].get_x1(),oldNotes[j].get_y1(),oldNotes[j].get_x2(),oldNotes[j].get_y2(),oldNotes[j].get_note(),oldNotes[j].get_friendId(),oldNotes[j].get_noteId(),oldNotes[j].get_displayName());
		}
		
		//Start tagggin again in singlemode
		if (this.get_singleMode()){
			this.StartNote();
		}
	},
	
	
	
	_failedCallback: function(){	
		//Hide saving message
		this.HideWaitingMessage();
		
		this.ShowWaitingMessage(MySpace.PhotoAlbums.WaitingMessageType.Error);
	},
	
	DeleteAllNotes: function(){
		if (typeof(PhotoNotes) !== "undefined"){
		var PeopleInPhotoCount = PhotoNotes.length;
			var newAdds = new Array();
			
			for (var j=0;j<PeopleInPhotoCount;j++){
				
					var removeElement = $get(j.toString());
					var insideDivId = "inside" + j.toString();
					var removeElement2 = $get(insideDivId);
					var highlightDivId = "highlightDiv" + j.toString();		
					var highlightDiv2Id = "highlightDiv2" + j.toString();
					
					if (removeElement){
						this.get_element().removeChild(removeElement);
						this.get_element().removeChild(removeElement2);	
						this.get_element().removeChild($get(highlightDivId));	
						this.get_element().removeChild($get(highlightDiv2Id));						
					}
			}				
			
			this.get_noteCaptionList().get_element().innerHTML = "";
			
			//reset counter since we got rid of all the notes
			this.NoteCounter = -1;			
		}
	},
			
	_positionBox: function( coords, dimensions ){	
	///	<param name="coords" type="Object">Returned Object from the Cropping tool. {x1:0y1:0,x2:0,y2:0}</param>
	///	<param name="dimensions" type="Object">Returned Object from the Cropping tool. {width:0,height:0}</param>
		
		var noteDiv = this.get_noteUI().get_element();
		var addNoteWidth = parseInt(noteDiv.style.width);
		var rightPosition = coords.x1 + dimensions.width + 10;
		//var leftPosition = coords.x1 - addNoteWidth - 21;
		var topPosition = coords.y1;
		
		noteDiv.style.display = "";
		
		//Check for location of the rec to determine if we need to be on the left of right side of the box		
		/*var side = "right";
		if ((rightPosition + addNoteWidth) > this.get_image().width)
			side = "left";		
			
		switch (side){
			case "right":
				  Sys.UI.DomElement.setLocation(noteDiv,rightPosition,topPosition);
				  break
		
			case "left":
				  Sys.UI.DomElement.setLocation(noteDiv,leftPosition,topPosition);
				  break
		}*/
		Sys.UI.DomElement.setLocation(noteDiv,rightPosition,topPosition);
		
		this.set_coords(coords.x1,coords.y1,coords.x2,coords.y2)
	},	
	
	SaveStart: function(){
	 
		var saveNote = true;
		
		this.ShowWaitingMessage(MySpace.PhotoAlbums.WaitingMessageType.Save);
		
		//First send the email and then save the note for real
		var emailInput = null;
		if (this.get_noteUI().get_emailInput() !== null){
			emailInput = this.get_noteUI().get_emailInput().value.trim();
			if (emailInput !== "" && emailInput !== MySpaceRes.ViewMorePicsPage.EnterAnEmail){
				MySpace.Web.Modules.PhotoAlbums.Services.PhotoAlbums.EmailToAFriend(this.get_noteUI().get_emailInput().value.trim(), this.get_imageId(), this._saveNoteHandler, this._failedCallbackHandler);
				
				saveNote = false;
				return;
			}
		}
		
		//Submit the note
		if (saveNote)
			this._saveNote();	
	},
	
	_saveNote: function(emailSaveResult){		
	///	<param name="emailSaveResult" type="String">Returned from the web service call for Emailing the photo to a friend.  It will return a string, comma-delimited of the valid emails it just sent the photo to. If it's blank, then no valid emails were provide.</param>
	
		var coords = this.get_coords();
		
		if (coords.x1 < 0 || coords.y1 < 0 || coords.x2 < 0 || coords.y2 < 0)
			this._failedCallbackHandler();
		
		//Get the right image owner ID
		var imageOwnerId = MySpace.ClientContext.DisplayFriendId;
		if (this.get_displayFriendId() === 0)
		   imageOwnerId = this.get_currentUserId();		
			
		//Determine if there is another note that has been approved
		//We don't want to generate another approval if there's already an approved or pending one for this user and photo
		var generateApproval = true;
		for(var i=0;i<PhotoNotes.length;i++){
			if ((PhotoNotes[i].get_approvalStatus() === MySpace.Media.Domain.TaggedPhotoApprovalStatus.Pending || PhotoNotes[i].get_approvalStatus() === MySpace.Media.Domain.TaggedPhotoApprovalStatus.Approved) && PhotoNotes[i].get_friendId() === parseInt(this._noteUI.get_friendId().value)){
				generateApproval = false;
			}
		}		
		
		//Make Web Service call
		if (emailSaveResult !== null && typeof(emailSaveResult) !== "undefined"){
			if (emailSaveResult !== ""){ //Save with a good email
				MySpace.Web.Modules.PhotoAlbums.Services.PhotoNotes.SaveNote(imageOwnerId, this.get_imageId(), coords.x1, coords.y1, coords.x2, coords.y2, this._noteUI.get_friendId().value, this._noteUI.get_noteField().value, generateApproval, this._saveNoteCallbackHandler, this._failedCallbackHandler, emailSaveResult);
			}
			else{
				this.HideWaitingMessage();
				this.ShowWaitingMessage(MySpace.PhotoAlbums.WaitingMessageType.EmailError);
			}
		}
		else if (typeof(emailSaveResult) === "undefined") //Save with no email
			MySpace.Web.Modules.PhotoAlbums.Services.PhotoNotes.SaveNote(imageOwnerId, this.get_imageId(), coords.x1, coords.y1, coords.x2, coords.y2, this._noteUI.get_friendId().value, this._noteUI.get_noteField().value, generateApproval, this._saveNoteCallbackHandler, this._failedCallbackHandler);
		else{
			this.HideWaitingMessage();
			this.ShowWaitingMessage(MySpace.PhotoAlbums.WaitingMessageType.EmailError);			
		}
			
	},
	
	_saveNoteCallback: function(result, context){
	/// <param name="result" type="Object">Returns an object that has the new NoteId created for the submitted note and also the scrubbed note from the InputContentFilter.  Example: {noteId:0,note:"don&apost you love this"}</param>

		if (result.error){
			this.HideWaitingMessage();	
			this.ShowWaitingMessage(MySpace.PhotoAlbums.WaitingMessageType.TooManyFriends);
			
			return;
		}
		
		if (result.note.length > 0){
            var coords = this.get_coords();
            this.NoteCounter++;
    		
            var newBox = document.createElement("div");
            newBox.id = this.NoteCounter;
    		
            this.get_element().appendChild(newBox)		
            var notedFriendId = parseInt(this._noteUI.get_friendId().value);
    		
            //CREATE PHOTO NOTE
            var photoNoteProps;
            if (notedFriendId === 0)
   	            photoNoteProps = {isEditMode:this.get_isEditMode(),x1:coords.x1,y1:coords.y1,x2:coords.x2,y2:coords.y2,note:result.note,friendId:notedFriendId,noteId:result.noteId};
            else
	            photoNoteProps = {isEditMode:this.get_isEditMode(),x1:coords.x1,y1:coords.y1,x2:coords.x2,y2:coords.y2,note:result.note,friendId:notedFriendId,noteId:result.noteId,displayName:this._noteUI.get_noteField().value,approvalStatus:MySpace.Media.Domain.TaggedPhotoApprovalStatus.Pending};
    			
            var newPhotoNote = $create(MySpace.PhotoAlbums.PhotoNote, photoNoteProps, null, null, newBox);
            PhotoNotes.push(newPhotoNote);
        
            //CREATE NOTE CAPTION
            var isNotedFriend = false;
            if (this.get_currentUserId() === notedFriendId) isNotedFriend = true;
    		
            var newCaption;
            if (notedFriendId === 0)
	            newCaption = MySpace.PhotoAlbums.NoteCaptionList.createCaption(this.NoteCounter,newPhotoNote.get_noteId(),newPhotoNote.get_note(),notedFriendId,this.get_profileURL(),this.get_imageUserId());
            else
	            newCaption = MySpace.PhotoAlbums.NoteCaptionList.createCaption(this.NoteCounter,newPhotoNote.get_noteId(),newPhotoNote.get_note(),notedFriendId,this.get_profileURL(),this.get_imageUserId(),newPhotoNote.get_displayName(), isNotedFriend);
    			
            newCaption.divNumber = this.NoteCounter;

            //Clear caption list
            if (PhotoNotes.length === 1)
	            this.get_noteCaptionList().clearCaptionList();
    		
            //Add caption to the list
            this.get_noteCaptionList().add_note(newCaption);	
		}
		
		if (context === null){
			this.HideWaitingMessage();	
			this.get_noteUI().CancelNoteAndReset();
			
			//Show the single mode message
			if (this.get_singleMode()){
				this.ShowWaitingMessage(MySpace.PhotoAlbums.WaitingMessageType.SingleNoteMode);
			}
		}
		else{
			this.HideWaitingMessage();	
			this.ShowWaitingMessage(MySpace.PhotoAlbums.WaitingMessageType.EmailSent, context);
		}
		
		//Reposition the window scroll to where we were before the save note
		if (this._scrollTop > 0){
			window.scroll(0, this._scrollTop);
		}
	},	
	
	AddExistingNote: function(x1,y1,x2,y2,note,notedFriendId,noteId,displayName,approvalStatus){			
	///	<param name="x1" type="Number" integer="true"></param>
	///	<param name="y1" type="Number" integer="true"></param>
	///	<param name="x2" type="Number" integer="true"></param>
	///	<param name="y2" type="Number" integer="true"></param>
	///	<param name="note" type="String" optional="false">The note being posted, can be blank</param>
	///	<param name="notedFriendId" type="Number" integer="true" optional="false">UserId of the noted user. 0 is the default</param>
	///	<param name="noteId" type="Number" integer="true"></param>
	///	<param name="displayName" type="Number" integer="true" optional="true">Display name of the noted user</param>
	///	<param name="approvalStatus" type="Number" integer="true" optional="true">This is status of the note to see if it's attached photo has been approved for viewing in the tagged photos section.  This is only used in the view more pics section and not in the photo management section.</param>
	
		
		this.NoteCounter++;
		
		var newBox = document.createElement("div");
		newBox.id = this.NoteCounter;
		
		this.get_element().appendChild(newBox)		
		
		//CREATE PHOTO NOTE
		var photoNoteProps = {isEditMode:this.get_isEditMode(),x1:x1,y1:y1,x2:x2,y2:y2,note:note,friendId:notedFriendId,noteId:noteId,displayName:displayName,approvalStatus:approvalStatus};
		var newPhotoNote = $create(MySpace.PhotoAlbums.PhotoNote, photoNoteProps, null, null, newBox);
		PhotoNotes.push(newPhotoNote);
		
		//CREATE NOTE CAPTION
		var isNotedFriend = false;
		if (this.get_currentUserId() === notedFriendId) isNotedFriend = true;
		
		var newCaption = MySpace.PhotoAlbums.NoteCaptionList.createCaption(this.NoteCounter,noteId,note,notedFriendId,this.get_profileURL(),this.get_imageUserId(),displayName, isNotedFriend);
		newCaption.divNumber = this.NoteCounter;
		
		//Clear out list
		if (PhotoNotes.length === 1)
			this.get_noteCaptionList().clearCaptionList();
		
		//Add caption to the list
		this.get_noteCaptionList().add_note(newCaption);	
	},		
	
	GetPhotoNotes: function(){
			
		MySpace.Web.Modules.PhotoAlbums.Services.PhotoNotes.GetNotes(this.get_currentUserId(),this.get_imageId(), this._processPhotoNoteHandler, this._processPhotoNoteHandler)
	
	},
	
	_processPhotoNotes: function(results){
	
		//Clear caption list
		this.DeleteAllNotes();		
		
		//Clear out any leftover notelabels
		var noteLabels = document.getElementsByClassName("notelabelwrapper");
		var noteLabelsLength = noteLabels.length;
		
		if (noteLabelsLength > 0){
			for(var k=0;k<noteLabelsLength;k++){
				noteLabels[k].parentNode.removeChild(noteLabels[k]);
			}
		}
		
		//Dispose of all photo notes ready to add new ones.
		var PeopleInPhotoCount = PhotoNotes.length;
		for (var j=0;j<PeopleInPhotoCount;j++){				
			PhotoNotes[j].dispose();
		}	
		
		Array.clear(PhotoNotes);
	
		if (results.length > 0){
			var notes = Sys.Serialization.JavaScriptSerializer.deserialize(results);				
						
			//Loop through the results and call AddExistingNote
			if (notes.length > 0){
				for (var i=0;i<notes.length;i++){
					if (typeof(notes[i].approvalStatus) !== "undefined")
						this.AddExistingNote(notes[i].x1,notes[i].y1,notes[i].x2,notes[i].y2,notes[i].note,notes[i].notedFriendId,notes[i].noteId,notes[i].displayName,notes[i].approvalStatus);
					else
						this.AddExistingNote(notes[i].x1,notes[i].y1,notes[i].x2,notes[i].y2,notes[i].note,notes[i].notedFriendId,notes[i].noteId);
				}
			}
		}
		
		this._redrawImageDiv();
	},
	
	ShowWaitingMessage: function(type, optionalMsg){
	///	<param name="type" type="MySpace.PhotoAlbums.WaitingMessageType"></param>
	///	<param name="optionalMsg" type="String">Used to send an optional message to the waiting message UI</param>
		
		//Don't show the message twice
		this.HideWaitingMessage();
		
		var coverWrapper = document.createElement("div");
		coverWrapper.id = "coverWrapper";
		coverStyle = coverWrapper.style;
		coverStyle.width = this.get_element().style.width;
		coverStyle.height = this.get_element().style.height;
		coverStyle.top = "0px";
		coverStyle.left = "0px";
		coverStyle.position = "absolute";
		
		this.get_element().appendChild(coverWrapper);
	
		//Cover up the main image
		var coverUpDiv = document.createElement("div");
		coverUpDiv.id ="coverUpDiv";		
		coverUpDiv.className = "saveBackground";
		
		//Make new divs to show waiting image
		var waitingDiv = document.createElement("div");
		waitingDiv.id = "waitingDiv";
		waitingDiv.style.left = ((parseInt(this.get_image().width) / 2) - 75) + "px";
		
		switch(type){
			case MySpace.PhotoAlbums.WaitingMessageType.Save:
				waitingDiv.innerHTML = "<img src='" + loadingImagePage + "' align='middle' style='vertical-align: middle;'> <span>" + SavingMessage + "</span>";
				break;
				
			case MySpace.PhotoAlbums.WaitingMessageType.Delete:
				waitingDiv.innerHTML = "<img src='" + loadingImagePage + "' align='middle' style='vertical-align: middle;'> <span>" + DeletingMessage + "</span>";
				break;
				
			case MySpace.PhotoAlbums.WaitingMessageType.Approve:
				waitingDiv.innerHTML = "<img src='" + loadingImagePage + "' align='middle' style='vertical-align: middle;'> <span>" + SavingMessage + "</span>";
				break;
				
			case MySpace.PhotoAlbums.WaitingMessageType.Deny:
				waitingDiv.innerHTML = "<img src='" + loadingImagePage + "' align='middle' style='vertical-align: middle;'> <span>" + SavingMessage + "</span>";
				break;
				
			case MySpace.PhotoAlbums.WaitingMessageType.Load:
				waitingDiv.innerHTML = "<img src='" + loadingImagePage + "' align='middle' style='vertical-align: middle;'> <span>" + MySpaceRes.ViewMorePicsPage.Loading + "</span>";
				break;
				
			case MySpace.PhotoAlbums.WaitingMessageType.Error:
				waitingDiv.innerHTML = " <span>" + ErrorMessage + "<br /><br /></span>";
				var closeBtn = document.createElement("input");
				closeBtn.type = "button";
				closeBtn.value = CloseMessage;
				
				waitingDiv.appendChild(document.createTextNode(""));
				waitingDiv.appendChild(closeBtn);
				
				$addHandlers(closeBtn, {click:this.CloseErrorMessage}, this);			
				break;
				
			case MySpace.PhotoAlbums.WaitingMessageType.EmailSent:
				waitingDiv.innerHTML = " <div><strong>" + MySpaceRes.ViewMorePicsPage.YourTagHasBeenAdded + "<br />" + optionalMsg + "<br /><br /></div></strong>";
				var closeBtn = document.createElement("input");
				closeBtn.type = "button";
				closeBtn.value = MySpaceRes.Common.Ok.toUpperCase();
				
				waitingDiv.appendChild(document.createTextNode(""));
				waitingDiv.appendChild(closeBtn);
				waitingDiv.style.width = 200 + "px";
				
				if(!this.get_singleMode())
					$addHandlers(closeBtn, {click:this.CloseErrorMessageAndCancelNote}, this);
				else
					$addHandlers(closeBtn, {click:this._closeWaitingSingleMode}, this);
				break;
				
			case MySpace.PhotoAlbums.WaitingMessageType.EmailError:
				waitingDiv.innerHTML = " <span>" + MySpaceRes.ViewMorePicsPage.NotValidEmails + "<br /><br /></span>";
				var closeBtn = document.createElement("input");
				closeBtn.type = "button";
				closeBtn.value = CloseMessage;
				
				waitingDiv.appendChild(document.createTextNode(""));
				waitingDiv.appendChild(closeBtn);
				waitingDiv.style.width = 200 + "px";
				
				$addHandlers(closeBtn, {click:this.CloseErrorMessage}, this);			
				break;
				
			case MySpace.PhotoAlbums.WaitingMessageType.SingleNoteMode:
				waitingDiv.innerHTML = " <span><b>" + MySpaceRes.ViewMorePicsPage.YourTagHasBeenAddedSimple + "</b><br /><br /></span>";
				var finishedBtn = document.createElement("input");
				finishedBtn.type = "button";
				finishedBtn.style.width = 175 + "px";
				finishedBtn.value = MySpaceRes.ViewMorePicsPage.Finished;
				
				var tagAgainBtn = document.createElement("input");
				tagAgainBtn.type = "button";
				tagAgainBtn.style.width = 175 + "px";
				tagAgainBtn.value = MySpaceRes.ViewMorePicsPage.AddAnotherTag;
				
				waitingDiv.appendChild(document.createTextNode(""));
				waitingDiv.appendChild(finishedBtn);
				waitingDiv.appendChild(document.createElement("br"));
				waitingDiv.appendChild(document.createElement("br"));
				waitingDiv.appendChild(tagAgainBtn);
				waitingDiv.style.width = 200 + "px";
				
				//TODO: figure out handlers for to close the entire box. maybe have the page subscribe to the noter, hmmmmmmm
				$addHandlers(finishedBtn, {click:this.CloseErrorMessageAndCancelNote}, this);			
				$addHandlers(tagAgainBtn, {click:this._cancelAndTagAgain}, this);			
				break;
				
			case MySpace.PhotoAlbums.WaitingMessageType.TooManyFriends:
				waitingDiv.innerHTML = " <span>" + MySpaceRes.ViewMorePicsPage.PopularPhoto + "<br /><br /></span>";
				var closeBtn = document.createElement("input");
				closeBtn.type = "button";
				closeBtn.value = CloseMessage;
				
				waitingDiv.appendChild(document.createTextNode(""));
				waitingDiv.appendChild(closeBtn);
				
				$addHandlers(closeBtn, {click:this.CloseErrorMessageAndCancelNote}, this);				
				break;
		}
		
		coverWrapper.appendChild(coverUpDiv);
		coverWrapper.appendChild(waitingDiv);
		
		//Hide NoteUI
		if (this.get_noteMode()) this._noteUI._element.style.display = "none";
		
		//Hide notes
		//Remove all box events for IE z-index issue
		var photoNotesLength = PhotoNotes.length;
		for (var i=0;i<photoNotesLength;i++){
			PhotoNotes[i].RemoveEvents();
		}
	},
	
	HideWaitingMessage: function(){
		//Remove waiting div
		if ($get("coverWrapper")){
			this.get_element().removeChild($get("coverWrapper"));
			
			//Show NoteUI
			if (this.get_noteMode()) this._noteUI._element.style.display = "";
			
			//Remove all box events for IE z-index issue
			var photoNotesLength = PhotoNotes.length;
			for (var i=0;i<photoNotesLength;i++){
				PhotoNotes[i].AddEvents();
			}
		}
	},
	
	HideWaitingMessageAndShowFs: function(){
		this.HideWaitingMessage();
		
		var fs = this.get_friendSuggest();
		
		if (fs !== null){
			this.ShowNoter();
		}
	},
	
	CloseErrorMessage: function(){
		this.HideWaitingMessage();
		//Add all box events for IE z-index issue
		var photoNotesLength = PhotoNotes.length;
		for (var i=0;i<photoNotesLength;i++){
			PhotoNotes[i].AddEvents();
		}		
		
		var fs = this.get_friendSuggest();
		if (fs !== null)
			fs.RemoveSuggestions();
	},
	
	CloseErrorMessageAndCancelNote: function(){
		this.CloseErrorMessage();		
		
		if (this.get_noteUI().get_element().style.display !== "none")
			this.get_noteUI().CancelNoteAndReset();
		
		if (this.get_singleMode())
			this._raiseEvent("taggingDone", Sys.EventArgs.Empty);
	},
	
	_cancelAndTagAgain: function(){	
		this.HideWaitingMessage();
		
		if (this.get_noteUI().get_element().style.display !== "none")
			this.get_noteUI().CancelNoteAndReset();
		
		this.StartNote();
	},
	
	_closeWaitingSingleMode: function(){
		this.HideWaitingMessage();
		this.ShowWaitingMessage(MySpace.PhotoAlbums.WaitingMessageType.SingleNoteMode);
	},
	
	getElementsByClassName : function(className, parentElement){
		var children = ($get(parentElement) || document.body).getElementsByTagName('*');
		var elements = [];
		var length = children.length
		for (var i = 0; i < length; i++){
		  child = children[i];
		  if (Sys.UI.DomElement.containsCssClass(child, className))
			elements.push(child);
		}
		return elements;
	},
	
	dispose: function(){		
		_captionList = null;
		_image = null;	
		_noteUI = null;
		_noteCaptionList = null;	
		_profileURL = null;
		_saveNoteHandler = null;
		_cancelNoteHandler = null;
		_coords = null;
		_currentUserId = 0;
		_displayFriendId = 0;
		_stillHideBoxes = true;
		_hideDelegate = null;
		_timeoutCookie = null;
		_imageLink = null;
		_imageAnchorHref = null;
		_elementLocation = null;
		this._emailBox = null;
		CropObject = null;
		PhotoNotes = null;
		
		MySpace.PhotoAlbums.PhotoNoteController.callBaseMethod(this, 'dispose');
	}
	
}
MySpace.PhotoAlbums.PhotoNoteController.registerClass('MySpace.PhotoAlbums.PhotoNoteController', Sys.UI.Control);


MySpace.PhotoAlbums.PhotoNote = function(element){
///	<param name="element" domElement="true"></param>

    MySpace.PhotoAlbums.PhotoNote.initializeBase(this, [element]);
}
MySpace.PhotoAlbums.PhotoNote.prototype = {
///	<summary>
///		This object represents a section of the photo that has been selected by the user.  Also supports a short text label or a friendId with display name for each section selected. Note and Tag should be used interchangeably.
///</summary>

	_noteId: null,
	_x1: null,
	_y1: null,
	_x2: null,
	_y2: null,
	_note: null,
	_friendId: null,
	_noteCounter: -1,
	_displayName: null,
	_approvalStatus: null,

	get_isEditMode: function(){
		return this._isEditMode;
	},
	set_isEditMode: function(value){
		this._isEditMode = value;
	},
	
	get_x1: function(){
		return this._x1;
	},
	set_x1: function(value){
		this._x1 = value;
	},
	
	get_y1: function(){
		return this._y1;
	},
	set_y1: function(value){
		this._y1 = value;
	},
	
	get_x2: function(){
		return this._x2;
	},
	set_x2: function(value){
		this._x2 = value;
	},
	
	get_y2: function(){
		return this._y2;
	},
	set_y2: function(value){
		this._y2 = value;
	},
	
	get_note: function(){
		return this._note;
	},
	set_note: function(value){
		this._note = value;
	},
	
	get_friendId: function(){
		return this._friendId;
	},
	set_friendId: function(value){
		this._friendId = value;
	},
	
	get_noteId: function(){
		return this._noteId;
	},
	set_noteId: function(value){
		this._noteId = value;
	},

	get_noteCounter: function(){
		return this._noteCounter;
	},
	set_noteCounter: function(value){
		this._noteCounter = value;
	},	
	
	get_displayName: function(){
		return this._displayName;
	},
	set_displayName: function(value){
		this._displayName = value;
	},
	
	get_approvalStatus: function(){
		return this._approvalStatus;
	},
	set_approvalStatus: function(value){
		this._approvalStatus = value;
	},
	
	initialize: function(){
		
		//For IE
		this.get_element().innerHTML = "&nbsp;";
		
		//figure height and width based on x1,y1 and x2,x2
		var width = this.get_x2() - this.get_x1();
		var height = this.get_y2() - this.get_y1();
		
		this.get_element().className = "nonote";
		
		//Set position
		var s = this.get_element().style;
		s.left = parseInt(this.get_x1()) + "px";
		s.top = parseInt(this.get_y1()) + "px";
		s.height = height + "px";
		s.width = width + "px";	
		s.position = "absolute";
		s.zIndex = 2000;	

		//add second div for effect
		var insideDiv = document.createElement("div");
		insideDiv.id = "inside" + this.get_element().id;
		var insideDivStyle = insideDiv.style;
		insideDivStyle.left = (parseInt(this.get_x1())+1) + "px";
		insideDivStyle.top = (parseInt(this.get_y1())+1) + "px";
		insideDivStyle.height = (height-2) + "px";
		insideDivStyle.width = (width-2) + "px";
		insideDivStyle.display = "none";
		insideDivStyle.zIndex = 2;
		this.get_element().parentNode.appendChild(insideDiv);
		
		var linkId = this.get_element().id + "-" + this.get_element().id;
		this.get_element().linkId = linkId;
		
		//add highlight divs for effect
		var highlightDiv = document.createElement("div");
		highlightDiv.id = "highlightDiv" + this.get_element().id;
		var highlightDivStyle = highlightDiv.style;
		highlightDiv.className = "NoteBorderHighlight";
		highlightDivStyle.left = (parseInt(s.left)-1) + "px";
		highlightDivStyle.top = (parseInt(s.top)-1) + "px";
		highlightDivStyle.height = (parseInt(s.height)+2) + "px";
		highlightDivStyle.width = (parseInt(s.width)+2) + "px";
		highlightDivStyle.display = "none";
		this.get_element().parentNode.appendChild(highlightDiv);
		
		var highlightDiv2 = document.createElement("div");
		highlightDiv2.id = "highlightDiv2" + this.get_element().id;
		var highlightDiv2Style = highlightDiv2.style;
		highlightDiv2.className = "NoteBorderHighlight";
		highlightDiv2Style.left = (parseInt(s.left)+2) + "px";
		highlightDiv2Style.top = (parseInt(s.top)+2) + "px";
		highlightDiv2Style.height = (parseInt(s.height)-4) + "px";
		highlightDiv2Style.width = (parseInt(s.width)-4) + "px";
		highlightDiv2Style.display = "none";
		this.get_element().parentNode.appendChild(highlightDiv2);
		
					
		$addHandlers(this.get_element(), {mouseover:this.EditBoxMouseOver,mouseout:this.EditBoxMouseOut}, this);
	},	
	
	RemoveEvents: function(){
		//$clearHandlers(this.get_element());
		this.get_element().style.display = "none";
	},
	
	AddEvents: function(){
		//$addHandlers(this.get_element(), {mouseover:this.EditBoxMouseOver,mouseout:this.EditBoxMouseOut}, this);
		this.get_element().style.display = "";
	},

	EditBoxMouseOver: function(e){
	///	<param name="e" type="Sys.UI.DomEvent"></param>
	
		if(!e) e=window.event;
		var target = e.target? e.target:e.srcElement;		
		$get(target.linkId).className = "captionNoteHighlight";
		
		//Get associated Photo Note object
		var theNote = PhotoNotes[target.id];
		
		//figure height and width based on x1,y1 and x2,x2
		var width = theNote.get_x2() - theNote.get_x1();
		var height = theNote.get_y2() - theNote.get_y1();
		
		//Add new box that shows the note near the box
		var noteLabel = document.createElement("span");
		noteLabel.className = "notelabel";	
		
		if (theNote.get_friendId() === 0)
			noteLabel.innerHTML = theNote.get_note();
		else
			noteLabel.innerHTML = theNote.get_displayName();
			
		//Add text-centered wrapper
		var divWrapper = document.createElement("div");
		divWrapper.id = "noteLabel" + target.id;
		divWrapper.style.left = theNote.get_x1() + "px";		
		divWrapper.style.top = (theNote.get_y1() + height + 3) + "px";
		divWrapper.className = "notelabelwrapper";	
		
		divWrapper.appendChild(noteLabel);				
		target.parentNode.appendChild(divWrapper);
		
		//show divs that make up the entire note box	
		var insideDivId = "inside" + target.id;
		var insideDiv = $get(insideDivId);
		var noteDiv = $get(target.id.toString());
		
		var highlightDivId = "highlightDiv" + target.id;		
		var highlightDiv2Id = "highlightDiv2" + target.id;
		
		var hDiv = $get(highlightDivId);		
		var hDiv2 = $get(highlightDiv2Id);
		
		Sys.UI.DomElement.toggleCssClass(noteDiv, "nonote");	
		Sys.UI.DomElement.toggleCssClass(noteDiv, "NoteBorder");	
		Sys.UI.DomElement.toggleCssClass(insideDiv, "InsideNoteBorder");
		
		hDiv.style.display = "";
		hDiv2.style.display = "";	
		insideDiv.style.display = "";
	},
	
	EditBoxMouseOut: function(e){
	///	<param name="e" type="Sys.UI.DomEvent"></param>
	
		if(!e) e=window.event;
		var target = e.target? e.target:e.srcElement;
		$get(target.linkId).className = "";	
			
		var noteLabel = "noteLabel" + target.id;
		if ($get(noteLabel)){			
			target.parentNode.removeChild($get(noteLabel));
		}
			
		//Hide divs that make up the note
		var noteDiv = $get(target.id.toString());
		var insideId = "inside" + target.id;
		var insideDiv = $get(insideId);
		var highlightDivId = "highlightDiv" + target.id;		
		var highlightDiv2Id = "highlightDiv2" + target.id;
		
		Sys.UI.DomElement.toggleCssClass(noteDiv, "nonote");	
		Sys.UI.DomElement.toggleCssClass(noteDiv, "NoteBorder");		
		Sys.UI.DomElement.toggleCssClass(insideDiv, "InsideNoteBorder");
		$get(highlightDivId).style.display = "none";
		$get(highlightDiv2Id).style.display = "none";
		insideDiv.style.display = "none";				
	},
	
	dispose: function(){
		$clearHandlers(this.get_element());
		
		MySpace.PhotoAlbums.PhotoNote.callBaseMethod(this, 'dispose');
	}
};
MySpace.PhotoAlbums.PhotoNote.registerClass('MySpace.PhotoAlbums.PhotoNote', Sys.UI.Control);


MySpace.PhotoAlbums.NoteUI = function(element){
///	<summary>
///		Represents the box that takes the input of the note.  This includes autoComplete which is a separatly written component.
///	</summary>
///	<param name="element" domElement="true"></param>

    MySpace.PhotoAlbums.NoteUI.initializeBase(this, [element]);
}


MySpace.PhotoAlbums.NoteUI.prototype = {

	_MAX_NOTE_LENGTH: 50,
	
	_noteField: null,
	_noteFieldDiv: null,
	_saveButton: null,
	_cancelButton: null,
	_friendId: null,
	_cancelNoteKeyDownHandler: null,
	
	_saveNoteHandler: null,
	_resetNoterHandler: null,	
	_emailBox: null,
	_emailInput: null,
	_addFriendHandler: null,
	_singleMode: false,
	_friendSuggest: null,
	_enableTextTags: true,
	_canForwardToFriend: true,
		
	get_noteFieldDiv: function(){
		return this._noteFieldDiv;
	},
	set_noteFieldDiv: function(value){
		this._noteFieldDiv = value;
	},	
	
	get_noteField: function(){
		return this._noteField;
	},
	set_noteField: function(value){
		this._noteField = value;
		this._noteField.className = "notefield";
		this._noteField.maxlength = this._MAX_NOTE_LENGTH;
	},
	
	get_friendSuggest: function(){
		return this._friendSuggest;
	},
	set_friendSuggest: function(value){
		if (this._friendSuggest !== value){
			this._friendSuggest = value;
				
			//Set up the watcher for the email field
			if (this.get_emailBox() !== null){	
				this._friendSuggest.add_propertyChanged(Function.createDelegate(this, this._watchFriendSuggestions));
			}
		}
	},
	
	get_saveButton: function(){
		return $get(this._saveButton);
	},
	set_saveButton: function(value){
		this._saveButton = value;
	},

	get_cancelButton: function(){
		return $get(this._cancelButton);
	},
	set_cancelButton: function(value){
		this._cancelButton = value;
	},
	
	get_friendId: function(){
		return $get(this._friendId);
	},
	set_friendId: function(value){
		this._friendId = value;
	},
	
	get_saveNoteHandler: function(){
		return this._saveNoteHandler;
	},
	set_saveNoteHandler: function(value){
		this._saveNoteHandler = value;
	},
	
	get_resetNoterHandler: function(){
		return this._resetNoterHandler;
	},
	set_resetNoterHandler: function(value){
		this._resetNoterHandler = value;
	},	
	
	get_emailBox: function(){
		return this._emailBox;
	},
	set_emailBox: function(value){
		this._emailBox = value;
	},	
		
	get_emailInput: function(){
		return this._emailInput;
	},
	set_emailInput: function(value){
		this._emailInput= value;
	},
	
	get_addFriendHandler: function(){
		return this._addFriendHandler;
	},
	set_addFriendHandler: function(value){
		this._addFriendHandler = value;
	},
	
	get_singleMode: function(){
		return this._singleMode;
	},
	set_singleMode: function(value){
		this._singleMode = value;
	},	
	
	get_enableTextTags: function(){
		return this._enableTextTags;
	},
	set_enableTextTags: function(value){
		this._enableTextTags = value;
	},
	
	get_canForwardToFriend: function(){
		return this._canForwardToFriend;
	},
	set_canForwardToFriend: function(value){
		this._canForwardToFriend = value;
	},
	
	//EVENTS
	
	add_taggingDone: function(handler){
		this.get_events().addHandler("taggingDone", handler);
	},
	remove_taggingDone: function(handler){
		this.get_events().removeHandler("taggingDone", handler);	
	},

	
	_raiseEvent : function(eventName, eventArgs) {
		var handler = this.get_events().getHandler(eventName);
		if (handler) {
			if (!eventArgs) {
				eventArgs = Sys.EventArgs.Empty;
			}
			handler(this, eventArgs);
		}
	},
	
		
	initialize: function(){		
		//Save button and enter events for the noting interface
		if (this.get_enableTextTags()){
			$addHandlers(this.get_noteField(), {keydown:this.SaveNoteKeyDown}, this);
			$addHandlers(this.get_saveButton(), {click:this.SaveNote}, this);	
		}
		else
			this.get_saveButton().style.display = "none";
		
		if (this.get_singleMode() === false)
			$addHandlers(this.get_cancelButton(), {click:this.CancelNoteAndReset}, this);
		else
			$addHandlers(this.get_cancelButton(), {click:this._cancelSingleMode}, this);		
		
		this._cancelNoteKeyDownHandler = Function.createDelegate(this, this.CancelNoteKeyDown);
		$addHandler(document, 'keydown', this._cancelNoteKeyDownHandler);
		this.set_addFriendHandler(Function.createDelegate(this, this._addAcFriend));
		
		var note = this.get_noteField();	
		note.style.width = 180 + "px";
		note.value = "";		
		$addHandlers(note, {focus:this.ChangeNoteStyle,blur:this.ChangeNoteStyleBack}, this);
		
		//Setup events for the email photo box
		if (this.get_emailBox() !== null && this.get_canForwardToFriend()){			
			
			//Get input field
			this.set_emailInput(this.get_emailBox().getElementsByTagName("input")[0]);
			
			this._emailBoxReset();			
			
			//Input field events
			$addHandlers(this.get_emailInput(), {focus:this._emailInputOnFocus,blur:this._emailInputOnBlur,keydown:this.SaveNoteKeyDown}, this);
		}
		else if(this.get_emailBox() !== null && this.get_canForwardToFriend() === false){
			this.get_emailBox().parentNode.removeChild(this.get_emailBox());
		}
		
		//Reset the notes box
		this.ChangeNoteStyleBack();		
		this.get_element().style.display = "none";
	},
	
	_raiseTaggingDone: function(){
		this._raiseEvent("taggingDone", Sys.EventArgs.Empty)
	},

	SaveNote:function(){
		var doSave = true;
		
		NotedFriend = this.get_friendId().value;		
		Note = this.get_noteField();
		
		//Check field length
		if (Note.value.length > 50){
			Note.value = Note.value.substring(0,49);
		}

		if(Note.value === DefaultNote)
			doSave = false;
			
		if (Note.value.length === 0 && NotedFriend === "0")
			doSave = false;

		if (doSave)
			this.get_saveNoteHandler()();
	},
	
	SaveNoteKeyDown: function(e){	
	///	<param name="e" type="Sys.UI.DomEvent"></param>
	
		//Check field length
		if (e.target.value.length > 50){
			e.target.value = e.target.value.substring(0,49);
		}
		
		if (e.keyCode === Sys.UI.Key.enter)
			this.SaveNote();
	},

	CancelNoteAndReset: function(){		
		this.get_resetNoterHandler()();			
		
		//Find the text box
		Note = this.get_noteField();	
		Note.value = "";
		
		this.RemoveAcFriend();
		
		//AutoComplete Hard Reset
		fs = this.get_friendSuggest();
		if (fs !== null){
			fs.RemoveSuggestions();
			
			fs.HardReset();			
		}
		
		if (this.get_emailBox() !== null)
			this._emailBoxReset();
			
		this.ChangeNoteStyleBack();
	},
	
	CancelNoteKeyDown: function(e){
	///	<param name="e" type="Sys.UI.DomEvent"></param>
	
		if (CropObject !== null){
			if (e.keyCode === Sys.UI.Key.esc)
				this.CancelNoteAndReset();
		}
	},	
	
	_cancelSingleMode: function(){
		//Find the text box
		Note = this.get_noteField();	
		Note.value = "";
				
		this.RemoveAcFriend();
		
		//AutoComplete Hard Reset
		fs = this.get_friendSuggest();
		if (fs !== null){
			fs.RemoveSuggestions();
			
			fs.HardReset();
		}
		
		//Hide email to a friend box
		if (this.get_emailBox() !== null)
			this._emailBoxReset();
			
		this.ChangeNoteStyleBack();
		
		this._raiseTaggingDone();
	},
	
	_addAcFriend: function(obj){
	///	<param name="obj" type="Object">Instance of a friend</param>	
	
		/*		
		<div class="addRcpt">
			<div id="AcFriendContainer" class="rcpt">
				<div id="imgTD" style="width: 34px; height: 34px;">
					<div id="divImgWrapOuter" class="imgWrapOuter">
						<div id="divImgWrapMiddle" class="imgWrapMiddle">
							<div id="divImgWrapInner" class="imgWrapInner">
								<img id="recipientImage" src="http://x.myspace.com/images/no_pic.gif" style="height: 30px;"/>
							</div>
						</div>
					</div>
				</div>
				<div class="acDisplayName">totalnutcase</div>
				<div id="divCloseBtn" class="closeRecipient"/>
			</div>
		</div>
		*/
		
		
		if (AcFriend === null && obj.get_a1() !== ""){
			var noteField = this.get_noteField();
			noteField.style.display = "none";			
			
			var acDiv = document.createElement("div");
			acDiv.className = "addRcpt"; 
			
			var AcFriendContainer = document.createElement("div");
			AcFriendContainer.id = "AcFriendContainer";
			AcFriendContainer.className = "rcpt";
			acDiv.appendChild(AcFriendContainer);
			
			var imgTD = document.createElement("div");
			imgTD.id = "imgTD";
			imgTD.style.cssFloat = "left";
			AcFriendContainer.appendChild(imgTD);
			
			var imgWrapOuter = document.createElement("div");
			imgWrapOuter.id = "divImgWrapOuter"
			imgWrapOuter.className = "imgWrapOuter";
			imgTD.appendChild(imgWrapOuter);
			
			var imgWrapMiddle = document.createElement("div");
			imgWrapMiddle.id = "divImgWrapMiddle";
			imgWrapMiddle.className = "imgWrapMiddle";
			imgWrapOuter.appendChild(imgWrapMiddle);
			
			var imgWrapInner = document.createElement("div");
			imgWrapInner.id = "divImgWrapInner";
			imgWrapInner.className = "imgWrapInner";
			imgWrapMiddle.appendChild(imgWrapInner);
			
			var AcFriendImg = document.createElement("img");
			AcFriendImg.id = "recipientImage";
			AcFriendImg.src = obj.get_imgURI();						
			imgWrapInner.appendChild(AcFriendImg);			
						
			var divDisplayName = document.createElement("div");
			divDisplayName.className = "acDisplayName";
			divDisplayName.innerHTML = this.TrimName(obj.get_a1());
			AcFriendContainer.appendChild(divDisplayName);
			
			this.get_noteFieldDiv().appendChild(acDiv);
			
			//Resizes the default photo and returns the size of the containing div
			var imgTDsize = this.AcResizeImage(AcFriendImg, imgTD);
			
			imgTD.style.width = imgTDsize.w;
			imgTD.style.height = imgTDsize.h;
			
			AcFriend = obj;
		
			this.get_friendId().value = obj.get_ID();	
			noteField.value = obj.get_a1();
			
			this.SaveNote();
		}
	},
	RemoveAcFriend: function(){
		var noteBox = this.get_noteFieldDiv();
		var boxDivs = noteBox.getElementsByTagName("div");	
		
		if (boxDivs.length > 0)
			noteBox.removeChild(boxDivs[0]);
			
		AcFriend = null;		
		this.get_noteField().style.display = "";
		this.get_noteField().value = "";		
		this.ChangeNoteStyleBack();
		this.get_friendId().value = "0";
	},
	
	TrimName: function (name){
	///	<param name="name" type="String"></param>
	
		if (name.length > this._MAX_NOTE_LENGTH) 
			name = name.substring(0,this._MAX_NOTE_LENGTH) + "...";
		return name;
	},

	
	AcResizeImage: function(img, imgTD){
	///	<param name="img" domElement="true"></param>
	///	<param name="imgTD" domElement="true"></param>
	
		  var maxSize = 30;
		  var width = img.clientWidth;
		  var height = img.clientHeight;			 
		  var ratio = width / height;
	
		  if((width == height && "24" == width) || (width == height && "0" == width)) { // img isn't loaded yet
				img.style.height = maxSize + "px";
				img.style.width = (maxSize * ratio) + "px";
		  }
		  
		  if (width>height) {
				if ( width > maxSize ){
					  img.style.width = maxSize + "px"; ;
					  img.style.height = (maxSize / ratio) + "px";
				}
		  } 
		  else {
				if ( height > maxSize ){
					  img.style.height = maxSize + "px"; 
					  img.style.width = (maxSize * ratio) + "px";
				}
		  }
		  var imgTDwidth = (maxSize+4) + "px";
		  var imgTDheight = (maxSize+4) + "px";
		  
		  return {w:imgTDwidth,h:imgTDheight}
	},

	ChangeNoteStyle: function(){	
		Note = this.get_noteField();
		if (Note.value === DefaultNote || Note.value === DefaultNoteNameOnly){
			Note.style.color = "#000000";
			Note.value = "";
			
			var fs = this.get_friendSuggest();
			/*if (fs !== null)
				fs.ShowHelp();*/
		}
	},
		
	ChangeNoteStyleBack: function(){	
		Note = this.get_noteField();
		if (Note.value.length === 0){
			Note.style.color = "#999999";
			if (this.get_enableTextTags())
				Note.value = DefaultNote;
			else
				Note.value = DefaultNoteNameOnly;
		}
	},
	
	
	_watchFriendSuggestions: function(sender, e){
		if(e.get_propertyName() === '_suggestionsCount'){
			if(sender.get_suggestionsCount() > 0){			
				this.get_emailBox().style.display = "none"; 
			}
			else{
				this.get_emailBox().style.display = "";
			}
		}
	},
	
	_showEmailField: function(e){
	///	<param name="e" type="Sys.UI.DomEvent"></param>
	
		if (typeof(this.get_friendSuggest()) !== "object")
			return;
			
		fs = this.get_friendSuggest();
		
		if (fs.get_localMatches().length === 0) 
			this.get_emailBox().style.display = "";
		else{
			this.get_emailBox().style.display = "none"; 
			this._emailBoxReset();
		}       
	},
	
	_emailInputOnFocus: function(){
		if (this.get_emailInput() !== null && this.get_emailInput().value === MySpaceRes.ViewMorePicsPage.EnterAnEmail){
			this.get_emailInput().value = "";
			this.get_emailInput().style.color = "#000";
		}
	},
	
	_emailInputOnBlur: function(){
		if (this.get_emailInput() !== null && this.get_emailInput().value.trim() === "")
			this._emailBoxReset();
	},

	_emailBoxReset: function(){
		if (this.get_emailInput() !== null){
			this.get_emailInput().value = MySpaceRes.ViewMorePicsPage.EnterAnEmail;
			this.get_emailInput().style.color = "#666";
			
			this.get_emailBox().style.display = "none";
		}
	}
}
MySpace.PhotoAlbums.NoteUI.registerClass('MySpace.PhotoAlbums.NoteUI', Sys.UI.Control);


MySpace.PhotoAlbums.NoteCaptionList = function(element){
///	<param name="element" domElement="true"></param>

    MySpace.PhotoAlbums.NoteCaptionList.initializeBase(this, [element]);
}
MySpace.PhotoAlbums.NoteCaptionList.prototype = {

	_noteMode: null,
	_deleteNoteHandler: null,
	
	
	get_noteMode: function(){
		return this._noteMode;
	},
	set_noteMode: function(value){
		this._noteMode = value;
	},
	
	get_isEditMode: function(){
		return this._isEditMode;
	},
	set_isEditMode: function(value){
		this._isEditMode = value;
	},
	
	get_deleteNoteHandler: function(){
		return this._deleteNoteHandler;
	},
	add_deleteNoteHandler: function(value){
		this._deleteNoteHandler = value;
	},
	
	get_cancelNoteHandler: function(){
		return this._cancelNoteHandler;
	},
	add_cancelNoteHandler: function(value){
		this._cancelNoteHandler = value;
	},
	
	initialize: function(){
		
	},
	
	clearCaptionList: function(){
		this.get_element().innerHTML = "";
	},
	
	add_note: function(captionNote){
	///	<param name="captionNote" type="MySpace.PhotoAlbums.NoteCaptionList.createCaption"></param>
	
		var captionList = this.get_element();
		if (captionList.childNodes.length>0){
			captionList.appendChild(document.createTextNode(", "));
		}
		
		captionList.appendChild(captionNote);
		
		//Add mouse over for the box highlighing when mouse over of the caption note
		$addHandlers(captionNote.childNodes[0],{mouseover:this.HighlightCaption,mouseout:this.HighlightCaption},this);
		
		//Check to see if there are 1 or 2 a tags for the delete click handler
		var deleteImg = captionNote.getElementsByTagName("img")[0];		
		if (deleteImg !== undefined)
		    $addHandlers(deleteImg,{click:this.DeleteNote}, this);
	},
	
	HighlightCaption: function(e){
	///	<param name="e" type="Sys.UI.DomEvent"></param>
	
		if(!e) e=window.event;
		var target = e.target? e.target:e.srcElement;
		var thenote = $get(target.divNumber.toString());
			
		if (thenote !== null){	
				var insideDivId = "inside" + thenote.id;
				var highlightDivId = "highlightDiv" + thenote.id;		
				var highlightDiv2Id = "highlightDiv2" + thenote.id;
								
				var hightlight1Style = $get(highlightDivId).style;
				var hightlight2Style = $get(highlightDiv2Id).style;
				var insideDiv = $get(insideDivId);
			
			if (hightlight1Style.display === "none"){
				
				//show highlight divs for effect		
				highlightDivId = "highlightDiv" + thenote.id;		
				highlightDiv2Id = "highlightDiv2" + thenote.id;
				
				hightlight1Style.display = "";
				hightlight2Style.display = "";
				insideDiv.style.display = "";
				
				//Show the note boxes
				Sys.UI.DomElement.toggleCssClass(thenote, "nonote");	
				Sys.UI.DomElement.toggleCssClass(thenote, "NoteBorder");
				Sys.UI.DomElement.toggleCssClass(insideDiv, "InsideNoteBorder");
			}
			else{	
				hightlight1Style.display = "none";
				hightlight2Style.display = "none";
				insideDiv.style.display = "none";
				
				//Hide the note boxes
				Sys.UI.DomElement.toggleCssClass(thenote, "nonote");	
				Sys.UI.DomElement.toggleCssClass(thenote, "NoteBorder");
				Sys.UI.DomElement.toggleCssClass(insideDiv, "InsideNoteBorder");
			}
		}
	},
	
	DeleteNote: function(e){ //In context of the a tag that does the delete (this = <a>)
	///	<param name="e" type="Sys.UI.DomEvent"></param>
	
		var doDelete = true;
		
		//Need to only do this confirmation if we're in view mode
		if (!this.get_isEditMode()){
			doDelete = false;
		
			if (confirm(MySpaceRes.ViewMorePicsPage.DeletePhotoNoteMessage))
				doDelete =  true;
		}
		
		if (doDelete){
			if(!e) e=window.event;
			var target = e.target? e.target:e.srcElement;				
			var noteid = parseInt(target.parentNode.noteId);		
			
			this.get_deleteNoteHandler()(noteid);
		}	
	},
		
	ShowCaptions: function(){
		var theCaptions = this.get_element().childNodes;
		var theCaptionsLength = theCaptions.length;
		if (theCaptionsLength > 0){
			for (var i = 0; i < theCaptionsLength; i++){
				if(theCaptions[i].style) theCaptions[i].style.display = "";
			}
		}
	},
	
	HideCaptions: function(){
		var theCaptions = this.get_element().childNodes;
		var theCaptionsLength = theCaptions.length;
		if (theCaptionsLength > 0){
			for (var i = 0; i < theCaptionsLength; i++){
				if(theCaptions[i].style) theCaptions[i].style.display = "none";
			}
		}
	},
	
	dispose: function(){		
		var captionList = this.get_element();
		var deleteImages = captionList.getElementsByTagName("img");
		var deleteImagesLength = deleteImages.Length;
		
		for (var i = 0; i < deleteImagesLength; i++){
			$clearHandlers(deleteImages[i]);
		}
		
		MySpace.PhotoAlbums.NoteCaptionList.callBaseMethod(this, 'dispose');
	}
}


MySpace.PhotoAlbums.NoteCaptionList.createCaption = function (noteCount,noteId,note,friendId,PROFILE_URL,imageUserId,displayName,isNotedFriend){
	/// <param name="noteCount" type="Number" integer="true"></param>
	/// <param name="noteId" type="Number" integer="true"></param>
	/// <param name="note" type="Object"></param>
	/// <param name="friendId" type="Number" integer="true"></param>
	/// <param name="PROFILE_URL" type="String"></param>
	/// <param name="isEditMode" type="Boolean"></param>
	/// <param name="displayName" type="String"></param>
	/// <param name="isNotedFriend" type="Boolean"></param>
	
	
	var a = null;			
				
	if (friendId === 0){
		a = document.createElement('span');
		a.innerHTML=note;		
	}
	else {
		a = document.createElement('a');
		a.href=String.format(PROFILE_URL, friendId);
		a.target = "_blank";
		a.innerHTML = displayName;		
	}
	
	a.id=noteCount + "-" + noteCount;
	a.divNumber=noteCount;
		
	//Make wrapper for whole note and delete
	var captionWrapper = document.createElement("span");
	captionWrapper.id = "wrapper" + noteCount;
	captionWrapper.className = "captionWrapper";
	captionWrapper.appendChild(a);	
	
	//Check to see if we're in the tagged photos view
	var viewingOwnPhoto = false;
		
	//Is in viewing their own photos
	if (imageUserId === MySpace.ClientContext.UserId)
		viewingOwnPhoto = true;
	
	//Append delete links
	if (isNotedFriend || viewingOwnPhoto){				
		var deleteLink = document.createElement('a');
		deleteLink.href = "javascript:void(0);";
		deleteLink.className = "redxvalign";
		deleteLink.innerHTML = "<img src='" + redXImagePath + "' align='middle'>";
		deleteLink.noteId = noteId;
		deleteLink.id = "deleteLink" + noteId;
		captionWrapper.appendChild(document.createTextNode(" [ "));
		captionWrapper.appendChild(deleteLink);	
		captionWrapper.appendChild(document.createTextNode(" ]"));
	}

	return captionWrapper;
};
MySpace.PhotoAlbums.NoteCaptionList.registerClass("MySpace.PhotoAlbums.NoteCaptionList", Sys.UI.Control);