﻿var fbloggedin = false;
var gotperm = false;
$(function(){
	var fbpermissions = function(submitafter){
		FB.Facebook.apiClient.users_hasAppPermission('publish_stream', function(res){
			if (res != 1) {
				gotperm = false;
				FB.Connect.showPermissionDialog('publish_stream', function(perms){
					if (perms != null && perms.length > 0) {
						gotperm = (perms.indexOf("publish_stream") > -1);
						$.getJSON("fb/recordAction.ashx?m=perms&r="+perms);
					}
					$("#fb")[0].checked = gotperm;
					if (submitafter)
						$("#submit input").click();
				});
			} else {
				gotperm = true;
				$("#fb")[0].checked = true;
				if (submitafter)
					$("#submit input").click();
			}
		});
	};
	var fbconnect = function(submitafter){
		FB.Connect.requireSession();
		FB.Facebook.get_sessionWaitable().waitUntilReady(function(){
			fbloggedin = true;
			fbpermissions(submitafter);
			$.getJSON("fb/setUser.ashx", {fbid: FB.Facebook.apiClient.get_session().uid});
		});
	};
	$("#fb").change(function(){
		if (this.checked && !gotperm) {
			FB.Connect.ifUserConnected(function(uid){
				fbloggedin = true;
				fbpermissions();
				$.getJSON("fb/setUser.ashx", {fbid: uid});
			}, fbconnect);
		}
	});
	$("#personalinfo").validate({success: "valid", rules: {
		first: "required",
		last: "required",
		email: {
			required: true,
			email: true
		}
	}, errorElement: "span", errorPlacement: function(error, element){
		error.appendTo(element.prev());
	}});

	setTimeout(function(){
		$("#reply").css("visibility", "visible");
	}, 5000);
	var bar = $("#bar")[0];
	var per = $("#progress span")[0];
	var done = $("#done")[0];
	var rem = $("#remaining")[0];

	var inQueue = 0;
	var queueSize = 0;
	var updateQueueSize = function(add){
		inQueue += (add < 0 ? -1 : 1);
		queueSize += add;
		if (inQueue > 0)
			$("#browser span").html("<b>" + inQueue + "</b> total - <b>" + $.ui.uploader.formatSize(queueSize) + "</b> of 100mb used <em>(<b>" + $.ui.uploader.formatSize(104857600 - queueSize) + "</b> available)</em>");
		else {
			$("#browser span").empty();
			$("#agree,#submit").hide();
			$("#browser").removeClass("sep");
			$("#uiUploader")[0].changeText("select files");
		}
	};
	var errorCount = 0;
	var showError = function(msg){
		var r = $("#reply").html(msg);
		setTimeout(function(){
			r.empty();
		}, 10000);
	};
	$("#submit input").click(function(){
		if ($("#personalinfo").valid()) {
			var fid = false;
			$("#queue form").each(function(){
				if (!$(this).valid() && !fid)
					fid = $(this).parent().attr("id");
			});
			if (!fid) {
				if ($("#agree input[name='agreed']")[0].checked) {
					if (!gotperm && $("#fb")[0].checked) {
						$("#fb")[0].checked = false;
						if (fbloggedin)
							fbpermissions(true);
						else
							fbconnect(true);
					} else
						$("#uiUploader")[0].queueUploadNext();
				} else
					showError("You must agree to the Graphics Submission Agreement before uploading.");
			} else
				$.scrollTo("#" + fid, 1000, {offset: -10, onAfter: function(){alert("Please fix the errors marked in red.");}});
		} else
			$.scrollTo("#personalinfo", 1000, {offset: -100, onAfter: function(){alert("Please fix the errors marked in red.");}});
	});
	
	var keywordsDefaultText = "ADD YOUR OWN SPECIFIC KEYWORDS HERE\nseparate with commas";

	$().uploader({
		name: 'uiUploader',
		fileFilters: ['ZIP or JPG files (*.zip,*.jpg)|*.zip;*.jpg;*.jpeg'],
		maxFileSize: 61440,
		maxQueueCount: -1,
		maxQueueSize: 102400,
		backendScript: 'submission.ashx?guid=' + guid,
		movie: 'cmykuploader.swf',
		width: '120',
		height: '28',
		wmode: 'window',
		callback: {
			UploaderInitialized: function(o){
				$("#reply").empty();
			},
			dialogPreShow: function(o){},
			dialogPostShow: function(o){},
			queueEmpty: function(o){
				showError("There are no files in the queue to upload.");
			},
			queueErrorCount: function(o){},
			queueErrorSize: function(o){
				alert("You have exceeded the 100mb total size limit. One or more files were not added.");
			},
			queueStarted: function(o){
				errorCount = 0;
				$("#reply").empty();
				per.innerHTML = "0%";
				bar.style.width = "0%";
				done.innerHTML = "";
				rem.innerHTML = "";
				$("#progress").parent().add("#noclose").show();
				done.style.display = "block";
				rem.style.display = "block";
			},
			queueCancelled: function(o){},
			queueCompleted: function(){
				var cmp = function(){
					if (errorCount > 0)
						$("#reply").html("There was an error with one or more of your uploads. Any successful uploads are now awaiting approval before being added to the site.");
					else
						$("#reply").html("Artwork uploaded successfully! Now awaiting approval before being added to the site.");
					per.className = "";
					$("#progress").parent().add("#noclose").hide();
					done.style.display = "none";
					rem.style.display = "none";
					$("#queue").children().slideUp(function(){
						$(this).remove();
					});
					inQueue = 1;
					updateQueueSize(-queueSize);
				};
				if ($.active > 0) {
					$().bind("ajaxStop", function(){
						$().unbind("ajaxStop");
						cmp();
					});
				} else
					cmp();
			},
			fileAdded: function(o){
				updateQueueSize(o.file.size);
				$("#uiUploader")[0].changeText("add more files");
				$("#browser").addClass("sep");
				var zj = (o.file.name.indexOf(".zip") == o.file.name.length - 4 ? "zip" : "jpg");
				$('<div id="d' + o.file.id + '" class="' + zj + 'details"></div>').appendTo("#queue").load("submit_" + zj + ".aspx?guid=" + guid, function(){
					$(this).slideDown(function(){
						$("#agree,#submit").show();
					}).each(function(){
						if (zj == "zip") {
							$(this).children().validate({success: "valid", rules: {
								title: "required",
								width: {number: true},
								height: {number: true},
								dpi: {digits: true},
								description: "required",
								thumbnail: {required: true, accept: true}
							}, messages: {
								thumbnail: {accept: "<br />Please select either a JPG, GIF, or PNG file."}
							}, errorElement: "span", errorPlacement: function(error, element){
								if (element.attr("name") == "height")
									error.appendTo(element.prev().prev().prev());
								else
									error.appendTo(element.prev());
							}});
						} else {
							$(this).children().validate({success: "valid", rules: {
								title: "required",
								description: "required"
							}, errorElement: "span", errorPlacement: function(error, element){
								error.appendTo(element.prev());
							}});
						}
					}).find("input:eq(0)").val(o.file.name).next().val(o.file.size).next().children("span").html(o.file.name + " <em>(" + $.ui.uploader.formatSize(o.file.size) + ")</em>").next().click(function(){
						if (confirm("Are you sure you want to remove '" + o.file.name + "'?"))
							$("#uiUploader")[0].fileCancel(o.file.id);
						return false;
					}).parent().next().next().val(o.file.name.replace(/\.(jpe?g|zip)/i, "")).siblings("div.keywords").find("textarea").val(keywordsDefaultText).each(function(){
						keywordsDefaultText = this.value;
					}).focus(function(){
						if (this.value == keywordsDefaultText)
							this.value = "";
					}).blur(function(){
						if ($.trim(this.value).length == 0)
							this.value = keywordsDefaultText;
					}).end().find("input").click(function(){
						var ta = $(this).parent().siblings("textarea").focus()[0];
						if (this.checked) {
							if (ta.value.length > 0)
								ta.value += ", " + this.value;
							else
								ta.value = this.value;
						} else
							ta.value = ta.value.replace(", " + this.value, "").replace(this.value + ", ", "").replace(this.value, "");
						$(ta).blur();
					});
				});
			},
			fileRemoved: function(o){
				$("#d" + o.file.id).slideUp(function(){
					$(this).remove();
				});
				updateQueueSize(-o.file.size);
			},
			fileStarted: function(o){
				$("#noclose div").html("<b>Currently Uploading:</b> " + o.file.name);
			},
			fileProgress: function(o){
				per.innerHTML = o.progress.qProgress + "%";
				if (o.progress.qProgress >= 50)
					per.className = "half";
				bar.style.width = o.progress.qProgress + "%";
				done.innerHTML = $.ui.uploader.formatSize(o.progress.qbDone) + " of " + $.ui.uploader.formatSize(o.progress.qbTotal);
				rem.innerHTML = "Time Remaining: " + $.ui.uploader.formatTime(o.progress.qtRemain) + " (" + $.ui.uploader.formatSize(o.progress.qbSpeed) + "/sec)";
			},
			fileCancelled: function(o){},
			fileCompleted: function(o){
				var pi = $("#personalinfo input");
				$("#d" + o.file.id + " form").each(function(){
					$("input[name='first']", this).val(pi[0].value);
					$("input[name='last']", this).val(pi[1].value);
					$("input[name='email']", this).val(pi[2].value);
					$("input[name='website']", this).val(pi[3].value);
					$("input[name='fb']", this).val((gotperm && $("#fb")[0].checked) ? "yes" : "no");
				}).ajaxSubmit({dataType: 'json', success: function(data){
					if (!data.success) {
						errorCount++;
						if (data.error.length > 0)
							alert(data.error);
					}
				}});
			},
			fileErrorSize: function(o){
				alert("A file you selected '" + o.file.name + "' exceeds the maximum filesize of 60mb and was not added.");
			},
			fileErrorIO: function(o){
				errorCount++;
				alert("An error occurred during the upload of '" + o.file.name + "'.\nPlease try that file again after the upload is complete.");
			},
			fileErrorSecurity: function(o){
				errorCount++;
				alert("A security error occurred during the upload of '" + o.file.name + "'.\nPlease try that file again after the upload is complete.\nError: " + o.errorString);
			},
			fileErrorHTTP: function(o){
				errorCount++;
				var m;
				switch (o.errorCode) {
					case 501:
						m = "'" + o.file.name + "' is not a valid ZIP file or is empty.\nPlease try a different file after the upload is complete.";
						break;
					case 502:
						m = "'" + o.file.name + "' is not a valid JPG file.\nPlease try a different file after the upload is complete.";
						break;
					case 503:
						m = "'" + o.file.name + "' is not at least 574 pixels wide or 355 pixels high.\nPlease try a different file that meets these minimum dimensions after the upload is complete.";
						break;
					default:
						m = "An error occurred during the upload of '" + o.file.name + "', please try this file again after the upload is complete.";
				}
				alert(m);
			}
		}
	});
});