/****************************************************************
 * Knerd Photo Management JavaScript Bindings and Functions
 *****************************************************************/


jQuery(document).ready(function($) {

	// setup dialog, but don't open yet.
	KJPhoto.instance.$dlgPhoto = $("#dlgPhotoManager").dialog({ // #dlgPhotoManager defined in index.php
		width: 425,
		height: 400,
		autoOpen: false,
		modal: true,
		title: "Photos",
		buttons: {
			'close': function() { $(this).dialog("close"); }
		},
		open: function() {
			KJPhoto.instance._getAndEditImages();
		}
	});
});

/**
 * Class KJPhoto
 * @class KJPhoto
 */
function KJPhoto() {
	this.kUserUploadToken = null;
	this.$dlgPhoto = null;

	this.connectorType = null;
	this.connectorID = null;

	this.loadingContent = '<p class="loading-msg">Loading</p>';
}

/**
 * set up a static reference to singleton
 * (setting it up this way for Eclipse's benefit, I know it's not optimal.)
 * @var KJPhoto
 */
KJPhoto.instance = new KJPhoto();

/**
 * Public entry point! -- other scripts call this to initiate the sequence of dialogs and bindings
 * that comprise the "photo management experience"
 *
 * @param connectorType 'person', 'band', etc...
 * @param connectorID
 * @return
 */
KJPhoto.prototype.managePhotosFor = function(connectorType, connectorID, dialogTitle) {

	this.connectorType = connectorType;
	this.connectorID   = connectorID;

	// if no dialog title is provided, use a generic default
	if (!dialogTitle || typeof(dialogTitle)=="undefined") {
		dialogTitle = "Photos";
	}

	// if dialog is already open, close it (so we can properly reset the content before re-opening)
	if (this.$dlgPhoto.dialog("isOpen")) {
		this.$dlgPhoto.dialog("close");
	}

	// open dialog
	this.$dlgPhoto.dialog("option", "title", dialogTitle);
	this.$dlgPhoto.dialog("open");
};




/**
 * Load images into inner .ajax-content <div> of the dlgPhoto
 */
KJPhoto.prototype._getAndEditImages = function() {

	// Load content from dialog file
	KJPhoto.instance.$dlgPhoto.find(".ajax-content").html(this.loadingContent).load("/scripts/photo_mgr/dlg.get-photos-generic.php",{
			connector_type: KJPhoto.instance.connectorType,
			connector_id:   KJPhoto.instance.connectorID
		},
		function() {

			// Get an upload token
			$.get("/scripts/photo_mgr/get-upload-token.php", {},
				function(json) {
					if ( !json.logged_in ) {
						warnNoLoginSession();
					}
					else if ( !json.token ) {
						// not good...
						KJPhoto.instance.$dlgPhoto.find(".ajax-content").html("<p class='error-msg'>Yikes, an error prevented us from loading this dialog. Please try again.</p>");
					}
					else {
						// Save token to an instance var
						KJPhoto.instance.kUserUploadToken = json.token;

						// knerd-buttons
						KJPhoto.instance.$dlgPhoto.find(".knerd-button").button();

						// EDIT Photo setup bindings
						KJPhoto.instance._setupEditPhotoBindings();

						// UPLOAD Photo SETUP bindings
						KJPhoto.instance._setupUploadify();
					}
				},
				'json'
			);
		}
	);
};


/**
 * Setup jquery bindings for the 'edit photo' dialog just displayed
 */
KJPhoto.prototype._setupEditPhotoBindings = function () {

	// CAPTION EDIT
	// setup in place editor for photo caption
	KJPhoto.instance.$dlgPhoto.find(".edit-caption").editable("/scripts/update-photo-title.php", {
		indicator: "Saving...",
		tooltip: "Click to edit...",
		type: 'textarea',
		submit: 'Save',
		cancel: 'Cancel',

		id: 'photo_id',
		name: 'photo_title',

		height: 'none',
		width: 'none',
		onblur: 'ignore',

		callback: function() {
			KJPhoto.instance.$dlgPhoto.find(".btn-edit-caption").show();
		},
		"onreset": function() {
			KJPhoto.instance.$dlgPhoto.find(".btn-edit-caption").show();
		}
	});

	KJPhoto.instance.$dlgPhoto.find(".btn-edit-caption").click(function() {
		$(this).parent().find(".edit-caption").click();
		$(this).hide();
	});

	// DELETE PHOTO
	KJPhoto.instance.$dlgPhoto.find(".btn-delete-photo").click(function() {

		var $delBtn = $(this);

		jConfirm("Really delete photo?", "Confirm Delete", function(resp) {
			if (resp) {
				var photoID = $delBtn.attr("id");
				var $photoContainer = $delBtn.closest(".photo-container");

				showAjaxLoad($photoContainer);

				$.get("/scripts/delete-photo.php", {
						photo_id: photoID
					},
					function(json) {
						hideAjaxLoad();
						if (json.success) {
							$photoContainer.fadeOut("slow");
						}
						else {
							if (json.message) {
								jAlert(json.message, "Error");
							} else {
								jAlert("Error: Couldn't delete photo", "Error");
							}
						}
					},
					'json'
				);
			}
		}); // end jConfirm

	}); // end .btn-delete-photo click()


	// "MAKE DEFAULT" Button bindings
	KJPhoto.instance.$dlgPhoto.find(".photo-container.is-default-photo .btn-make-default").button("disable"); // disable if already default

	KJPhoto.instance.$dlgPhoto.find(".btn-make-default").click(function() {
		var $origButton = $(this).mouseout().blur().button("disable");
		var photoID = $(this).attr("id");
		$.get("/scripts/make-photo-default.php", {
				photo_id: photoID
			},
			function(json) {
				if (json.success) {
					// show the 'default' icon and disable make-default button
					KJPhoto.instance.$dlgPhoto.find(".photo-container").removeClass("is-default-photo"); // remove from others
					$origButton.closest(".photo-container").addClass("is-default-photo"); // add to this one
				}
				else {
					var errorMsg = (json.message)? json.message : "An error occured" ;
					jAlert(errorMsg, "Error");
				}

				KJPhoto.instance.$dlgPhoto.find(".photo-container:not(.is-default-photo) .btn-make-default").button("enable"); // enable other 'make default' buttons
			},
			'json'
		);
	}); // end .btn-make-default click()

}; // end setup bindings fn


/**
 * Setup the uploadify bindings and settings for the flash file uploader
 *
 * @return
 */
KJPhoto.prototype._setupUploadify = function()
{
	var $uploadifyObj = KJPhoto.instance.$dlgPhoto.find('.upLoadifyFileInput');
	var randomID = "upload_file_input_" + (new Date()).getTime(); // the uploadify 'file' input *needs* to have an ID set.
	$uploadifyObj.attr("id",randomID);

	/// UPLOADIFY initial setup
	$uploadifyObj.uploadify({
		'uploader': '/js/uploadify.swf',
		'script':   '/scripts/photo_mgr/uploadify.php',
		onOpen: function() {
			// Event onOpen occurs each time uploadify begins to upload a new file
			$(".img-upload-ajax-spinner").show();
			return true;
		},
		onAllComplete: function(event, data) {
			// Event onAllComplete fires after all uploads have completed.

			$(".img-upload-ajax-spinner").hide(); // stop ajax spinner

			if (data.filesUploaded > 0) {
				// Only "refresh" image list if at least one image successfully uploaded
				KJPhoto.instance._getAndEditImages();
			}

			return true;
		},
		'cancelImg': '/js/cancel.png',
		'multi': true,
		'sizeLimit': '8192000', // 8MB
		'fileExt': '*.gif;*.jpeg;*.jpg;*.png;',
		'fileDesc': 'Please only upload GIF, JPG or PNG.',
		scriptData: {
			token: KJPhoto.instance.kUserUploadToken,
			connector_type: KJPhoto.instance.connectorType,
			connector_id:   KJPhoto.instance.connectorID
		},
		buttonText: "Browse",
		auto: true
	});

}; // end _setupUploadify
