// Major version of Flash required
var requiredMajorVersion = 10;
// Minor version of Flash required
var requiredMinorVersion = 0;
// Revision of Flash required
var requiredRevision = 0;

swa.sitelife.multiplePhotoUpload = function() {
	this.parentWidget = null;
	this.fileArray = [];
	this.photoKeyList = [];
	this.photoNameList = [];
	this.thisDocumentTitle = document.title;
	this.emptyTitlesError = "Photo titles cannot be empty.";
	this.imageSizeExceededErrorString = "This image is too large";
	this.imageSizeExceededError = "Please select a file under 4MB.";
	this.unsupportedFileTypeErrorString = "The image file type is not supported.";
	this.unsupportedFileTypeError =
	"The image file was of an unsupported format. Valid file Types are JPG; GIF and PNG.";
	this.badLanguageErrorString = "submission included words not permitted";
	this.badLanguageError =
	" Your title did not meet our submission guidelines due to inappropriate language. Please try again.";
	this.defaultError = "Please try again later.";
	this.titleUpdateDefaultError = "Some trip title(s) could not be updated. Please try again later.";
	this.photoUpdateDefaultError = "Some photo(s) could not be uploaded. Please try again later.";
	this.max_title_length = 50;
	this.flashWidget = null;
	this.trips = [];
	this.tripCount = 0;
	this.ccpList = [];
	this.trip = null;
	this.photo_tags = null;

	this.init = function(parent) {
		if (swaLoggedInUserId != "") { 
			this.parentWidget = parent;
			if (this.tripDoesNotExist(this.parentWidget)) {
				this.getTrips();
			}
			this.loadFlashPhotoUpload();
		}
	};
	this.getTrips = function() {
		var cck = new CustomCollectionKey("trips_" + window.swaLoggedInUserId);
		var ccp = new CustomCollectionPage(cck, 10, 1, "PositionDescending");
		var rb = new RequestBatch();
		rb.AddToRequest(ccp);
		var me = this;
		rb.BeginRequest(SITELIFE_DIRECT_PROCESS_ADDRESS, function(resp) {
			if (resp.Messages[0].Message == "ok") {
				me.trips = resp.Responses[0].CustomCollectionPage.Items
				me.tripCount = resp.Responses[0].CustomCollectionPage.NumberOfItems;
				if (me.tripCount > 10) {
					me.getTrips_fetchSubsequentBatches();
				} else {
					me.createTripSelectBox();
				}
			} else {
				//User doesnt have any trips yet.
				me.createTripSelectBox();
			}
		});
	};
	this.getTrips_fetchSubsequentBatches = function() {
		var cck = new CustomCollectionKey("trips_" + window.swaLoggedInUserId);
		for (var i = 2; i <= (Math.ceil(this.tripCount / 10)); i++) {
			this.ccpList[this.ccpList.length] = new CustomCollectionPage(cck, 10, i, "PositionDescending");
		}
		for (var j = 0; j < this.ccpList.length; j++) {
			var rb = new RequestBatch();
			var ccp = this.ccpList[j];
			rb.AddToRequest(ccp);
			var me = this;
			var responseCount = 0;
			rb.BeginRequest(SITELIFE_DIRECT_PROCESS_ADDRESS, function(resp) {
				me.trips = me.trips.concat(resp.Responses[0].CustomCollectionPage.Items);
				responseCount++;
				if (responseCount == me.ccpList.length) {
					me.createTripSelectBox();
				}
			});

		}
	};
	this.createTripSelectBox = function() {
		if (this.tripDoesNotExist(this.parentWidget)) {
			if (this.tripCount == 0) {
				$("#createTripForPhoto").show();
				$("#photoUploadForm").hide();
				$("#createNewTripLink").hide();
			} else {
				var selectHTML = "Add photos to trip: <select id='tripId' name='tripId'>";
				for (var i = 0; i < this.trips.length; i++) {
					selectHTML +=
					"<option value='" + this.trips[i].CustomItem.CustomItemKey.Key + "'>"
					    + this.trips[i].CustomItem.Name + "</option>";
				}
				selectHTML += "</select>";
				$("#photoTripSelect").html(selectHTML);
				$("#createTripForPhoto").hide();
				$("#photoUploadForm").show();
				$("#createNewTripLink").show();
			}
			if (typeof(modalName) !== 'undefined' && modalName == "photo_upload") {
				this.showModal();
			}
		}

	};
	this.loadFlashPhotoUpload = function() {
		var hasRightVersion = DetectFlashVer(requiredMajorVersion, requiredMinorVersion, requiredRevision);
		if (hasRightVersion) {  // if we've detected an acceptable version embed the flash movie
			AC_FL_RunContent('codebase', 'http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=10,0,0,0', 'width', '330', 'height', '22', 'src', '/flash/multiplefileupload', 'quality', 'high', 'pluginspage', 'http://www.adobe.com/go/getflashplayer', 'align', 'middle', 'play', 'true', 'loop', 'true', 'scale', 'showall', 'wmode', 'windowrrors', 'devicefont', 'false', 'id', 'multiplefileupload', 'bgcolor', '#ffffff', 'name', 'multiplefileupload', 'menu', 'true', 'allowFullScreen', 'false', 'allowScriptAccess', 'sameDomain', 'movie', '/flash/multiplefileupload', 'salign', '');
			this.flashWidget = document["multiplefileupload"];
		} else {  // flash is too old or we can't detect the plugin
			var alternateContent = 'This content requires the Adobe Flash Player 10. '
			    + '<a href="http://www.adobe.com/go/getflashplayer/">Get Flash</a>';
			document.write(alternateContent);
		}
	};
	//Called from Flash Widget
	this.updatePhotoInformation = function(photoKeys, photoNames) {
		this.photoNameList = photoNames;
		this.photoKeyList = photoKeys;

		if (this.tripDoesNotExist(this.parentWidget)) {
			var tripId = $("#tripId").val();
			var me = this;
			swa.sitelife.util.sendRequestBatch(new CustomItemKey(tripId), function(response) {
				me.getTrip(response.Responses[0])
			});
		} else {
			this.trip = this.parentWidget.contextWidget.trip;
			this.updatePhotoTags();
		}
	};

	this.getTrip = function (trip) {
		this.trip = new swa.sitelife.Trip(trip);
		this.updatePhotoTags();
	};

	this.tripDoesNotExist = function (widget) {
		return !(widget && widget.contextWidget && widget.contextWidget.trip);
	}

	this.updatePhotoTags = function() {
		var requestBatch = new RequestBatch();
		for (var i = 0; i < this.photoKeyList.length; i++) {
			this.photo_tags = this.trip.generateTagsForPhoto(this.photoNameList[i]);
			var photoKey = new PhotoKey(this.photoKeyList[i]);
			requestBatch.AddToRequest(new UpdatePhotoAction(photoKey, this.photoNameList[i], this.photoNameList[i], this.photo_tags, new Section("trips")));
		}
		var me = this;
		requestBatch.BeginRequest(SITELIFE_DIRECT_PROCESS_ADDRESS, function(response) {
			me.errorCheckAndAttachPhotosToTrip(response);
		});
	};

	//Called From Flash Widget
	this.updateTitles = function() {
		if (this.areTitlesEmpty()) {
			$("#photouploadError").html(this.emptyTitlesError);
			return;
		}
		var rb = new RequestBatch();
		var me = this;
		$(".photoTitle").each(function() {
			var photoKey = new PhotoKey(this.id);
			var title = this.value.substr(0, me.max_title_length);
			var photo_tags = me.trip.generateTagsForPhoto(title);
			rb.AddToRequest(new UpdatePhotoAction(photoKey, title, title, photo_tags, new Section("trips")));
		});
		var me = this;
		rb.BeginRequest(SITELIFE_DIRECT_PROCESS_ADDRESS, function(response) {
			me.errorCheckAndWrapup(response);
		});
	};

	this.attachPhotosToTrip = function() {
		var photoCollectionId = this.trip.getPhotoCollectionId();
		var requestBatch = new RequestBatch();
		for (var i = 0; i < this.photoKeyList.length; i++) {
			var photoKey = new PhotoKey(this.photoKeyList[i]);
			var updatedPhotoCollection = new InsertIntoCollectionAction(new CustomCollectionKey(photoCollectionId), photoKey, 1);
			requestBatch.AddToRequest(updatedPhotoCollection);
		}
		var me = this;
		requestBatch.BeginRequest(SITELIFE_DIRECT_PROCESS_ADDRESS, function(response) {
			me.errorCheckAndUpdateTitles(response);
		});
	};

	this.showTitleForm = function() {
		this.clearFileLists();
		this.allowTitleUpdate();
		this.loadPhotoTitleForm();
	};

	this.loadPhotoTitleForm = function() {
		var rb = new RequestBatch();
		for (var i = 0; i < this.photoKeyList.length; i++) {
			var photoKey = new PhotoKey(this.photoKeyList[i]);
			rb.AddToRequest(photoKey);
		}
		var me = this;
		rb.BeginRequest(SITELIFE_DIRECT_PROCESS_ADDRESS, function(response) {
			me.populatePhotoTitleForm(response);
		});
	};

	this.populatePhotoTitleForm = function(response) {
		var htmlTable = this.createPhotoTitleTable(response);
		$("#fileList").append(htmlTable);
	};

	this.createPhotoTitleTable = function(response) {
		var htmlTable = "<table >";
		htmlTable += "<tr><th></th><th> Photo Title</th></tr>";
		for (var i = 0; i < response.Responses.length; i++) {
			var photo = response.Responses[i];
			var thumbnailUrl = photo.Photo.Image.Small;
			var photoKey = photo.Photo.PhotoKey.Key;
			var thumbnail = "<img  src='" + thumbnailUrl + "'/>";
			var titleInput = "<input type ='text' id=" + photoKey + " class ='photoTitle' value='"
			    + photo.Photo.Title + "' maxlength=" + this.max_title_length + " />";
			htmlTable += "<tr><td>" + thumbnail + "</td><td>" + titleInput + "</td></tr>";
		}
		htmlTable += "</table>";
		return htmlTable;
	};

	this.allowTitleUpdate = function() {
		this.flashWidget.allowTitleUpdate();
	};

	this.clearFileLists = function() {
		this.fileArray = [];
		if (this.flashWidget != null && this.flashWidget.removeAllFiles) {
			this.flashWidget.removeAllFiles();
		}
		$("#fileList li").remove();
		$("#fileList table").remove();
		this.hideSpinner();
	};

	this.showModal = function() {
		$("#addPhotoModalBackground").show();
		$("#addPhotoModal").show();
	};

	this.closePhotoUploadModal = function() {
		this.clearFileLists();
		this.clearMessages();
		$("#addPhotoModalBackground").css("display", "none");
		$("#addPhotoModal").css("display", "none");
	};

	this.removeFile = function(index) {
		this.flashWidget.removeFile(index);
		this.fileArray.splice(index, 1);
		this.loadSelectedFiles(this.fileArray);
		if (! this.fileArray.length) {
			this.flashWidget.disableUpload();
		}
	};

	this.handleSitelifeError = function(response, errorType, fileName) {
		var message = "";
		if (errorType == "UPLOAD") {
			message += this.getFileUploadErrors(response, fileName);
			;
		}
		if (errorType == "UPDATE_TITLE") {
			if (this.containsError(response, this.badLanguageErrorString)) {
				message += this.badLanguageError;
			} else {
				message += this.titleUpdateDefaultError;
			}
		}
		if (errorType == "UPDATE_PHOTO") {
			message += this.photoUpdateDefaultError;
		}
		$("#photouploadError").append(message);
	};

	this.getFileUploadErrors = function(response, fileName) {
		var photoName = fileName || "";
		var message = "<p>Could not upload file " + photoName + ". ";
		if (this.containsError(response, this.unsupportedFileTypeErrorString)) {
			message += (this.unsupportedFileTypeErrorString + "</p>");
		} else if (this.containsError(response, this.imageSizeExceededErrorString)) {
			message += (this.imageSizeExceededError + "</p>");
		} else {
			message += this.defaultError + "</p>";
		}
		return message;
	};

	this.areTitlesEmpty = function() {
		var areTitlesEmpty = false;
		$(".photoTitle").each(function(index) {
			if (this.value == "") {
				areTitlesEmpty = true;
			}
		});
		return areTitlesEmpty;
	};

	this.clearMessages = function() {
		$("#photouploadError").html("");
		$("#photouploadWarning").html("");
	};

	this.isResponseNotOk = function(response) {
		return response.Messages[0].Message != "ok";
	};

	this.errorCheckAndWrapup = function(response) {
		if (this.isResponseNotOk(response)) {
			this.handleSitelifeError(response.Messages[0].Message, "UPDATE_TITLE");

		} else {
			this.closePhotoUploadModal();
			window.location.reload();
		}
	};

	this.errorCheckAndUpdateTitles = function(response) {
		if (this.isResponseNotOk(response)) {
			this.handleSitelifeError("", "UPDATE_PHOTO");
		} else {
			this.hideSpinner();
			this.showTitleForm();
		}
	};

	this.errorCheckAndAttachPhotosToTrip = function(response) {
		if (this.isResponseNotOk(response)) {
			this.handleSitelifeError("", "UPDATE_PHOTO");
		} else {
			this.attachPhotosToTrip();
		}
	};

	this.hideSpinner = function() {
		$('#loading_indicator').hide();
	};
	this.containsError = function(response, errorMessage) {
		return response.indexOf(errorMessage) != -1;
	};
	this.loadSelectedFiles = function(fileList) {
		this.fileArray = fileList;
		$("#fileList li").remove();
		for (var i = 0; i < this.fileArray.length; i++) {
			$("#fileList ul").append("<li style='padding-top:8px;'>" + this.fileArray[i].name
			    + " &nbsp; <a class ='hyperlink' onclick='multipleFileUploadWidget.removeFile(" + i
			    + ")'>[remove]</a></li>"); // UGGGLYYYY- figure out some way of getting the parent object of flashInterface and let us know - Udit\Sarah
		}
	};
	this.resetPageTitle = function() {
		document.title = this.thisDocumentTitle;
	};

};

swa.sitelife.multiplePhotoUpload.prototype.flashInterface = function() {
	return {
		photoListSizeExceeded : "More than 10 simultaneous File uploads are not permitted.",

		getSitelifeServerUrl : function() {
			return SITELIFE_SERVER_URL;
		},

		getAtCookie : function() {
			var cookie = document.cookie;
			var index1 = cookie.indexOf("at=") + 3;
			var index2 = cookie.indexOf(";", index1);
			return  cookie.substring(index1, index2);
		},
		getUserKey : function() {
			return window.swaLoggedInUserId;
		},

		getPhotoGalleryKey : function() {
			return window.PHOTO_GALLERY_KEY;
		},

		showSpinner : function() {
			$('#loading_indicator').show();
		},
		handleFileCountExceededWarning : function() {
			$("#photouploadWarning").html(this.photoListSizeExceeded);
		}
	};
}();

