var Progress = {
	intervals: {},
	statusXml: function() {
		var _this = Progress;
		$.get("/sosapp/upload_progress.xml", null, function(data, status) {
			var progress = $(data).find("progress");
			ProgressBar.update(progress.attr("bytesRead"), progress.attr("totalBytes"));
			if(progress.attr("isComplete") == "true") {
				// This should build the error object, but since this isn't used, no need to
				_this.stop();
				VideoEntryForm.error();
			} else if(progress.attr("isComplete") == "true") _this.stop();
		}, "xml");
	},
	statusJson: function() {
		var _this = Progress;
		$.get("/sosapp/upload_progress.json", null, function(data, status) {
			if(data.success == false || data.hasError == true) {
				_this.stop();
				VideoEntryForm.error(data);
			} else {
				ProgressBar.update(data.bytesRead, data.totalBytes);
				if(data.isComplete) _this.stop();
			}
		}, "json");
	},
	status: function() {
		ProgressBar.reset(true);
		this.intervals.status = setInterval(this.statusJson, 5000);
	},
	stop: function() {
		$.get("/sosapp/reset_progress.json");
		for(var interval in this.intervals) clearInterval(this.intervals[interval]);
		//ProgressBar.reset(false);
	}
};
	
var ProgressBar = {
	container: "#videoupload",
	progress: "#progress",
	number: "#progress_number",
	update: function(current, total) {
		if(current && total) {
			var percent = current / total * 100;
			if(percent > 100) percent = 100;
			$(this.number).text(Math.round(percent));
			$(this.progress).css("width", percent + "%");
		}
	},
	reset: function(show) {
		if(show) $(this.container).addClass("show");
		else $(this.container).removeClass("show");
		this.update(0, 100);
	}
};

var VideoEntryForm = {
	form: "#entry",
	enabled: true,
	init: function() {
		var form = $(this.form);
		this.action = form.attr("action");
		form.ajaxForm({
			beforeSubmit: this.validate,
			success: this.checkResult,
			dataType: "json",
			iframe: true
		});
		if(form.length > 0) form.ajaxError(VideoEntryForm.error);
		
		var dob = $("#dob,#phone");
		dob.focus(function() { if(this.value == this.defaultValue) { this.value = ""; } });
		dob.blur(function() { if(this.value == "") { this.value = this.defaultValue; } });
	},
	
	// May not have context to this object
	validate: function(data, form, options) {
		var _this = VideoEntryForm;
		
		var enabled = _this.enabled;
		// Disable while it's validating
		_this.enabled = false;
		if(!enabled) {
			$("#error_multiple").addClass("show");
			return false;
		}

		var valid = true;
		$("span.show").removeClass("show");
		var emptyFields = form.find("input.required[value=]");
		if(emptyFields.length > 0) {
			emptyFields.each(function() {
				var id = this.id;
				if(/^address\d$/.test(id)) id = "address";
				$("#error_" + id).addClass("show");
			});
			valid = false;
		}
		
		var emailField = $("#email")[0];
		var email = emailField.value;
		if(email && !_this.isValidEmail(email)) {
			$("#error_" + emailField.id).addClass("show");
			valid = false;
		}
		
		var dobField = $("#dob")[0];
		var dob = dobField.value;
		if(dob && !_this.isValidDate(dob)) {
			$("#error_" + dobField.id).addClass("show");
			valid = false;
		}
		
		var fileField = $("#videoFile")[0];
		var file = fileField.value;
		if(file && !_this.isValidFileType(file)) {
			$("#error_" + fileField.id).addClass("show");
			valid = false;
		}
		this.url = _this.buildAction();
		if(valid) Progress.status();
		else $("#error_required").addClass("show");
		// Re-enable so it can be submitted again
		if(enabled && !valid) _this.enabled = true;
		return valid;
	},
	isValidEmail: function(email) {
		return /^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$/i.test(email);
	},
	isValidDate: function(date) {
		var valid = false;
		if(/^(\d{2}\/){2}\d{2}$/.test(date)) {
			var obj = new Date(date);
			var m = (obj.getMonth() < 9) ? "0" : "";
			m += (obj.getMonth()+1) + "";
			var d = (obj.getDate() < 10) ? "0" : "";
			d += obj.getDate();
			var y = obj.getYear();
			var str = m + "/" + d + "/" + y;
			valid = (date == str);
		}
		return valid;
	},
	isValidFileType: function(file) {
		return /.+\.(mpg|mpeg|mov|avi|wmv)$/i.test(file);
	},
	// May not have context to this object
	checkResult: function(data, status, req) {
		var _this = VideoEntryForm;
		if(data.success) _this.success(data);
		else _this.error(data);
	},
	success: function(data) {
		//$(this.form).resetForm();
		//setTimeout(function() { ProgressBar.reset(false); }, 5000);
		location.href = "success.html";
	},
	error: function(data) {
		var _this = VideoEntryForm;
		$("span.show").removeClass("show");
		if(data && data.error && /FileSizeLimitExceededException/.test(data.error.type)) {
			$("#error_required").addClass("show");
			$("#error_videoFile").addClass("show");
		} else {
			// Possibly an resource exception
			$("#error_unknown").addClass("show");
		}
		Progress.stop();
		ProgressBar.reset(false);
		// Re-enable the form to be able to submit again
		_this.enabled = true;
	},
	/**
	 * This serializes the form fields and appends it to the action.
	 * The fields need to be added to the action as a get, because
	 * they're not coming across in the multipart post.
	 */
	buildAction: function() {
		var form = $(this.form);
		var action = this.action.replace(/.html\b/i, ".ajax");
		action += (/\?/.test(this.action)) ? "&" : "?";
		action += form.formSerialize();
		return action;
	}
};

//TODO START DELETE Demo purposes only
/*
Progress = {
	intervals: {},
	start: function() {
		this.count = 0;
		this.intervals.increment = setInterval(this.increment, 100);
		this.status();
	},
	increment: function() {
		Progress.count++;
	},
	status: function() {
		ProgressBar.reset(true);
		this.intervals.status = setInterval(function() {
			var _this = Progress;
			ProgressBar.update(_this.count, 100);
			if(_this.count >= 100) _this.stop();
		}, 500);
	},
	stop: function() {
		for(var interval in this.intervals) clearInterval(this.intervals[interval]);
		VideoEntryForm.success({success:true});
	}
};
VideoEntryForm.orgInit = VideoEntryForm.init;
VideoEntryForm.initDemoData = function() {
	var _this = VideoEntryForm;
	_this.orgInit();
	_this.insertDemoData();
};
//VideoEntryForm.init = VideoEntryForm.initDemoData;
VideoEntryForm.insertDemoData = function() {
	var form = $(this.form);
	var cnt = 0;
	form.find("input").each(function() {
		if(this.type != "text") return true;
		this.value = "field" + (++cnt);
	});
	var emailElem = form.find("input[name=email]");
	var email = emailElem.attr("value") + "@test.com";
	emailElem.attr("value", email);
	form.find("input[name=dateOfBirth]").attr("value", "05/04/78");
	//form.find("input[type=file]").attr("value", "/Users/eric/bin/projects/vml/OfficeDepot/build.number");
};
VideoEntryForm.orgValidate = VideoEntryForm.validate;
VideoEntryForm.validate = function(data, form, options) {
	var _this = VideoEntryForm;
	if(_this.orgValidate(data, form, options)) {
		Progress.start();
	}
	return false;
};
VideoEntryForm.isValidFileType = function(file) {
	return /.+\.(mpg|mpeg|mov|avi|wmv|number)$/i.test(file);
};
*/
// END DELETE SECTION

$(document).ready(function() {
	/*var prompts = $("input[type=text].prompt");
	prompts.focus(function() {
		if(this.value == this.defaultValue) {
			this.value = "";
			$(this).removeClass("prompt");
		}
	});
	prompts.blur(function() {
		if(this.value == "") {
			this.value = this.defaultValue;
			$(this).addClass("prompt");
		}
	});*/
	VideoEntryForm.init();
});