/* These handlers use a FileProgress class that handles the UI for displaying the file name and percent complete.
The FileProgress class is not part of SWFUpload.
*/

jQuery(window).load(setupSWFU);
jQuery(window).load(showFileInput);

function setupSWFU() {
		
		setupSubmitBtn();
		
		var settings_object = {
			upload_url : "http://vasnas.futurniture.se/upload.php",
			flash_url : "wp-includes/js/swfupload/swfupload.swf",
			file_size_limit : "100MB",
			file_upload_limit : "0",
			file_queue_limit : "1",
			post_params : {},
			debug : false, 
			
			
			// upload button
			button_image_url: "http://www.vasnas.nu/wp-content/themes/vasnas/img/swfupload_button.png",
			button_placeholder_id : "spanButtonPlaceHolder",
			button_width: "117",
			button_height: "45",
			button_text: '<span class="theFont">Bläddra</span>',
			button_text_style: ".theFont { color:#ffffff; font-size: 16px; font-weight: bold; font-family: Arial, sans-serif; }",
			button_text_left_padding: 20,
			button_text_top_padding: 10,
			
			
			// The event handler functions are defined in handlers.js
			swfupload_loaded_handler : swfUploadLoaded,
			file_dialog_start_handler: fileDialogStart,
			file_queued_handler : fileQueued,
			file_queue_error_handler : fileQueueError,
			file_dialog_complete_handler : fileDialogComplete,
			upload_start_handler : uploadStart,
			upload_progress_handler : uploadProgress,
			upload_error_handler : uploadError,
			upload_success_handler : uploadSuccess,
			upload_complete_handler : uploadComplete,
			swfupload_pre_load_handler : preLoadHandler,
			custom_settings : {
					progressTarget : "fsUploadProgress"
				}
		};
		
		swfu = new SWFUpload(settings_object);
}

function showFileInput() {
	jQuery('#vasnas-fileName').css('display', 'inline'); 
}

function setupSubmitBtn() {
	var btnSubmit = document.getElementById("btnSubmit");
	btnSubmit.onclick = doSubmit; // replace regular submit
}

function swfUploadLoaded() {
	// do nothing atm
}

// if swfupload was successfully loaded, replace file input field
function preLoadHandler() {
	var newFileInput = document.createElement('input');
	newFileInput.setAttribute('type', 'text');
	newFileInput.setAttribute('id', 'vasnas-fileName');
	newFileInput.setAttribute('disabled', 'true');
	jQuery('#vasnas-fileName').before(newFileInput).remove();
	jQuery('#vasnas-fileName').css('display', 'inline');
}
	

function fileQueued(file) {
	try {
		var txtFileName = document.getElementById("vasnas-fileName");
	    txtFileName.value = file.name;
		txtFileName.setAttribute('class', 'file-chosen');
	} catch (ex) {
	}

}

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.");
			//console.log("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.");
			//console.log("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.");
			//console.log("Error Code: Invalid File Type, File name: " + file.name + ", File size: " + file.size + ", Message: " + message);
			break;
		default:
			if (file !== null) {
				progress.setStatus("Unhandled Error");
			}
			//console.log("Error Code: " + errorCode + ", File name: " + file.name + ", File size: " + file.size + ", Message: " + message);
			break;
		}
	} catch (ex) {
    }
}

function fileDialogStart() {
	var txtFileName = document.getElementById("vasnas-fileName");
	txtFileName.value = "";

	this.cancelUpload();
}

function fileDialogComplete(numFilesSelected, numFilesQueued) {
	// nothing atm
}


// Called by the submit button to start the upload
function doSubmit(e) {
	if(!validateForm())
		return false;	
	e = e || window.event;
	if (e.stopPropagation) {
		e.stopPropagation();
	}
	e.cancelBubble = true;
	
	try {
		swfu.startUpload();
	} catch (ex) {
		//document.forms[0].submit(); // if swfupload failed to load submit normally
	}
	return false;
}

// TODO: add proper validation
function validateForm() {
    var txtFileName = document.getElementById("vasnas-fileName");
	var txtName = document.getElementById("vasnas-name");
	var txtEmail = document.getElementById("vasnas-email");
	var txtCity = document.getElementById("vasnas-city");
	var txtComment = document.getElementById("vasnas-comment");
	var ok = document.getElementById("vasnas-ok");
	
	var isValid = true;
	if (txtName.value === "") {
		isValid = false;
		txtName.style.backgroundColor = "red";
	} else {
		txtName.style.backgroundColor = "#ffffff";
	}
	
	if ((txtEmail.value === "") || !txtEmail.value.match(/^([a-zA-Z0-9_.-])+@(([a-zA-Z0-9-])+.)+([a-zA-Z0-9]{2,4})+$/)) {
		isValid = false;
		txtEmail.style.backgroundColor = "red";
	} else {
		txtEmail.style.backgroundColor = "#ffffff";
	}
	
	if (txtFileName.value === "") {
		isValid = false;
		txtFileName.style.backgroundColor = "red";
	} else {
		txtFileName.style.backgroundColor = "#ffffff";
	}
	
	if (txtCity.value === "") {
		isValid = false;
		txtCity.style.backgroundColor = "red";
	} else {
		txtCity.style.backgroundColor = "#ffffff";
	}
	
	checkboxContainer = document.getElementById("checkbox-container");
	if (!ok.checked) {
		isValid = false;
		checkboxContainer.style.backgroundColor = "red";
	} else {
		checkboxContainer.style.backgroundColor = "";	
	}
	
	statusText = "";
	if(!isValid)
		statusText = "Någonting blev fel, kontrollera dina uppgifter ovan och prova sedan att ladda upp igen.";
	document.getElementById("validation-info").innerHTML = statusText;

	return isValid;
}

function uploadStart(file) {
	try {
		 
	    this.addPostParam('vasnas-name', document.getElementById('vasnas-name').value);
	    this.addPostParam('vasnas-title', document.getElementById('vasnas-title').value);
	    this.addPostParam('vasnas-email', document.getElementById('vasnas-email').value);
	    this.addPostParam('vasnas-city', document.getElementById('vasnas-city').value);
	    this.addPostParam('vasnas-comment', document.getElementById('vasnas-comment').value); 
		
		// if we want a loader image instead - set it here
		//var progress = new FileProgress(file, this.customSettings.progressTarget);
		//progress.setStatus('<img src="'+LOADER_URL+'"/>'); 
	}
	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.setStatus('Laddar upp... ' + percent + " % klar.");
	} catch (ex) {
	}
}

function uploadSuccess(file, serverData) {	
	try {
		if (serverData === " ") {
			this.customSettings.upload_successful = false;
		} else {
			this.customSettings.upload_successful = true;
			document.getElementById("hidFileName").value = serverData;
			uploadDone();
		}
		
	} 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);
			//console.log("Error Code: HTTP Error, File name: " + file.name + ", Message: " + message);
			break;
		case SWFUpload.UPLOAD_ERROR.UPLOAD_FAILED:
			progress.setStatus("Upload Failed.");
			//console.log("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");
			//console.log("Error Code: IO Error, File name: " + file.name + ", Message: " + message);
			break;
		case SWFUpload.UPLOAD_ERROR.SECURITY_ERROR:
			progress.setStatus("Security Error");
			//console.log("Error Code: Security Error, File name: " + file.name + ", Message: " + message);
			break;
		case SWFUpload.UPLOAD_ERROR.UPLOAD_LIMIT_EXCEEDED:
			progress.setStatus("Upload limit exceeded.");
			//console.log("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.");
			//console.log("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);
			//console.log("Error Code: " + errorCode + ", File name: " + file.name + ", File size: " + file.size + ", Message: " + message);
			break;
		}
	} catch (ex) { 
    }
}

function uploadComplete(file) {
	// nothing for now
}

// This event comes from the Queue Plugin
function queueComplete(numFilesUploaded) {
	var status = document.getElementById("divStatus");
	status.innerHTML = numFilesUploaded + " file" + (numFilesUploaded === 1 ? "" : "s") + " uploaded.";
}

 // Called by the queue complete handler to submit the form
function uploadDone() {
	try {
		document.forms[0].submit();
	} catch (ex) {
		alert("Error submitting form");
	}
}
