// Rails notes

// This is the handlers.js file from swfupload's application demo

// All image paths are changed from relative to absolute

// Example:
//   AddImage("images/" + image_name);  ->  AddImage("/images/" + image_name);

// Images from the swfupload demo are saved in #{RAILS_ROOT}/public/images

// uploadSuccess was changed
// The line: AddImage("thumbnail.php?id=" + serverData);
// was changed to: AddImage(serverData);
// The rails photo controller should return a text string
// containing the full URL to the thumbnail

// called when the flash button loads
function swfUploadLoaded() {
	// needs to exist
}


// called as the file dialog begins opening
function fileDialogStart() {
	// needs to exist
}

function uploadDone() {
    try {
		// seems to skip the event and actually submit the form
        document.forms[0].submit();
    } catch (ex) {
        alert("Error submitting form");
    }
}

function fileQueueError(file, error_code, message) {
	try {
		var error_name = "";
		switch(error_code) {
			case SWFUpload.ERROR_CODE_QUEUE_LIMIT_EXCEEDED:
				error_name = "You have attempted to queue too many files.";
			break;
		}

		if (error_name !== "") {
			alert(error_name);
			return;
		}

		switch(error_code) {
			case SWFUpload.QUEUE_ERROR.ZERO_BYTE_FILE:
				alert(message);
			break;
			case SWFUpload.QUEUE_ERROR.FILE_EXCEEDS_SIZE_LIMIT:
				alert(message);
				break;
			case SWFUpload.QUEUE_ERROR.ZERO_BYTE_FILE:
				alert(message);
				break;
			case SWFUpload.QUEUE_ERROR.INVALID_FILETYPE:
				alert(message);
				break;
			default:
				alert(message);
				image_name = "error.gif";
			break;
		}

		AddImage("/images/" + image_name);

	} catch (ex) { this.debug(ex); }

}

function fileQueued(file) {
	var type = $("input[name=guest]:checked").attr("title");
	// any type specific logic
	switch (type) {
		case 'images':
			this.customSettings.image_queued = true;		
		break;
		case 'video':
			this.customSettings.video_queued = true;
		break;
	}
	$("#txtFileName").val(file.name);
	var progress = new FileProgress(file, this.customSettings.progress_target);
	progress.setStatus("Pending...");
}

function uploadStart(file) {
}

function fileDialogComplete(num_files_queued) {
}

function uploadProgress(file, bytesLoaded, bytesTotal) {
    try {
		var percent = Math.ceil((bytesLoaded / bytesTotal) * 100);

		//file.id = "singlefile";	// This makes it so FileProgress only makes a single UI element, instead of one for each file
		var progress = new FileProgress(file, this.customSettings.progress_target);
		progress.setProgress(percent);
		progress.setStatus("uploading " + percent + "%");	
    } catch (ex) { 
        this.debug(ex); 
    }
}

function uploadSuccess(file, serverData) {
	try {

		//file.id = "singlefile";	// This makes it so FileProgress only makes a single UI element, instead of one for each file
		var progress = new FileProgress(file, this.customSettings.progress_target);
		progress.setComplete();
		progress.setStatus("complete");
		progress.toggleCancel(false);
		
		if (serverData === " ") {
			this.customSettings.upload_successful = false;
		} else {
			this.customSettings.upload_successful = true;
			document.getElementById("hidFileID").value = serverData;
		}
    } catch (ex) { 
        this.debug(ex); 
    }
}

function uploadComplete(file) {
	try {
	  var videoRadioBtn = document.getElementById("rad1");
	  var imageRadioBtn = document.getElementById("rad2");
		if (this.customSettings.upload_successful && videoRadioBtn.checked) {
			this.setButtonDisabled(true);
			uploadDone();
		}else if(imageRadioBtn && imageRadioBtn.checked){
			var stats = this.getStats();
			if(stats.files_queued > 0){
				this.startUpload();	
			}
			else{
				uploadDone();
			}
			
		
		} else {
			file.id = "singlefile";	// This makes it so FileProgress only makes a single UI element, instead of one for each file
			var progress = new FileProgress(file, this.customSettings.progress_target);
			progress.setError();
			progress.setStatus("file rejected");
			progress.toggleCancel(false);
			
			var txtFileName = document.getElementById("txtFileName");
			txtFileName.value = "";
			
			// validateForm();
			// alert("There was a problem with the upload.\nThe server did not accept it.");
		}
	} catch (ex) {
        this.debug(ex);
	}
}

function uploadError(file, errorCode, message) {

    try {
		if (errorCode === SWFUpload.UPLOAD_ERROR.FILE_CANCELLED) {
			// Don't show cancelled error boxes
			return;
		}
		
		var txtFileName = document.getElementById("txtFileName");
		txtFileName.value = "";
		// validateForm();
		
		// Handle this error separately because we don't want to create a FileProgress element for it.
		switch (errorCode) {
		case SWFUpload.UPLOAD_ERROR.MISSING_UPLOAD_URL:
			alert("There was a configuration error.  You will not be able to upload a resume at this time.");
			this.debug("Error Code: No backend file, File name: " + file.name + ", Message: " + message);
			return;
		case SWFUpload.UPLOAD_ERROR.UPLOAD_LIMIT_EXCEEDED:
			alert("You may only upload 1 file.");
			this.debug("Error Code: Upload Limit Exceeded, File name: " + file.name + ", File size: " + file.size + ", Message: " + message);
			return;
		case SWFUpload.UPLOAD_ERROR.FILE_CANCELLED:
		case SWFUpload.UPLOAD_ERROR.UPLOAD_STOPPED:
			break;
		default:
			alert("An error occurred in the upload. Try again later.");
			this.debug("Error Code: " + errorCode + ", File name: " + file.name + ", File size: " + file.size + ", Message: " + message);
			return;
		}

		//file.id = "singlefile";	// This makes it so FileProgress only makes a single UI element, instead of one for each file
		var progress = new FileProgress(file, this.customSettings.progress_target);
		progress.setError();
		progress.toggleCancel(false);

		switch (errorCode) {
		case SWFUpload.UPLOAD_ERROR.HTTP_ERROR:
			progress.setStatus("upload error");
			this.debug("Error Code: HTTP Error, File name: " + file.name + ", Message: " + message);
			break;
		case SWFUpload.UPLOAD_ERROR.UPLOAD_FAILED:
			progress.setStatus("upload failed.");
			this.debug("Error Code: Upload Failed, File name: " + file.name + ", File size: " + file.size + ", Message: " + message);
			break;
		case SWFUpload.UPLOAD_ERROR.IO_ERROR:
			progress.setStatus("server (IO) error");
			this.debug("Error Code: IO Error, File name: " + file.name + ", Message: " + message);
			break;
		case SWFUpload.UPLOAD_ERROR.SECURITY_ERROR:
			progress.setStatus("security error");
			this.debug("Error Code: Security Error, File name: " + file.name + ", Message: " + message);
			break;
		case SWFUpload.UPLOAD_ERROR.FILE_CANCELLED:
			progress.setStatus("upload cancelled");
			this.debug("Error Code: Upload Cancelled, File name: " + file.name + ", Message: " + message);
			break;
		case SWFUpload.UPLOAD_ERROR.UPLOAD_STOPPED:
			progress.setStatus("upload stopped");
			this.debug("Error Code: Upload Stopped, File name: " + file.name + ", Message: " + message);
			break;
		}
	} catch (ex) {
        this.debug(ex);
	}
}


/* ******************************************
 *	FileProgress Object
 *	Control object for displaying file info
 * ****************************************** */

/*
	A simple class for displaying file information and progress
	Note: This is a demonstration only and not part of SWFUpload.
	Note: Some have had problems adapting this class in IE7. It may not be suitable for your application.
*/

// Constructor
// file is a SWFUpload file object
// targetID is the HTML element id attribute that the FileProgress HTML structure will be added to.
// Instantiating a new FileProgress object with an existing file will reuse/update the existing DOM elements
function FileProgress(file, targetID) {
	this.fileProgressID = file.id;

	this.opacity = 100;
	this.height = 0;

	this.fileProgressWrapper = document.getElementById(this.fileProgressID);
	if (!this.fileProgressWrapper) {
		this.fileProgressWrapper = document.createElement("div");
		this.fileProgressWrapper.className = "progressWrapper";
		this.fileProgressWrapper.id = this.fileProgressID;

		this.fileProgressElement = document.createElement("div");
		this.fileProgressElement.className = "progressContainer";

		var progressCancel = document.createElement("a");
		progressCancel.className = "progressCancel";
		progressCancel.href = "#";
		progressCancel.style.visibility = "hidden";
		progressCancel.appendChild(document.createTextNode(" "));

		var progressText = document.createElement("div");
		progressText.className = "progressName";
		progressText.appendChild(document.createTextNode(file.name));

		var progressBar = document.createElement("div");
		progressBar.className = "progressBarInProgress";

		var progressStatus = document.createElement("div");
		progressStatus.className = "progressBarStatus";
		progressStatus.innerHTML = "&nbsp;";

		this.fileProgressElement.appendChild(progressCancel);
		this.fileProgressElement.appendChild(progressText);
		this.fileProgressElement.appendChild(progressBar);
		this.fileProgressElement.appendChild(progressStatus);

		this.fileProgressWrapper.appendChild(this.fileProgressElement);

		document.getElementById(targetID).appendChild(this.fileProgressWrapper);
	} else {
		this.fileProgressElement = this.fileProgressWrapper.firstChild;
		this.fileProgressElement.childNodes[1].innerHTML = file.name;
	}

	this.height = this.fileProgressWrapper.offsetHeight;

}
FileProgress.prototype.setProgress = function (percentage) {
	this.fileProgressElement.className = "progressContainer blue";
	this.fileProgressElement.childNodes[2].className = "progressBarInProgress";
	this.fileProgressElement.childNodes[2].style.width = percentage + "%";
};
FileProgress.prototype.setComplete = function () {
	this.appear();
	this.fileProgressElement.className = "progressContainer green";
	this.fileProgressElement.childNodes[2].className = "progressBarComplete";
	this.fileProgressElement.childNodes[2].style.width = "";

	var oSelf = this;
	setTimeout(function () {
		oSelf.disappear();
	}, 10000);
};
FileProgress.prototype.setError = function () {
	this.appear();
	this.fileProgressElement.className = "progressContainer red";
	this.fileProgressElement.childNodes[2].className = "progressBarError";
	this.fileProgressElement.childNodes[2].style.width = "";

	var oSelf = this;
	setTimeout(function () {
		oSelf.disappear();
	}, 5000);
};
FileProgress.prototype.setCancelled = function () {
	this.appear();
	this.fileProgressElement.className = "progressContainer";
	this.fileProgressElement.childNodes[2].className = "progressBarError";
	this.fileProgressElement.childNodes[2].style.width = "";

	var oSelf = this;
	setTimeout(function () {
		oSelf.disappear();
	}, 2000);
};
FileProgress.prototype.setStatus = function (status) {
	this.fileProgressElement.childNodes[3].innerHTML = status;
};

// Show/Hide the cancel button
FileProgress.prototype.toggleCancel = function (show, swfUploadInstance) {
	this.fileProgressElement.childNodes[0].style.visibility = show ? "visible" : "hidden";
	if (swfUploadInstance) {
		var fileID = this.fileProgressID;
		this.fileProgressElement.childNodes[0].onclick = function () {
			swfUploadInstance.cancelUpload(fileID);
			return false;
		};
	}
};

// Makes sure the FileProgress box is visible
FileProgress.prototype.appear = function () {
		if (this.fileProgressWrapper.filters) {
			try {
				this.fileProgressWrapper.filters.item("DXImageTransform.Microsoft.Alpha").opacity = 100;
			} catch (e) {
				// If it is not set initially, the browser will throw an error.  This will set it if it is not set yet.
				this.fileProgressWrapper.style.filter = "progid:DXImageTransform.Microsoft.Alpha(opacity=100)";
			}
		} else {
			this.fileProgressWrapper.style.opacity = 1;
		}
		
		this.fileProgressWrapper.style.height = "";
		this.height = this.fileProgressWrapper.offsetHeight;
		this.opacity = 100;
		this.fileProgressWrapper.style.display = "";

};

// Fades out and clips away the FileProgress box.
FileProgress.prototype.disappear = function () {

	var reduceOpacityBy = 15;
	var reduceHeightBy = 4;
	var rate = 30;	// 15 fps

	if (this.opacity > 0) {
		this.opacity -= reduceOpacityBy;
		if (this.opacity < 0) {
			this.opacity = 0;
		}

		if (this.fileProgressWrapper.filters) {
			try {
				this.fileProgressWrapper.filters.item("DXImageTransform.Microsoft.Alpha").opacity = this.opacity;
			} catch (e) {
				// If it is not set initially, the browser will throw an error.  This will set it if it is not set yet.
				this.fileProgressWrapper.style.filter = "progid:DXImageTransform.Microsoft.Alpha(opacity=" + this.opacity + ")";
			}
		} else {
			this.fileProgressWrapper.style.opacity = this.opacity / 100;
		}
	}

	if (this.height > 0) {
		this.height -= reduceHeightBy;
		if (this.height < 0) {
			this.height = 0;
		}

		this.fileProgressWrapper.style.height = this.height + "px";
	}

	if (this.height > 0 || this.opacity > 0) {
		var oSelf = this;
		setTimeout(function () {
			oSelf.disappear();
		}, rate);
	} else {
		this.fileProgressWrapper.style.display = "none";
	}
};

// form validation
// added by jamund ferguson
// march 3, 2010
function validateForm(type) {
  	
  	// check if they sent the type
  	type = typeof(type) != 'undefined' ? type : false;
  	
	// fresh start
	$("div.error-msg-holder").hide();
	
	// set up some variables
	var numErrors=0;
	var errors = "";
	var inputBoxes = $('#txt, #miracle_story, #txt3');
	var isValid = true;
	
	// remove the text boxes default value
	if (($("#miracle_story").val() == 'Enter your story here')) {$("#miracle_story").val('');}

	// check to make sure that the boxes are filled
	inputBoxes.each(function () {			
		var value = $(this).val();
		if (!value) {
			$(this).addClass('fieldWithErrors');
			errors += '<li>'+$(this).attr('title')+'</li>';
			numErrors++;
		}
	});
	
	// check for uploads if type is specified
	if (type) {
		switch (type) {
			case 'images':
				if (!swfu_img.customSettings.image_queued) {
					numErrors++;
					errors += "<li>No images selected</li>";
				}
			break;
			case 'video':
				if (!swfu_vid.customSettings.video_queued) {
					numErrors++;
					errors += "<li>No video selected</li>";
				}		
			break;
		}
	}
	
	// display any and all errors
	if (numErrors) {
	
		// scroll to the top
		window.scrollTo(0,0);
	
		// add an error message
		var html =  '<strong><div id="errorExplanation" class="errorExplanation"><h2>';
			html += numErrors + ' errors prohibited this miracle from being saved</h2>';
			html += '<p>There were problems with the following fields:</p>';
			html += '<ul>' + errors + '</ul></div></strong>';
		$("div.error-msg-holder").show().html(html);
	
		// set the return variable
		isValid = false;	
	}

	// return false if there are any errors
	return isValid;
}

function validateUpload(type) {
	isValid = true;
	switch(type) {

	}
	return isValid;
}

// next button validation
// added by jamund ferguson
// march 3, 2010
$(function() {
		
	// create one simple variable with all of the fields we're checking
	var inputBoxes = $('#txt, #miracle_story, #txt3');
	
	// error state is removed on focus
	inputBoxes.focus(function() {$(this).removeClass('fieldWithErrors');});

	// when you click next, apply validation first of the form and then the upload itself
	$("form.edit_miracle").submit(function() {
		var type = $("input[name=guest]:checked").attr("title");
		var submit = false;
		if (validateForm(type)) {
			switch (type) {
				case 'text':
					submit=true;
				break;
				case 'images':
					swfu_img.startUpload();
				break;
				case 'video':
					swfu_vid.startUpload();
				break;
			}
		}
		return submit;
	});
	
});