/*
 * Contact Form JS
 * Used for handling IFRAME file upload with upload animation display
 * Author: Mocanu Razvan, 2008
 * Copyright GeCAD Technologies 2008
 */

// Function called on file upload end
function endProgressAnimation(upload_result, filename) {
	switch (upload_result) {
	case 0:	// SUCCESS
		// Remove the form and disable the file upload input
		$('#upload_td form').replaceWith($('#upload_td form').contents());
		$("#upload_td input[type='file']").attr("disabled", "disabled");
		
		// Update text and image and set filename value
		$('#upload_td span').text('File uploaded succesfully.');
		//$('#upload_td img').attr("src", "/img/support-upload-ok.gif");
		$("#upload_td input[name='srv_filename']").val(filename);
		
		// Submit the main form
		// Timeout is used becuase there was an issue with the image not changing
		// because the form was submitted and the refresh happened arbitrarily 
		setTimeout(function () {$('#frmFeedback').trigger("submit", [1]); }, 500);
		// ...and exit
		return;
		break;
	case 1:	// ERR_SIZE_TOO_BIG
		$('#upload_td span').text('ERROR: File size is too big.');
		break;
	case 2:	// ERR_TYPE_NOT_ACCEPTED
		$('#upload_td span').text('ERROR: Files of this type cannot pe uploaded.');
		break;
	case 3:	// ERR_SERVER_ERROR
		$('#upload_td span').text('ERROR: A server-side error occurred.');
		break;
	case 4:	// ERR_UNKNOWN
	default:
		$('#upload_td span').html('ERROR: Time limit exceeded.<br /> File is probably too big.');
		break;
	}
	// ... An error occurred...
	// Remove the form
	$('#upload_td form').replaceWith($('#upload_td form').contents());
	// Replace icon
	//$('#upload_td img').attr("src", "/img/support-upload-warning.gif");
	// Re-enable the main form submit button
	$('#frmFeedbackSubmit').removeAttr("disabled");
}

// Function called on file upload start
function startProgressAnimation() {
	$('#upload_td span').text("Uploading...");
	//$('#upload_td img').attr("src", "/img/support-upload-progress.gif");
}

// On DOM Load
$(document).ready(function () {

	$('#frmFeedback').bind("submit", function (event, stage) {
		if (stage === undefined) {
			// Start background upload only if user selected a file for upload
			if ($('#upload_td input[type="file"]').val() !== "") {
				$('#frmFeedbackSubmit').attr("disabled", "disabled");
				$('#upload_td').children().wrapAll(
					"<form method=\"post\" enctype=\"multipart/form-data\" name=\"frmUpload\" " +
					"id=\"frmUpload\" action=\"contact_upload.php\" target=\"iframe_upload\"></form>"
				);
				// Submit the form containing the file input (to the iframe)
				$('#frmUpload').submit(function () {
					startProgressAnimation();
				}).submit();
				return false;
			}
		}
	});
});

