var totalQueueSize=0;

//The fileQueued event is fired for each file that is queued after the File Selection Dialog window is closed.
function fileQueued(file) {
	try {
	    //show the upload panel
    	$(this.customSettings.upload_panel).style.display="block";
    	
    	//if multi-file upload, hide the organizer panel
    	if (this.customSettings.fileMode == "multiple")
    	{
    	    $('MainPanel').style.display="none";
    	    $('TaskTitle').innerHTML = "Upload Your Photos";
    	}
    	
		var progress = new FileProgress(file, this.customSettings.upload_target, this.customSettings.fileMode);

        var size = file.size;
        totalQueueSize += size;

		var fileInfo = fileStats(size);
        var abbrev=fileInfo[0];
        var denom=fileInfo[1];
		progress.setStatus((file.size / denom).toFixed(2) + " " + abbrev);
		progress.toggleCancel(true, this);

	} catch (ex) {
		this.debug(ex);
	}
}

//The fileQueueError event is fired for each file that was not queued after the File Selection Dialog window is closed.
function fileQueueError(file, errorCode, message) {
	try {
		var imageName = "error.gif";
		var errorName = "";
		if (errorCode === SWFUpload.errorCode_QUEUE_LIMIT_EXCEEDED) {
			errorName = "You have attempted to queue too many files.";
		}

		if (errorName !== "") {
			alert(errorName);
			return;
		}

		switch (errorCode) {
		case SWFUpload.QUEUE_ERROR.ZERO_BYTE_FILE:
			imageName = "zerobyte.gif";
			alert('File "' + file.name + '" is 0 bytes and cannot be uploaded!');
			break;
		case SWFUpload.QUEUE_ERROR.FILE_EXCEEDS_SIZE_LIMIT:
			imageName = "toobig.gif";
			alert('File "' + file.name + '" is larger than the maximum size we allow (7MB) and cannot be uploaded!');
			break;
		case SWFUpload.QUEUE_ERROR.INVALID_FILETYPE:
		default:
			//alert(message);
			break;
		}

	} catch (ex) {
		this.debug(ex);
	}

}

// This event comes from the Queue Plugin
function queueComplete(numFilesUploaded) {
    var status = $("divStatus");
	status.innerHTML = numFilesUploaded + " file" + (numFilesUploaded === 1 ? "" : "s") + " successfully uploaded.";
}

//The fileDialogComplete event fires after the File Selection Dialog window has been closed and all the selected files have been processed.
function fileDialogComplete(numFilesSelected, numFilesQueued) {
	try {
		if (numFilesQueued > 0) {
		    if (this.customSettings.fileMode == "single") {
		        //$('UploadButtonPlaceholder').style.visibility="hidden";
	            this.startUpload();
	        }
	        else {
	            //multi-file upload
		        $(this.customSettings.cancelButtonId).disabled = false;
		        $(this.customSettings.startButtonId).disabled = false;
    			
			    //count total files and total MB
			    //<div class="name2">27 Files</div><div class="size2">Total: 9.42MB</div>
			    var fileInfo = fileStats(totalQueueSize);
                var abbrev=fileInfo[0];
                var denom=fileInfo[1];
    		    var summaryText = "<div class='name2'>" + this.getStats().files_queued + " Files</div><div class='size2'>Total: " + (totalQueueSize / denom).toFixed(2) + " " + abbrev + "</div>";
    		    $(this.customSettings.queueStats).innerHTML = summaryText;
            }
		}
	} catch (ex) {
		this.debug(ex);
	}
}

//uploadStart is called immediately before the file is uploaded. 
//This event provides an opportunity to perform any last minute validation, add post params or do any other work before the file is uploaded.
function uploadStart(file) {
	try {
		var progress = new FileProgress(file, this.customSettings.upload_target, this.customSettings.fileMode);
		//cannot cancel an in-progress upload
		progress.toggleCancel(false, this);
        if (this.customSettings.fileMode == "multiple")
    	{
  	        this.setButtonImageURL("/na.gif");
  	    }
  	    else
  	    {
		    //disable uploading of another image
            this.setButtonDisabled(true);
  	    }
        
        if (this.customSettings.fileMode == "multiple") {
            //$(this.customSettings.cancelButtonId).disabled = true;
	        //$(this.customSettings.startButtonId).disabled = true;
	        $(this.customSettings.cancelButtonId).style.display = "none";
	        $(this.customSettings.startButtonId).style.display = "none"
        }
	}
	catch (ex) {}
	
	return true;
}

//The uploadProgress event is fired periodically by the Flash Control. 
//This event is useful for providing UI updates on the page.
function uploadProgress(file, bytesLoaded, bytesTotal) {

	try {
		var percent = Math.ceil((bytesLoaded / bytesTotal) * 100);
        //alert(bytesLoaded + " " + bytesTotal + " " + percent);
		var progress = new FileProgress(file, this.customSettings.upload_target, this.customSettings.fileMode);
		progress.setProgress(percent);
	} catch (ex) {
		this.debug(ex);
	}
}

//uploadSuccess is fired when the entire upload (single file) has been transmitted and the server returns a HTTP 200 status code. 
//Any data outputted by the server is available in the server data parameter.
function uploadSuccess(file, serverData, response) {
	try {
	    if (this.customSettings.fileMode == "single") {
	        //add thumbnail
            addImage("FatheadThumbnail.aspx?id=" + serverData);
            //show Cancel/Continue buttons
            $("WizButtons").style.display="";
        }

		var progress = new FileProgress(file, this.customSettings.upload_target, this.customSettings.fileMode);

		progress.setComplete();
	    var status = $("divStatus");
	    var numFilesUploaded = this.getStats().successful_uploads;
    	status.innerHTML = numFilesUploaded + " file" + (numFilesUploaded === 1 ? "" : "s") + " successfully uploaded.";
	} catch (ex) {
		this.debug(ex);
	}
}

//uploadComplete is always fired at the end of an upload cycle (after uploadError or uploadSuccess). 
//At this point the upload is complete and another upload can be started.
function uploadComplete(file) {
	if (this.getStats().files_queued === 0 && this.customSettings.fileMode == "multiple") {
    	//finished uploading all files
    	//show Cancel/Continue buttons
        $("WizButtons").style.display="";
    }
}

//The uploadError event is fired any time an upload is interrupted or does not complete successfully. 
//The error code parameter indicates the type of error that occurred. The error code parameter specifies a constant in SWFUpload.UPLOAD_ERROR.
function uploadError(file, errorCode, message) {
	var imageName =  "error.gif";
	var progress;
	try {
	    alert(errorCode + " " + message);
		switch (errorCode) {
		case SWFUpload.UPLOAD_ERROR.FILE_CANCELLED:
			try {
				progress = new FileProgress(file,  this.customSettings.upload_target, this.customSettings.fileMode);
				progress.setCancelled();
				//progress.setStatus("Cancelled");
				progress.toggleCancel(false);
				
				//remove file size from queue'd total
				totalQueueSize -= file.size;
				
			    //count total files and total MB
			    var fileInfo = fileStats(totalQueueSize);
                var abbrev=fileInfo[0];
                var denom=fileInfo[1];
			    //<div class="name2">27 Files</div><div class="size2">Total: 9.42MB</div>
    		    var summaryText = "<div class='name2'>" + this.getStats().files_queued + " Files</div><div class='size2'>Total: " + (totalQueueSize / denom).toFixed(2) + " " + abbrev + "</div>";
    		    $(this.customSettings.queueStats).innerHTML = summaryText;
			}
			catch (ex1) {
				this.debug(ex1);
			}
			break;
		case SWFUpload.UPLOAD_ERROR.UPLOAD_STOPPED:
			try {
				progress = new FileProgress(file,  this.customSettings.upload_target, this.customSettings.fileMode);
				progress.setCancelled();
				progress.setStatus("Stopped");
				progress.toggleCancel(true);
			}
			catch (ex2) {
				this.debug(ex2);
			}
		case SWFUpload.UPLOAD_ERROR.UPLOAD_LIMIT_EXCEEDED:
			imageName = "uploadlimit.gif";
			break;
		default:
			//alert(message);
			alert("An unexpected error occurred while uploading your file. Please try again or select a different file.")
			//window.open("FatheadDefault.aspx", "_self")
            //this.setButtonDisabled(false);
			break;
		}

		if (this.getStats().files_queued == 0) {
    	    //$(this.customSettings.cancelButtonId).disabled = true;
    	    //$(this.customSettings.startButtonId).disabled = true;
    	    $(this.customSettings.cancelButtonId).style.display = "none";
    	    $(this.customSettings.startButtonId).style.display = "none"
		}
	} catch (ex3) {
		this.debug(ex3);
	}
}

function addImage(src) {
	var newImg = document.createElement("img");
	newImg.id = "image";
	newImg.style.margin = "5px";

	$("thumbnails").appendChild(newImg);
	//$("thumbnails").appendChild(canvasElem);
	if (newImg.filters) {
		try {
			newImg.filters.item("DXImageTransform.Microsoft.Alpha").opacity = 0;
		} catch (e) {
			// If it is not set initially, the browser will throw an error.  This will set it if it is not set yet.
			newImg.style.filter = 'progid:DXImageTransform.Microsoft.Alpha(opacity=' + 0 + ')';
		}
	} else {
		newImg.style.opacity = 0;
	}

	newImg.onload = function () {
		fadeIn(newImg, 0);
	};
	newImg.src = src;
}

function fadeIn(element, opacity) {
	var reduceOpacityBy = 5;
	var rate = 30;	// 15 fps


	if (opacity < 100) {
		opacity += reduceOpacityBy;
		if (opacity > 100) {
			opacity = 100;
		}

		if (element.filters) {
			try {
				element.filters.item("DXImageTransform.Microsoft.Alpha").opacity = 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.
				element.style.filter = 'progid:DXImageTransform.Microsoft.Alpha(opacity=' + opacity + ')';
			}
		} else {
			element.style.opacity = opacity / 100;
		}
	}

	if (opacity < 100) {
		setTimeout(function () {
			fadeIn(element, opacity);
		}, rate);
	}
}

function fileStats(fileSize)
{
    var abbrev="";
    var denom=1;
    if (fileSize > 1024*1024) {
        abbrev = "MB";
        denom = 1024*1024;
    }
    else if (totalQueueSize > 1024) {
        abbrev = "KB"
        denom=1024;
    }
    return [abbrev,denom];
}
