/* Copyright 2009 Palm, Inc.  All rights reserved. */

Photos.Scene.Fullscreen = Class.create(Photos.Scene.Base,
					Photos.Common.AccountAdjustment, {
	initialize: function($super, passedArg) {
		$super(passedArg);
		this.uiTimeoutSeconds = 5;
		this.deferActivate = passedArg.deferActivate;
	},

	shareFamilyAppId: 'com.palm.app.connect',
	shareFamilyAppText: $L("Share with My Group"),

	setup: function($super) {
		$super();
		Mojo.Log.info("Starting orientation",
			Mojo.Controller.getAppController(
				).getScreenOrientation());

		this.currentUrl = "";
		this.currentName = "";
		this.tempFileCounter = 0;
		this.inDrag = false;
		this.inGesture = false;
		this.idleTimeoutRestMS = 10;

		this.flipviewElement =
				this.controller.get('image_flipview_full');
		this.flipviewElement.style.height =
			Mojo.Environment.DeviceInfo.screenHeight + "px";
		this.flipviewElement.style.width =
			Mojo.Environment.DeviceInfo.screenWidth + "px";
		this.contactCropSize = Math.min(
			256, Mojo.Environment.DeviceInfo.screenWidth);
		this.extractfsParams = "720:720:3";

		// These numbers are the max numbers for tv res images.
		// No sense in scaling up twice.
		this.controller.setupWidget(this.flipviewElement.id, {
			extractfsParams: this.extractfsParams,
			highResolutionTimeout: 0.4
		}, {
			background: "black",
			onLeftFunction:
				this.sceneModel.goLeft.bind(this.sceneModel),
			onRightFunction:
				this.sceneModel.goRight.bind(this.sceneModel)
		});

		this.sceneModel.setCallbacks(
			this.providedCenterUrl.bind(this),
			this.providedLeftUrl.bind(this),
			this.providedRightUrl.bind(this));

		this.autoListen(this.flipviewElement, Mojo.Event.tap,
			this.handleTap.bind(this));
		this.autoListen(this.flipviewElement,
			Mojo.Event.imageViewChanged,
			this.flipViewChanged.bind(this));
		this.autoListen(this.flipviewElement, Mojo.Event.dragStart,
			this.dragStart.bind(this), true);
		this.autoListen(this.flipviewElement, Mojo.Event.dragEnd,
			this.dragEnd.bind(this), true);
		this.autoListen(this.controller.document, 'gesturestart',
			this.gestureStart.bind(this), true);
		this.autoListen(this.controller.document, 'gestureend',
			this.gestureEnd.bind(this), true);

		this.menuModel = {visible: true, items: []};

		this.controller.setupWidget(Mojo.Menu.commandMenu, {
			spacerHeight: 0,
			menuClass: 'no-fade'
		}, this.menuModel);

		this.uiVisible = true;

		this.spinnerModel = {spinning: false};
		this.controller.setupWidget('spinner',
				{spinnerSize: 'large'}, this.spinnerModel);
		this.controller.get('spinner').style.marginTop =
				(this.controller.window.innerHeight / 2) + "px";

		// Dialog widget setup
		this.controller.setupWidget('userField', {
			hintText: $L("Enter username"),
			textReplacement: false,
			focus: true
		});
		this.controller.setupWidget('passField', {
			hintText: $L('Enter password')
		});

		this.autoListen(this.controller.window, 'resize',
			this.handleWindowResize.bind(this));

		this.controller.get('fullscreen_album_description').hide();
		function updateDescription(text) {
			if (text) {
				this.controller.get(
					'fullscreen_album_description').show();
			}
			Mojo.Log.info("Got photo description > " + text);
			this.controller.get(
				'fullscreen_album_description').update(
					text.escapeHTML());
		}

		function updateName(text) {
			Mojo.Log.info("Got album name > " + text);
			this.albumName = text.escapeHTML();
			this.controller.get('fullscreen_album_name').update(
				this.albumName);
		}

		this.albumName = "";
		this.sceneModel.getDescription(updateDescription.bind(this));
		this.sceneModel.getName(updateName.bind(this));

		if (this.sceneModel.headerTapped) {
			this.autoListen(this.controller.get('header'),
				Mojo.Event.tap, this.headerTapped.bind(this));
		}


		this.accountItem = {
			label: $L("Upload..."),
			disabled: true,
			command: 'new-account'
		};

		this.shareModel = {
			items: [{
				label: $L('Assign to contact'),
				command: 'share-contact',
				disabled: !this.sceneModel.canAssignToContact()
			},{
				label: $L('Set wallpaper'),
				command: 'share-wallpaper',
				disabled: !this.sceneModel.canSetWallpaper()
			},{
				label: $L('Share via email'),
				command: 'share-email',
				disabled: !this.sceneModel.canEmail()
			},{
				label: $L('Share via MMS'),
				command: 'share-messaging',
				disabled: !this.sceneModel.canMMS()
			}, this.accountItem]
		};

		this.controller.setupWidget(
			'share-menu', null, this.shareModel);

		this.controller.serviceRequest('palm://com.palm.accounts', {
			method: "getAllAccountsForService",
			parameters: {subscribe: true, service: "PHOTO_UPLOAD"},
			onSuccess: this.getAccountsOkay.bind(this),
			onFailure: this.getAccountsFail.bind(this)
		});

		this.startHideTimer();
		this.potentialStartIdle();
		this.checkForAndAddFamilyApp();
	},

	checkForAndAddFamilyApp: function() {
		var self = this;

		function installFamilyLaunchPoint() {
			self.shareModel.items.splice(4, 0, {
				label: self.shareFamilyAppText,
				command: 'share-family',
				disabled: !self.sceneModel.canShareFamily()
			});
			self.controller.modelChanged(self.shareModel);
		}

		function gotLaunchPoints(response) {
			var apps = response.launchPoints;
			var found = !apps.every(function(app) {
				if (app.appId === self.shareFamilyAppId) {
					return false;
				}
				return true;
			});

			if (found) {
				installFamilyLaunchPoint();
			}
		}

		this.controller.serviceRequest(
			'palm://com.palm.applicationManager', {
				method: 'listLaunchPoints',
				parameters: {},
				onSuccess: gotLaunchPoints
		});
	},

	headerTapped: function() {
		this.sceneModel.headerTapped(this.controller.stageController);
	},

	dragStart: function() {
		this.inDrag = true;
		this.stopIdle();
		this.stopHideTimer();
	},

	dragEnd: function() {
		this.inDrag = false;
		this.startHideTimer();
		this.potentialStartIdle();
	},

	gestureStart: function() {
		this.stopIdle();
		this.inGesture = true;
	},

	gestureEnd: function() {
		this.inGesture = false;
		this.potentialStartIdle();
	},

	stopIdle: function() {
		if (!this.idleTimeout) {
			return;
		}

		this.sceneModel.idleStop();
		this.controller.window.clearTimeout(this.idleTimeout);
		this.idleTimeout = undefined;
	},

	potentialStartIdle: function() {
		if (this.inGesture || this.inDrag || this.idleTimeout) {
			return;
		}

		this.idleTimeout = this.controller.window.setTimeout(
			this.sceneModel.idleStart.bind(this.sceneModel),
			this.idleTimeoutRestMS);
	},

	infoTapped: function(event) {
		// restart hide timeout for every tap on the info pane.
		this.refreshUITimer();
	},

	startHideTimer: function() {
		this.stopHideTimer();
		this.hideTimeout = this.controller.window.setTimeout(
			this.hideUI.bind(this), this.uiTimeoutSeconds * 1000);
	},

	stopHideTimer: function() {
		if (!this.hideTimeout) {
			return;
		}

		this.controller.window.clearTimeout(this.hideTimeout);
		delete this.hideTimeout;
	},

	refreshUITimer: function() {
		if (this.inDrag) {
			return;
		}

		if (this.hideTimeout) {
			this.startHideTimer();
		}
	},

	aboutToActivate: function($super, callback) {
		$super(callback);
		this.controller.enableFullScreenMode(true);
		this.orientateControls(
			Mojo.Controller.getAppController(
				).getScreenOrientation());
	},

	getAccountsOkay: function(response) {
		Mojo.Log.info("Got photo accounts:", Object.toJSON(response));
		this.buildMenuItems(response.list);
	},

	getAccountsFail: function(response) {
		Mojo.Log.info("Failed to get photo accounts.");
		this.buildMenuItems([]);
	},

	buildMenuItems: function(accounts) {
		this.morphAccounts(accounts);
		var subItems = [];
		for (var i = 0; i < accounts.length; i++) {
			subItems.push({
				label: accounts[i].displayLogin,
				domain: accounts[i].domain,
				icon: accounts[i].domain,
				disabled: !this.sceneModel.canUpload(),
				accountID: accounts[i].accountId,
				command: "upload|" + accounts[i].domain +
						"|" + accounts[i].accountId
			});
		}

		if (!subItems.length) {
			// if we can upload and we don't have a prefix,
			// meaning a original app launch, go ahead and enable
			// the Upload... item, otherwise it won't be localized.
			this.accountItem = {
				label: $L("Upload..."),
				disabled: !(this.sceneModel.canUpload() &&
						!this.templatePrefix),
				command: 'new-account'
			};
		} else {
			this.accountItem = {
				label: $L("Upload"),
				items: subItems,
				disabled: !this.sceneModel.canUpload()
			};
		}
		
		this.shareModel.items[this.shareModel.items.length - 1] =
			this.accountItem;

		try {
			this.controller.modelChanged(this.shareModel);
		} catch (e) {
			// not a big deal, the menu was not open, so model
			// changed had no effect.
		}
	},

	activate: function($super, params) {
		$super(params);
		Mojo.Log.info("Activate params:", Object.toJSON(params));
		this.isActive = true;

		if (this.deferActivate) {
			delete this.deferActivate;
			this.controller.stageController.activate();
		}

		if (params && params.personId) {
			this.handleContactSelected(params);
		}
	},

	deactivate: function() {
		this.isActive = false;
		this.orientateControls("up");
	},

	providedLeftUrl: function(url, thumbUrl, name) {
		// it is possible for the model to provide urls faster than
		// we call widget setup
		if (!this.flipviewElement.mojo) {
			return;
		}
		this.flipviewElement.mojo.leftUrlProvided(url, thumbUrl);
	},

	providedRightUrl: function(url, thumbUrl, name) {
		// it is possible for the model to provide urls faster than
		// we call widget setup
		if (!this.flipviewElement.mojo) {
			return;
		}
		this.flipviewElement.mojo.rightUrlProvided(url, thumbUrl);
	},

	providedCenterUrl: function(url, thumbUrl, name) {
		// it is possible for the model to provide urls faster than
		// we call widget setup
		if (!this.flipviewElement.mojo) {
			return;
		}

		if (this.spinnerModel.spinning) {
			this.spinnerModel.spinning = false;
			this.controller.modelChanged(this.spinnerModel);
			this.controller.get('delete-image-div').style.display = "none";
		}

		Mojo.Log.info("providing center url to widget", url);
		this.flipviewElement.mojo.centerUrlProvided(url, thumbUrl);
		Mojo.Log.info("providing name: ", name);
		this.currentName = name;
		this.updateView();
	},

	updateView: function() {
		if (this.sceneModel.getTotal() <= 0) {
			return;
		}

		this.controller.get("album_count").update(
			$L("#{index}/#{total}").interpolate({
				index: this.sceneModel.getIndex() + 1,
				total: this.sceneModel.getTotal()
		}).escapeHTML());

		this.menuModel.items = [{
			iconPath: this.params.applicationRoot +
						'images/menu-icon-send.png',
			submenu: 'share-menu'
		},{}, (this.sceneModel.canComment() ? {
			iconPath: this.params.applicationRoot +
						'images/menu-icon-comment.png',
			command: 'menu-comment'
		} : {}), {},{
			iconPath: this.params.applicationRoot +
						'images/menu-icon-delete.png',
			command: 'menu-delete',
			disabled: !this.sceneModel.canRemove()
		}];

		this.controller.modelChanged(this.menuModel);
	},

	orientateControls: function(dir) {
		if (this.orientation == dir) {
			Mojo.Log.info("Same dir, ignoring orientation.");
			return;
		}
		
		this.orientation = dir;
		this.controller.stageController.setWindowOrientation(dir);
	},

	orientationChanged: function(dir) {
		Mojo.Log.info("Changing orientation.", dir);

		if (!this.isActive) {
			Mojo.Log.info("Not active, ignoring orientation.");
			return;
		}

		this.orientateControls(dir);
	},

	handleWindowResize: function(event) {
		Mojo.Log.info("Window resize!", 
					this.controller.window.innerWidth,
					this.controller.window.innerHeight);
		if (this.flipviewElement && this.flipviewElement.mojo) {
			this.flipviewElement.mojo.manualSize(
					this.controller.window.innerWidth,
					this.controller.window.innerHeight);
		}
		this.controller.get('spinner').style.marginTop =
				(this.controller.window.innerHeight / 2) + "px";
	},

	handleShare: function(event) {
		this.stopHideTimer();
/*
		if (!this.testBannerKey)
		{
		Photos.Common.newFeedback(
				this.controller,
				this.controller.get('feedback'),
				$L("Uploading nonsense long long long"),
				"facebook",
				this.templatePrefix);
		Photos.Common.newFeedback(
				this.controller,
				this.controller.get('feedback'),
				$L("Uploading nonsense long long long"),
				"contact",
				this.templatePrefix);
		this.testBannerKey = Photos.Common.newFeedback(
				this.controller,
				this.controller.get('feedback'),
				"Uploading nonsense raahahahah",
				"photobucket",
				this.templatePrefix);
		Photos.Common.newFeedback(
				this.controller,
				this.controller.get('feedback'),
				"Setting nonsense",
				"wallpaper",
				this.templatePrefix);
		}
		else
		{
		Photos.Common.deleteFeedback(this.testBannerKey, $L("Login required."));
		delete this.testBannerKey;
		}
		*/
	},

	nextTempFile: function() {
		var ret = "/media/internal/.photos-temp-" +
			this.tempFileCounter + ".jpg";
		this.tempFileCounter = ((this.tempFileCounter + 1) % 30);
		return ret;
	},

	convertIfNecessary: function(originalOkay, okay, fail) {
		// mms and uploads really only accept jpegs, however
		// emails can, so we accept the original in that case.
		if (Photos.Common.isMediaSynced(this.currentUrl) ||
			(!originalOkay &&
				(this.currentUrl.endsWith(".png") ||
				this.currentUrl.endsWith(".bmp")))) {
			var path = this.nextTempFile();
			this.controller.serviceRequest(
				'palm://com.palm.systemservice/', {
				method: 'wallpaper/convert',
				parameters: {
					source: this.flipviewElement.mojo.getCurrentParams().sourceImage,
					dest: path,
					destType: "jpg"
				},
				onSuccess: okay.curry(path),
				onFailure: fail
			});
		} else {
			okay(this.currentUrl);
		}
	},

	handleUpload: function(accountId, accountType) {
		var bannerKey = Photos.Common.newFeedback(
				this.controller,
				this.controller.get('feedback'),
				$L("Uploading #{file}").interpolate(
					{file: this.translateName(
					this.currentUrl, this.currentName)}),
				accountType,
				this.templatePrefix);

		function uploadFailed(accountID, domain, response) {
			Mojo.Log.error("We failed upload " +
				Object.toJSON(response));

			if (!response || !response.errorCode ||
				response.errorCode != "loginRequired") {
				Photos.Common.deleteFeedback(
					bannerKey, $L("Upload failed"));

				this.controller.showAlertDialog({
					onChoose: this.handleDialogTap.bind(this),
					title: "",
					message: $L("Failed to upload photo"),
					choices: [{
						label: $L("Close"),
						type: "dismiss"
					}]
				});
				return;
			}

			Photos.Common.deleteFeedback(
				bannerKey, $L("Login required"));

			this.controller.showDialog({
				template: 'fullscreen/login',
				assistant: new Photos.Scene.LoginAssistant(
							this, accountID, domain)
			});
		}

		function sendImage(path) {
			this.controller.serviceRequest(
				'palm://com.palm.photos', {
				method: 'upload',
				parameters: {
					accountId: accountId,
					path: path
				},
				onSuccess: uploadOkay.bind(this),
				onFailure: uploadFailed.bind(
						this, accountId, accountType)
			});
		}

		this.convertIfNecessary(false,
			sendImage.bind(this), uploadFailed.bind(this));

		function uploadOkay(response) {
			Photos.Common.deleteFeedback(
				bannerKey, $L("Upload complete"));
		}
	},

	handleDialogTap: function() {
	},

	handleShareWithFamily: function() {
		function attachImage(path) {
			this.controller.serviceRequest(
				'palm://com.palm.applicationManager', {
				method: 'open',
				parameters: {
					id: this.shareFamilyAppId,
					params: {"attachment": path}
				}
			});
		}

		function convertFailed(response) {
			Mojo.Log.error("Failed to convert image: " +
				Object.toJSON(response));
		}

		this.convertIfNecessary(false,
			attachImage.bind(this), convertFailed.bind(this));
	},
	
	handleCommand: function($super, event) {
		$super(event);

		if (event.type != Mojo.Event.command) {
			return;
		}

		switch (event.command) {
		case 'menu-delete':
			this.handleConfirmDelete();
			event.stop();
			break;
		case 'menu-share':
			// may still need to disable hide ui timer.
			this.handleShare();
			event.stop();
			break;
		case 'menu-comment':
			//this.runTest();
			if (this.sceneModel.canComment()) {
				this.sceneModel.viewComments(
					this.pushWithTemplate.bind(this, null));
			}
			break;
		case 'share-wallpaper':
			this.handleSetAsWallpaper();
			break;
		case 'share-family':
			this.handleShareWithFamily();
			break;
		case 'share-contact':
			this.handleAssignToContact();
			break;
		case 'share-messaging':
			this.handleSendViaMessaging();
			break;
		case 'share-email':
			this.handleAttachToEmail();
			break;
		case 'new-account':
			this.pushWithTemplate(null, 'accounts');
			break;
		default:
			var value = event.command;
			if (!value || !value.startsWith("upload")) {
				break;
			}

			var accountType = value.split("|")[1];
			var accountId = value.split("|")[2];
			this.handleUpload(accountId, accountType);
			break;
		}
	},

	handleAssignToContact: function() {
		if (this.settingContactPicture) {
			return;
		}
		this.controller.stageController.pushScene({
			appId: "com.palm.app.contacts",
			name: "list"
		});
	},

	handleContactSelected: function(params) {
		Mojo.Log.info("Contact selected", Object.toJSON(params));
		if (!params || !params.personId) {
			return;
		}

		var path = this.flipviewElement.mojo.getCurrentParams().sourceImage;
		this.pushWithTemplate(null, {
			name: 'cropscale',
			disableSceneScroller: true
		}, {
			model: new Photos.Model.Cropscale(
				$L("Assign to contact"),
				this.contactCropSize, this.contactCropSize,
				path, true,
				this.contactCropAccepted.bind(
					this, params.personId, path))
		});
	},

	contactCropAccepted: function(
				contactID, url, cropParams, fullCropParams) {
		this.settingContactPicture = true;
		var key = Photos.Common.newFeedback(
				this.controller,
				this.controller.get('feedback'),
				$L("Setting contact picture"),
				"contact",
				this.templatePrefix);
		this.controller.stageController.popScenesTo('fullscreen');

		function convertedImageOkay(response) {
			this.controller.serviceRequest(
				'palm://com.palm.contacts', {
				method: 'savePersonPicture',
				parameters: {
					personId: contactID,
					path: tempPath,
					cropInfo: {window: {
					focusX: 0.5,
					focusY: 0.5,
					scale: 1.0,
					suggestedXSize: this.contactCropSize,
					suggestedYSize: this.contactCropSize
					}
				}},
				onSuccess: assignedContactOkay.bind(this),
				onFailure: assignedContactFail.bind(this)
			});
		}

		function assignedContactOkay(response) {
			Mojo.Log.info("Assign to contact okay!");
			Photos.Common.deleteFeedback(
					key, $L("Contact picture set"));
			delete this.settingContactPicture;
		}

		function assignedContactFail(response) {
			Mojo.Log.error("Assign to contact failed!",
						Object.toJSON(response));
			Photos.Common.deleteFeedback(
					key, $L("Assign to contact failed"));
			delete this.settingContactPicture;
		}

		var tempPath = "/tmp/contact-temp.jpg";
		this.controller.serviceRequest(
			'palm://com.palm.systemservice/', {
			method: 'wallpaper/convert',
			parameters: {
				source: url,
				dest: tempPath,
				destType: "jpg",
				scale: cropParams.scale,
				focusX: cropParams.focusX,
				focusY: cropParams.focusY
			},
			onSuccess: convertedImageOkay.bind(this),
			onFailure: assignedContactFail.bind(this)
		});
	},

	handleSetAsWallpaper: function() {
		if (this.settingWallpaper) {
			Mojo.Log.error("Cannot set wallpaper two at once.");
			return;
		}
		var path = this.flipviewElement.mojo.getCurrentParams().sourceImage;
		this.pushWithTemplate(null, {
			name: 'cropscale',
			disableSceneScroller: true
		}, {
			cameFromFullScreen: true,
			model: new Photos.Model.Cropscale(
				$L("Set wallpaper"),
				Mojo.Environment.DeviceInfo.screenWidth - 2,
				Mojo.Environment.DeviceInfo.screenHeight - 1,
				path, true,
				this.wallpaperAccepted.bind(this, path))
		});
	},

	wallpaperAccepted: function(url, cropParams) {
		this.settingWallpaper = true;
		var key = Photos.Common.newFeedback(
				this.controller,
				this.controller.get('feedback'),
				$L("Setting wallpaper"),
				"wallpaper",
				this.templatePrefix);
		this.controller.stageController.popScene();

		function convertedWallpaperOkay(response) {
			this.controller.serviceRequest(
				'palm://com.palm.systemservice/', {
				method: 'wallpaper/importWallpaper',
				parameters: {
					target: tempPath,
					scale: 1.0,
					focusX: 0.5,
					focusY: 0.5
				},
				onSuccess: importedWallpaperOkay.bind(this),
				onFailure: assignedWallpaperFail.bind(this)
			});
		}

		function importedWallpaperOkay(response) {
			this.controller.serviceRequest(
				'palm://com.palm.systemservice/', {
				method: 'setPreferences',
				parameters: {wallpaper: response.wallpaper},
				onSuccess: assignedWallpaperOkay.bind(this),
				onFailure: assignedWallpaperFail.bind(this)
			});
		}

		function assignedWallpaperOkay(response) {
			Mojo.Log.info("Assign to wallpaper okay");
			Photos.Common.deleteFeedback(key, $L("Wallpaper set"));
			delete this.settingWallpaper;
		}

		function assignedWallpaperFail(response) {
			Mojo.Log.error("Assign to wallpaper failed " +
						Object.toJSON(response));
			Photos.Common.deleteFeedback(key,
						$L("Failed to set wallpaper"));
			delete this.settingWallpaper;
		}

		var tempPath = "/tmp/wallpaper-temp.jpg";
		this.controller.serviceRequest(
			'palm://com.palm.systemservice/', {
			method: 'wallpaper/convert',
			parameters: {
				source: url,
				dest: tempPath,
				destType: "jpg",
				scale: cropParams.scale,
				focusX: cropParams.focusX,
				focusY: cropParams.focusY
			},
			onSuccess: convertedWallpaperOkay.bind(this),
			onFailure: assignedWallpaperFail.bind(this)
		});

	},

	translateName: function(url, name) {
		if (Photos.Common.isMediaSynced(url)) {
			// maybe move this to the local model..
			return $L("#{albumName} #{index}.jpg").interpolate({
				albumName: this.albumName,
				index: this.sceneModel.getIndex() + 1
			});
		} else if (name) {
			return name;
		} else if (url.lastIndexOf('/') >= 0) {
			// no name from the model, fall back to the file
			// basename provided
			return url.substr(url.lastIndexOf('/') + 1);
		} else {
			// weird url provided...
			Mojo.Log.error("We couldn't find a name for image!",
								url, name);
			return "";
		}
	},

	handleAttachToEmail: function() {

		function attachImage(path) {
			this.controller.serviceRequest(
				'palm://com.palm.applicationManager', {
				method: 'open',
				parameters: {
				id: 'com.palm.app.email',
					params: {
					recipients: [],
					attachments: [{
					fullPath: path,
					displayName: this.translateName(
						this.currentUrl,
						this.currentName)
					}]
				}}
			});
		}

		function convertFailed(response) {
			Mojo.Log.error("Failed to convert image: " +
				Object.toJSON(response));
		}

		this.convertIfNecessary(true,
			attachImage.bind(this), convertFailed.bind(this));
	},

	handleSendViaMessaging: function() {

		function attachImage(path) {
			this.controller.serviceRequest(
				'palm://com.palm.applicationManager', {
				method: 'open',
				parameters: {
					id: 'com.palm.app.messaging',
					params: {"attachment": path}
				}
			});
		}

		function convertFailed(response) {
			Mojo.Log.error("Failed to convert image: " +
				Object.toJSON(response));
		}

		this.convertIfNecessary(false,
			attachImage.bind(this), convertFailed.bind(this));
	},

	handleConfirmDelete: function() {
		if (this.deleteRequest) {
			Mojo.Log.error("Delete in progress already.");
			return;
		}

		var self = this;
		this.deleteRequest = true;
		var deleteUrl = this.currentUrl;
		var deleteStartTotal = this.sceneModel.getTotal();
		var deleteStartIndex = this.sceneModel.getIndex();
		var deleteElement = this.controller.get('delete-image-div');

		function deleteResult(response) {
			delete self.deleteRequest;
			self.spinnerModel.spinning = false;
			self.controller.modelChanged(self.spinnerModel);
			deleteElement.style.display = "none";
			self.updateView();

			if (!response.returnValue) {
				Mojo.Log.info("Delete failed!");

				self.controller.showAlertDialog({
					onChoose: function(){},
					title: $L("Delete image failed"),
					message: "",
					choices: [{
						label: $L("Close"),
						type: 'dismiss'
					}]
				});
			} else if (deleteStartTotal <= 1) {
				var scene = self.sceneModel.emptyScene();
				if (scene) {
					self.controller.stageController.popScenesTo(scene);
				}
			}
		}

		function handleDelete(value) {
			self.startHideTimer();

			if (value !== "confirmed") {
				delete self.deleteRequest;
				return;
			}

			self.sceneModel.remove(deleteStartIndex);
			if (((deleteStartIndex + 1) == deleteStartTotal) &&
						(deleteStartIndex > 0)) {
				self.sceneModel.jumpTo(deleteStartIndex - 1);
			}
			self.spinnerModel.spinning = true;
			self.controller.modelChanged(self.spinnerModel);
			deleteElement.style.display = "block";
			self.deleteRequest = Photos.Service.deleteFile(
				deleteUrl, deleteResult, self.controller);
		}

		this.stopHideTimer();
		this.controller.showAlertDialog({
			onChoose: handleDelete,
			title: $L("Delete image?"),
			message: $L("This action cannot be undone."),
			choices: [{
				label: $L("Delete"),
				value: "confirmed",
				type: 'negative'
			},{
				label: $L("Cancel"),
				value: "cancelled",
				type: 'dismiss'
			}]
		});
	},

	handleTap: function(event) {
		if (event.count != 1) {
			return;
		}

		event.stop();
		
		if (this.uiVisible) {
			this.hideUI();
		} else {
			this.showUI();
		}
	},

	showUI: function() {
		this.uiVisible = true;
		this.controller.setMenuVisible(Mojo.Menu.commandMenu, true);
		this.controller.get('header').show();
		this.startHideTimer();
	},

	hideUI: function() {
		this.stopHideTimer();
		this.controller.setMenuVisible(Mojo.Menu.commandMenu, false);
		this.controller.get('header').hide();
		this.uiVisible = false;
	},

	flipViewChanged: function(event) {
		Mojo.Log.info("Image view changed " + Object.toJSON(event));
		if (event.url == this.currentUrl) {
			return;
		}

		this.currentUrl = event.url;
		this.cropParams = this.flipviewElement.mojo.getCurrentParams();
		if (event.error) {
			Mojo.Log.error("File was corrupt: " + event.url);
		}
		this.refreshUITimer();
		this.ready();
	},

	cleanup: function($super) {
		$super();
		this.sceneModel.cleanup();
		this.stopHideTimer();
	}
});

Photos.Scene.LoginAssistant = Class.create({
	initialize: function(sceneAssistant, accountID, domain) {
		this.assistant = sceneAssistant;
		this.controller = sceneAssistant.controller;
		this.accountID = accountID;
		this.domain = domain;
	},

	setup: function(widget) {
		this.widget = widget;
		this.controller.get('submitButton').addEventListener(
			Mojo.Event.tap,
			this.handleSubmit.bindAsEventListener(this));
		this.controller.get('cancelButton').addEventListener(
			Mojo.Event.tap,
			this.handleCancel.bindAsEventListener(this));
	},

	cleanup: function() {
		if (this.request) {
			Mojo.Log.info("Cancelling request to login.");
			this.request.cancel();
			this.request = undefined;
		}
	},

	handleCancel: function() {
		this.widget.mojo.close();
	},

	handleSubmit: function() {
		this.request = this.service.login(this.controller,
			this.controller.get('userField').mojo.getValue(),
			this.controller.get('passField').mojo.getValue(),
			this.loginOkay.bind(this),
			this.loginFail.bind(this));

	},

	loginOkay: function(response) {
		Mojo.Log.info("Login okay");
		this.widget.mojo.close();
		this.assistant.handleUpload.bind(this.assistant)(this.service, this.domain);
	},

	loginFail: function(response) {
		Mojo.Log.info("Failed to login");
		this.controller.showAlertDialog({
			onChoose: this.dialogClick.bind(this), 
			title: $L("Failed to login"),
			message: response.errorText,
			choices: [{label: $L("Close"), type: "dismiss"}]
		});
	},

	dialogClick: function() {
	}
});

