/* Demo Note:  This demo uses a FileProgress class that handles the UI for displaying the file name and percent complete.
The FileProgress class is not part of SWFUpload.
*/


/* **********************
   Event Handlers
   These are my custom event handlers to make my
   web application behave the way I went when SWFUpload
   completes different tasks.  These aren't part of the SWFUpload
   package.  They are part of my application.  Without these none
   of the actions SWFUpload makes will show up in my application.
   ********************** */
// Called by the submit button to start the upload
function doSubmit(e) {
//    e = e || window.event;
//    if (e.stopPropagation) {
//        e.stopPropagation();
//    }
//    e.cancelBubble = true;
    
    try {
        swfu.startUpload();
    } catch (ex) {

    }
    return false;
}

function fileQueued(file) {
	try {
		var progress = new FileProgress(file, this.customSettings.progressTarget);
		progress.setStatus("Pending...");
		progress.toggleCancel(true, this);

	} catch (ex) {
		this.debug(ex);
	}
}

function projectFileQueued(file) {
    try {
        var txtFileName = document.getElementById("txtFileName");
        txtFileName.value = file.name;
    } catch (e) {
    }
}

function projectDrawingFileQueued(file) {
    try {
        var txtFileName = document.getElementById("txtFileName");
        txtFileName.value = file.name;
    } catch (e) {
    }
}

function projectVideoFileQueued(file) {
    try {
        var txtFileName = document.getElementById("txtFileName");
        txtFileName.value = file.name;
    } catch (e) {
    }
}

function peopleProfileFileQueued(file) {
	try {
        var txtFileName = document.getElementById("txtFileName");
        txtFileName.value = file.name;
    } catch (e) {
    }
}

function fileBrowse() {
    var txtFileName = document.getElementById("txtFileName");
    txtFileName.value = "";

    this.cancelUpload();
    this.selectFile();
}

function fileQueueError(file, errorCode, message) {
	try {
		if (errorCode === SWFUpload.QUEUE_ERROR.QUEUE_LIMIT_EXCEEDED) {
			alert("You have attempted to queue too many files.\n" + (message === 0 ? "You have reached the upload limit." : "You may select " + (message > 1 ? "up to " + message + " files." : "one file.")));
			return;
		}

		var progress = new FileProgress(file, this.customSettings.progressTarget);
		progress.setError();
		progress.toggleCancel(false);

		switch (errorCode) {
		case SWFUpload.QUEUE_ERROR.FILE_EXCEEDS_SIZE_LIMIT:
			progress.setStatus("File is too big.");
			this.debug("Error Code: File too big, File name: " + file.name + ", File size: " + file.size + ", Message: " + message);
			break;
		case SWFUpload.QUEUE_ERROR.ZERO_BYTE_FILE:
			progress.setStatus("Cannot upload Zero Byte files.");
			this.debug("Error Code: Zero byte file, File name: " + file.name + ", File size: " + file.size + ", Message: " + message);
			break;
		case SWFUpload.QUEUE_ERROR.INVALID_FILETYPE:
			progress.setStatus("Invalid File Type.");
			this.debug("Error Code: Invalid File Type, File name: " + file.name + ", File size: " + file.size + ", Message: " + message);
			break;
		default:
			if (file !== null) {
				progress.setStatus("Unhandled Error");
			}
			this.debug("Error Code: " + errorCode + ", File name: " + file.name + ", File size: " + file.size + ", Message: " + message);
			break;
		}
	} catch (ex) {
        this.debug(ex);
    }
}

function fileDialogComplete(numFilesSelected, numFilesQueued) {
	try {
		if (numFilesSelected > 0) {
			document.getElementById(this.customSettings.cancelButtonId).disabled = false;
		}
		
		/* I want auto start the upload and I can do that here */
		this.startUpload();
	} catch (ex)  {
        this.debug(ex);
	}
}

function projectFileDialogComplete(numFilesSelected, numFilesQueued) {
    try {
        
    } catch (ex)  {
        this.debug(ex);
    }
}

function projectDrawingFileDialogComplete(numFilesSelected, numFilesQueued) {
    try {
        
    } catch (ex)  {
        this.debug(ex);
    }
}

function projectVideoFileDialogComplete(numFilesSelected, numFilesQueued) {
    try {
        
    } catch (ex)  {
        this.debug(ex);
    }
}

function uploadStart(file) {
	try {
		/* I don't want to do any file validation or anything,  I'll just update the UI and
		return true to indicate that the upload should start.
		It's important to update the UI here because in Linux no uploadProgress events are called. The best
		we can do is say we are uploading.
		 */
		var progress = new FileProgress(file, this.customSettings.progressTarget);
		progress.setStatus("Uploading...");
		progress.toggleCancel(true, this);
	}
	catch (ex) {}
	
	return true;
}

function uploadProgress(file, bytesLoaded, bytesTotal) {
	try {
		var percent = Math.ceil((bytesLoaded / bytesTotal) * 100);
        
		var progress = new FileProgress(file, this.customSettings.progressTarget);
		progress.setProgress(percent);
		progress.setStatus("Uploading...");
	} catch (ex) {
		this.debug(ex);
	}
}

function uploadSuccess(file, serverData) {
	try {
		var progress = new FileProgress(file, this.customSettings.progressTarget);
		progress.setComplete();
		progress.setStatus("Complete.");
		progress.toggleCancel(false);
	} catch (ex) {
		this.debug(ex);
	}
}

function uploadSuccess(file, serverData) {
    try {
        var progress = new FileProgress(file, this.customSettings.progressTarget);
        progress.setComplete();
        progress.setStatus("Complete.");
        progress.toggleCancel(false);
        
        if (serverData === " ") {
            this.customSettings.upload_successful = false;
        } else {
            this.customSettings.upload_successful = true;
            document.getElementById("txtFileName").value = serverData;
        }
    } catch (e) {
    }
}

function uploadError(file, errorCode, message) {
	try {
		var progress = new FileProgress(file, this.customSettings.progressTarget);
		progress.setError();
		progress.toggleCancel(false);

		switch (errorCode) {
		case SWFUpload.UPLOAD_ERROR.HTTP_ERROR:
			progress.setStatus("Upload Error: " + message);
			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.UPLOAD_LIMIT_EXCEEDED:
			progress.setStatus("Upload limit exceeded.");
			this.debug("Error Code: Upload Limit Exceeded, File name: " + file.name + ", File size: " + file.size + ", Message: " + message);
			break;
		case SWFUpload.UPLOAD_ERROR.FILE_VALIDATION_FAILED:
			progress.setStatus("Failed Validation.  Upload skipped.");
			this.debug("Error Code: File Validation Failed, File name: " + file.name + ", File size: " + file.size + ", Message: " + message);
			break;
		case SWFUpload.UPLOAD_ERROR.FILE_CANCELLED:
			// If there aren't any files left (they were all cancelled) disable the cancel button
			if (this.getStats().files_queued === 0) {
				document.getElementById(this.customSettings.cancelButtonId).disabled = true;
			}
			progress.setStatus("Cancelled");
			progress.setCancelled();
			break;
		case SWFUpload.UPLOAD_ERROR.UPLOAD_STOPPED:
			progress.setStatus("Stopped");
			break;
		default:
			progress.setStatus("Unhandled Error: " + errorCode);
			this.debug("Error Code: " + errorCode + ", File name: " + file.name + ", File size: " + file.size + ", Message: " + message);
			break;
		}
	} catch (ex) {
        this.debug(ex);
    }
}

function uploadComplete(file) {
	
	if (this.getStats().files_queued === 0) {
		document.getElementById(this.customSettings.cancelButtonId).disabled = true;
	}
}

function projectUploadComplete(file) {
    if (xmlHttp.readyState == 4 || xmlHttp.readyState == 0) {
        try {
            var project_id = $('project_id').value;
            var photo = $('txtFileName').value;
            var photo_copyright = $('photo_copyright').value;
            xmlHttp.open("POST", "includes/ajax/projectPhotos.ajax", true);
            xmlHttp.onreadystatechange = handleProjectUploadComplete;
            xmlHttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
            xmlHttp.send("request=" + encodeURI("insertProjectPhoto") + "&project_id=" + encodeURI(project_id) + "&photo=" + encodeURI(photo) + "&photo_copyright=" + encodeURI(photo_copyright));
        } catch(e) {
            alert("Can't connect to the server:\n" + e.toString());
        }
    } else {
        setTimeout("projectUploadComplete('" + file + "')", 1);
    }
}

function handleProjectUploadComplete() {
    if (xmlHttp.readyState == 4) {
        if (xmlHttp.status == 200) {
            try {
                var xmlResponse = xmlHttp.responseText;
                xmlResponse = xmlResponse.split(":|||:");
                window.addEvent('domready', function() {
                    setTimeout("getData('" + xmlResponse[0] + "', '2', 'project')", 100);
                });
            } catch(e) {
                alert("Error reading the response: " + e.toString());
            }
        } else {
            alert("There was a problem accessing the server: " + xmlHttp.statusText);
        }
    }
}

function projectDrawingUploadComplete(file) {
    if (xmlHttp.readyState == 4 || xmlHttp.readyState == 0) {
        try {
            var project_id = $('project_id').value;
            var project_drawing_title = $('project_drawing_title').value;
            var project_drawing_file = $('txtFileName').value;
            var project_drawing_description = $('project_drawing_description').value;
            
            xmlHttp.open("POST", "includes/ajax/projectDrawings.ajax", true);
            xmlHttp.onreadystatechange = handleProjectDrawingUploadComplete;
            xmlHttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
            xmlHttp.send("request=" + encodeURI("insertProjectDrawing") + "&project_id=" + encodeURIComponent(project_id) + "&project_drawing_title=" + encodeURIComponent(project_drawing_title) + "&project_drawing_file=" + encodeURIComponent(project_drawing_file) + "&project_drawing_description=" + encodeURIComponent(project_drawing_description));
        } catch(e) {
            alert("Can't connect to the server:\n" + e.toString());
        }
    } else {
        setTimeout("projectDrawingUploadComplete('" + file + "')", 1);
    }
}

function handleProjectDrawingUploadComplete() {
    if (xmlHttp.readyState == 4) {
        if (xmlHttp.status == 200) {
            try {
                var xmlResponse = xmlHttp.responseText;
                xmlResponse = xmlResponse.split(":|||:");
                window.addEvent('domready', function() {
                    setTimeout("getData('" + xmlResponse[0] + "', '4', 'project', 'sub_category_link_4')", 100);
                });
            } catch(e) {
                alert("Error reading the response: " + e.toString());
            }
        } else {
            alert("There was a problem accessing the server: " + xmlHttp.statusText);
        }
    }
}

function projectVideoUploadComplete(file) {
    if (xmlHttp.readyState == 4 || xmlHttp.readyState == 0) {
        try {
            var project_id = $('project_id').value;
            var project_video_title = $('project_video_title').value;
            var project_video_thumbnail = $('txtFileName').value;
            var project_video_description = $('project_video_description').value;
            var project_video_url = $('project_video_url').value;
            var project_video_size = $('project_video_size').value;
            
            xmlHttp.open("POST", "includes/ajax/projectVideos.ajax", true);
            xmlHttp.onreadystatechange = handleProjectVideoUploadComplete;
            xmlHttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
            xmlHttp.send("request=" + encodeURI("insertProjectVideo") + "&project_id=" + encodeURIComponent(project_id) + "&project_video_title=" + encodeURIComponent(project_video_title) + "&project_video_thumbnail=" + encodeURIComponent(project_video_thumbnail) + "&project_video_description=" + encodeURIComponent(project_video_description) + "&project_video_url=" + encodeURIComponent(project_video_url) + "&project_video_size=" + encodeURIComponent(project_video_size));
        } catch(e) {
            alert("Can't connect to the server:\n" + e.toString());
        }
    } else {
        setTimeout("projectDrawingUploadComplete('" + file + "')", 1);
    }
}

function handleProjectVideoUploadComplete() {
    if (xmlHttp.readyState == 4) {
        if (xmlHttp.status == 200) {
            try {
                var xmlResponse = xmlHttp.responseText;
                xmlResponse = xmlResponse.split(":|||:");
                window.addEvent('domready', function() {
                    setTimeout("getData('" + xmlResponse[0] + "', '5', 'project', 'sub_category_link_5')", 100);
                });
            } catch(e) {
                alert("Error reading the response: " + e.toString());
            }
        } else {
            alert("There was a problem accessing the server: " + xmlHttp.statusText);
        }
    }
}

function peopleProfileUploadComplete(file) {
	if (xmlHttp.readyState == 4 || xmlHttp.readyState == 0) {
        try {
			this.debug("function peopleProfileUploadComplete() REACHED");
            var person_id = $('person_id').value;
            var person_profile_picture = $('txtFileName').value;
            xmlHttp.open("POST", "includes/ajax/peopleProfilePicture.ajax", true);
            xmlHttp.onreadystatechange = handlePeopleProfileUploadComplete;
            xmlHttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
            xmlHttp.send("request=" + encodeURI("insertProfilePicture") + "&person_id=" + encodeURIComponent(person_id) + "&person_profile_picture=" + encodeURIComponent(person_profile_picture));
        } catch(e) {
            alert("Can't connect to the server:\n" + e.toString());
        }
    } else {
        setTimeout("peopleProfileUploadComplete('" + file + "')", 1);
    }
}

function handlePeopleProfileUploadComplete() {
	if (xmlHttp.readyState == 4) {
        if (xmlHttp.status == 200) {
            try {
                var xmlResponse = xmlHttp.responseText;
                xmlResponse = xmlResponse.split(":|||:");
                window.addEvent('domready', function() {
                    setTimeout("loadEntityPage('" + xmlResponse[0] + "', 'person')", 100);
                });
            } catch(e) {
                alert("Error reading the response: " + e.toString());
            }
        } else {
            alert("There was a problem accessing the server: " + xmlHttp.statusText);
        }
    }
}

// This event comes from the Queue Plugin
function queueComplete(numFilesUploaded) {
	var status = document.getElementById("divStatus");
	status.innerHTML = numFilesUploaded + " file" + (numFilesUploaded === 1 ? "" : "s") + " uploaded.";
	//setTimeout("editNewsItem('" + this.customSettings.newsItemId +"', '" + this.customSettings.newsItemDate +"', '" + this.customSettings.newsItemHeading +"', '" + this.customSettings.newsItemBriefOverview +"', '" + this.customSettings.newsItemContent +"', " + this.customSettings.newsItemImageIdsArray +", " + this.customSettings.newsItemThumbsArray +", " + this.customSettings.newsItemImagesArray +", " + this.customSettings.newsItemLinkIdsArray +", " + this.customSettings.newsItemLinksUrlArray +", " + this.customSettings.newsItemLinksTitleArray +")", 1);
	//editNewsItem(this.customSettings.newsItemId, this.customSettings.newsItemDate, this.customSettings.newsItemHeading, this.customSettings.newsItemBriefOverview, this.customSettings.newsItemContent, this.customSettings.newsItemImageIdsArray, this.customSettings.newsItemThumbsArray, this.customSettings.newsItemImagesArray, this.customSettings.newsItemLinkIdsArray, this.customSettings.newsItemLinksUrlArray, this.customSettings.newsItemLinksTitleArray);
}
