
// This is the page controller constructor. This controller handles
// the Edit Gallery page.
function GalleryEditPage( strControllerURL, objPostProperties ){
	this.ControllerURL = strControllerURL;
	this.PostProperties = objPostProperties;
	
	// Initialize page.
	this.Init();
}

// Extend the page controller class.
GalleryEditPage.prototype = new PageControllerClass;


// When page loads, hook up events and properties.
GalleryEditPage.prototype.Init = function(){
	var objSelf = this;
	var jForm = $( "#edit-gallery" );
	var jUploadButton = $( "#upload-photo" );		
	var jSaveGallery = $( "#save-gallery" );
	var jDeleteGallery = $( "#delete-gallery" );

	// Flag as busy.
	this.SetBusy( true );
	
	// Hook up the upload button.
	jUploadButton.click(
		function( objEvent ){
			// Check to see if page is currently busy.
			if (objSelf.GetBusy()){
			
				// Alert busyness.
				objSelf.AlertBusy();
				
				// Prevent default.
				objEvent.preventDefault();
				return( false );
				
			} else {
			
				// Flag page as busy.
				objSelf.SetBusy( true );
				
				// Uplaod photos.
				objSelf.UploadPhotos();
				
			}
		}
		);
	
	// Hook up save button.
	jSaveGallery.click(
		function( objEvent ){
			// Check to see if page is currently busy.
			if (objSelf.GetBusy()){
			
				// Alert busyness.
				objSelf.AlertBusy();
			
			} else {
		
				// Flag page as busy.
				objSelf.SetBusy( true );
		
				// Submit form.
				jForm.submit();
				
			}
				
			// Stop click event.
			objEvent.preventDefault();
			return( false );
		}
		);
	
	// Hook up delete button.
	jDeleteGallery.click(
		function( objEvent ){
			// Check to see if page is currently busy.
			if (objSelf.GetBusy()){
			
				// Alert busyness.
				objSelf.AlertBusy();
				
				// Stop click event.
				objEvent.preventDefault();
				return( false );
				
			} else if (!confirm( "Delete this gallery?" )){
			
				// Stop click event.
				objEvent.preventDefault();
				return( false );
			
			} else {
				
				// We are deleting the gallery. Flag page as busy.
				objSelf.SetBusy( true );
								
			}
		}
		);
	
	
	// Load the photo data.
	this.LoadPhotos();
	
	// Leave the init method busy since the load photos will end that.
}


// This loads the photos into the edit page (based on the list of IDs).
// We are going to assume that the page is already busy at this moment.
GalleryEditPage.prototype.LoadPhotos = function(){
	var objSelf = this;
	var jForm = $( "#edit-gallery" );
	
	// Define the post properties.
	var objPostProperties = {
		"do": "api.gallery.get-photo-list-markup",
		photo_id_list: jForm.find( "input[ name = 'photo_id_list' ]" ).val()
		};
	
	// Make API request with the given data.
	$.post(
		this.ControllerURL,
		objPostProperties,
		function( objResponse ){
			objSelf.LoadPhotosHandler( objResponse );
		},
		"json"
		);
}


// This handles the photo load handler.
GalleryEditPage.prototype.LoadPhotosHandler = function( objResponse ){
	var jListContainer = $( "#photo-list-container" );
		
	// Check to see if there are errors. If there are, alert.
	if (objResponse.SUCCESS){
		
		// Initialize the photos that have come back.
		var jPhotoIDList = $( "#photo_id_list" );
		var jResponse = $( objResponse.DATA );
		var jPhotoListItem = jResponse.find( "li" );
		
		// Loop over each photo.
		jPhotoListItem.each(
			function(){
				var jThis = $( this );	
				var jDelete = jThis.find( "a.delete-photo" );
				
				// Hook up delete link.
				jDelete.click(
					function( objEvent ){
						if (confirm( "Delete photo?" )){
							var intID = jThis.attr( "id" ).replace( new RegExp( "[^\\d]+" ), "" );
							
							// Remove the ID from the id list.
							jPhotoIDList.val( 
								jPhotoIDList.val().replace( new RegExp( ("\\b" + intID + "\\b"), "gi" ), "" )
								);
													
							// Remove this element from the markup.
							jThis.remove();
						}
						
						// Prevent default.
						objEvent.preventDefault();
						return( false );
					}
					);
			}
			);
				
		
		// Clear the current container and append the photos.
		jListContainer
			.empty()
			.append( jResponse )
		;
				
	} else {
		
		// There were errors.
		this.ShowAPIErrors( objResponse.ERRORS );
			
	}	
	
	// Flag the page as not busy.
	this.SetBusy( false );
}


// This uses an API-like call to upload photos in the given form.
GalleryEditPage.prototype.UploadPhotos = function(){
	var objSelf = this;
	var strName = ("uploader" + (new Date()).getTime());
	var jFrame = $( "<iframe name=\"" + strName + "\" src=\"about:blank\" />" );
	var jForm = $( "#edit-gallery" );
	var jDo = jForm.find( "input[ name = 'do' ]" );
	var jLoaderImage = jForm.find( "img.ajax-loader" );
	
	// Show loader.
	jLoaderImage.show();
	
	// Set the target of the form to post to this uploader frame
	// and to point to the asset API.
	jForm
		.attr( "target", strName )
		.attr( "enctype", "multipart/form-data" )
		.attr( "encoding", "multipart/form-data" )
	;
	
	// Point the form to the upload page action.
	jDo.val( "api.photo.upload" );
	
	// Set the CSS so the frame does not load.
	jFrame.css( "display", "none" );
	
	// Hook up the load function on the frame so that it executes when
	// the form as been posted and the server has returned (with our 
	// special API-like response).
	jFrame.load(
		function( objEvent ){
			var objUploadBody = window.frames[ strName ].document.getElementsByTagName( "body" )[ 0 ];
			var jDoc = $( objUploadBody );
			
			// Clean up the form so that it doesn't submit again as a photo upload.
			jForm.attr( "target", "_self" );
			
			// Point the form page to the edit page.
			jDo.val( "gallery.edit" );
			
			// Remove the frame. Give this a little delay; if we don't,
			// the DOM update makes the browser think forever.
			setTimeout(
				function(){
					jFrame.remove();
				},
				100
				);
			
			// Clear the input field.
			jForm.find( "input[ name = 'upload1' ]" ).val( "" );
			
			// Execute the call back method and pass back the API response.
			objSelf.UploadPhotosHandler( eval( "(" + jDoc.html() + ")" ) );
		}
		);
		
	// Attach the frame to the body. Without it being attached, the 
	// form post will not work properly.
	$( "body:first" ).append( jFrame );
		
	// Let the form process as normal.
	return;
}


// This handles the upload photo response.
GalleryEditPage.prototype.UploadPhotosHandler = function( objResponse ){
	var jPhotoIDList = $( "#photo_id_list" );
	var jForm = $( "#edit-gallery" );
	var jLoaderImage = jForm.find( "img.ajax-loader" );

	// Hide loader.
	jLoaderImage.hide();
	
	// Check to see if the upload worked.
	if ( objResponse.SUCCESS ){
	
		// Add ID's to the photo list field.
		jPhotoIDList.val( jPhotoIDList.val() + "," + objResponse.DATA.join( "," ) );
		
		// Load the photos again.
		this.LoadPhotos();					
	
	} else {
	
		// Something went wrong. Alert errors.
		this.ShowAPIErrors( objResponse.ERRORS );
			
	}
}
