var recordings = {}, recording = false, soundBlob = null, recordTimer = null;
$(document).ready(function() {
	var fpbxForm = $(".fpbx-submit");
	var prevpage = fpbxForm.data("fpbx-prevpage");
	if (!prevpage || prevpage.length === 0) {
		$("#btnBack").prop("disabled", true);
	}

	/** File Drop **/
	//Stop the browser from showing us the file we dropped.
	//Thaaaaaanx chrome, I dont want to see it
	$('.dropzone').on('drop dragover', function (e) {
		e.preventDefault();
	});
	//remove our cool class when we drop or leave
	$('.dropzone').on('dragleave drop', function (e) {
		$(this).removeClass("activate");
	});
	//add our cool class when we hover a file to be dropped
	$('.dropzone').on('dragover', function (e) {
		$(this).addClass("activate");
	});
	//the upload container magic (note this is an each)
	$(".fileupload-container").each(function() {
		var input = $(this).find(".input-upload"),
				dropzone = $(this).find(".dropzone"),
				progressBar = $(this).find(".progress-bar"),
				key = $(this).data("key");

		input.fileupload({
			dataType: 'json',
			dropZone: dropzone,
			add: function (e, data) {
				//build pattern of supported formats
				var sup = "\.("+supportedRegExp+")$",
						patt = new RegExp(sup),
						submit = true;
				//only one file is allowed here
				if(data.files.length > 1) {
					alert(_("Only one file is allowed at a time"));
					return false;
				}
				//loop over files... file
				$.each(data.files, function(k, v) {
					if(!patt.test(v.name.toLowerCase())) {
						submit = false;
						alert(_("Unsupported file type"));
						return false;
					}
				});
				//ok they look good now submit
				if(submit) {
					data.submit();
				}
			},
			//what to do when the file is dropped
			drop: function () {
				progressBar.css("width", "0%");
			},
			//drag over, same thing
			dragover: function (e, data) {
			},
			change: function (e, data) {
			},
			//file has been uploaded. AJAX done.
			done: function (e, data) {
				if(data.result.status) {
					$("#jquery_jplayer_"+key).jPlayer( "clearMedia" );
					recordings[key] = data.result.localfilename;
				} else {
					alert(data.result.message);
				}
			},
			//during progress
			progressall: function (e, data) {
				var progress = parseInt(data.loaded / data.total * 100, 10);
				progressBar.css("width", progress+"%");
			},
			//AJAX Faile: file failed :-(
			fail: function (e, data) {
			},
			//AJAX Always
			always: function (e, data) {
			}
		});
	});
	/** End file Drop **/

	/** In-Browser Playback **/
	$(".browser-player-container").each(function() {
		var key = $(this).data("key"),
				uploadProgress = $(this).find(".browser-recorder-progress"),
				player = $("#jquery_jplayer_"+key),
				container = player.data("container");

		//show it
		$(this).removeClass("hidden");
		$("#jquery_jplayer_"+key).jPlayer({
			ready: function(event) {
				$("#"+container + " .jp-play").click(function() {
					if(!player.data("jPlayer").status.srcSet) {
						$("#"+container).addClass("jp-state-loading");
						//it is a temp file OR a system file
						if(typeof recordings[key] !== "undefined" || !isNaN(parseInt(player.data("recording-id")))) {
							var type = (typeof recordings[key] !== "undefined") ? "temp" : "system",
									id = (typeof recordings[key] !== "undefined") ? recordings[key] : player.data("recording-id");
							//get our html5 file, hope we have one
							$.ajax({
								type: 'POST',
								url: "ajax.php",
								data: {module: "oembranding", command: "gethtml5", id: id, type: type},
								dataType: 'json',
								timeout: 30000,
								success: function(data) {
									if(data.status) {
										player.on($.jPlayer.event.error, function(event) {
											$("#"+container).removeClass("jp-state-loading");
											console.log(event);
										});
										player.one($.jPlayer.event.canplay, function(event) {
											$("#"+container).removeClass("jp-state-loading");
											player.jPlayer("play");
										});
										player.jPlayer( "setMedia", data.files);
									} else {
										alert(data.message);
										$("#"+container).removeClass("jp-state-loading");
									}
								}
							});
						} else {
							alert(_("No file to load!"));
						}
					} else {
						//source is already set
					}
				});
			},
			//moves our ball
			timeupdate: function(event) {
				$("#jp_container_"+key).find(".jp-ball").css("left",event.jPlayer.status.currentPercentAbsolute + "%");
			},
			//puts our ball back at the start
			ended: function(event) {
				$("#jp_container_"+key).find(".jp-ball").css("left","0%");
			},
			cssSelectorAncestor: "#jp_container_"+key,
			swfPath: "http://jplayer.org/latest/dist/jplayer",
			supplied: supportedHTML5,
			wmode: "window",
			useStateClassSkin: true,
			autoBlur: false,
			keyEnabled: true,
			remainingDuration: true,
			toggleDuration: true
		});
		var acontainer = null;
		$('#jp_container_'+key+' .jp-play-bar').mousedown(function (e) {
			acontainer = $(this).parents(".jp-audio-freepbx");
			updatebar(e.pageX);
		});
		$(document).mouseup(function (e) {
			if (acontainer) {
				updatebar(e.pageX);
				acontainer = null;
			}
		});
		$(document).mousemove(function (e) {
			if (acontainer) {
				updatebar(e.pageX);
			}
		});

		//update Progress Bar control
		var updatebar = function (x) {
			var player = $("#" + acontainer.data("player")),
					progress = acontainer.find('.jp-progress'),
					maxduration = player.data("jPlayer").status.duration,
					position = x - progress.offset().left,
					percentage = 100 * position / progress.width();

			//Check within range
			if (percentage > 100) {
				percentage = 100;
			}
			if (percentage < 0) {
				percentage = 0;
			}

			player.jPlayer("playHead", percentage);

			//Update progress bar and video currenttime
			acontainer.find('.jp-ball').css('left', percentage+'%');
			acontainer.find('.jp-play-bar').css('width', percentage + '%');
			player.jPlayer.currentTime = maxduration * percentage / 100;
		};
	});
	/** End In Browser Playback **/

	/** Start In Browser Recording **/
	//check if this browser supports WebRTC and we are in HTTPS
	if (Modernizr.getusermedia && window.location.protocol == "https:") {
		if($(".browser-recorder-container").length && typeof Recorder === "undefined") {
			$.getScript( "assets/oembranding/js/recorder.js", function( data, textStatus, jqxhr ) {
			});
		}
		$(".browser-recorder-container").each(function() {
			var key = $(this).data("key"),
					uploadProgress = $(this).find(".browser-recorder-progress");
			//show in browser recording if it does
			$(this).removeClass("hidden");
			$("#jquery_jrecorder_"+key).jPlayer({
				ready: function(event) {

				},
				timeupdate: function(event) {
					$("#jr_container_"+key).find(".jp-ball").css("left",event.jPlayer.status.currentPercentAbsolute + "%");
				},
				ended: function(event) {
					$("#jr_container_"+key).find(".jp-ball").css("left","0%");
				},
				cssSelectorAncestor: "#jr_container_"+key,
				swfPath: "http://jplayer.org/latest/dist/jplayer",
				supplied: "wav",
				wmode: "window",
				useStateClassSkin: true,
				autoBlur: false,
				keyEnabled: true,
				remainingDuration: true,
				toggleDuration: true
			});
			var acontainer = null;
			$('#jr_container_'+key+' .jp-play-bar').mousedown(function (e) {
				acontainer = $(this).parents(".jp-audio-freepbx");
				updatebar(e.pageX);
			});
			$(document).mouseup(function (e) {
				if (acontainer) {
					updatebar(e.pageX);
					acontainer = null;
				}
			});
			$(document).mousemove(function (e) {
				if (acontainer) {
					updatebar(e.pageX);
				}
			});

			//update Progress Bar control
			var updatebar = function (x) {
				var player = $("#" + acontainer.data("player")),
						progress = acontainer.find('.jp-progress'),
						maxduration = player.data("jPlayer").status.duration,
						position = x - progress.offset().left,
						percentage = 100 * position / progress.width();

				//Check within range
				if (percentage > 100) {
					percentage = 100;
				}
				if (percentage < 0) {
					percentage = 0;
				}

				player.jPlayer("playHead", percentage);

				//Update progress bar and video currenttime
				acontainer.find('.jp-ball').css('left', percentage+'%');
				acontainer.find('.jp-play-bar').css('width', percentage + '%');
				player.jPlayer.currentTime = maxduration * percentage / 100;
			};
			//find the record button in this container
			$(this).find(".record").click(function() {
				var counter = $("#jr_container_"+key+" .jp-duration"),
						title = $("#jr_container_"+key+" .jp-title"),
						player = $("#jquery_jrecorder_"+key),
						controls = $(this).parents(".jp-controls"),
						url = $(this).data("url");

				controls.toggleClass("recording");
				player.jPlayer( "clearMedia" );
				//previously recording
				if (recording) {
					//stop timer
					clearInterval(recordTimer);
					//action buttons
					title.html('<button id="saverecording" class="btn btn-primary" type="button">'+_("Save Recording")+'</button><button id="deleterecording" class="btn btn-primary" type="button">'+_("Delete Recording")+'</button>');

					//save recording
					$("#saverecording").one("click", function() {
						//clear media for upload
						player.jPlayer( "clearMedia" );
						var data = new FormData(),
								name = Math.random().toString(36).replace(/[^a-z]+/g, '').substr(0, 15);
						//attach our file to the formdata object
						data.append("file", soundBlob);
						$.ajax({
							type: "POST",
							url: url + "&filename=" + encodeURIComponent(name),
							xhr: function() {
								uploadProgress.removeClass("hidden").addClass("in");
								var xhr = new window.XMLHttpRequest();
								//Upload progress
								xhr.upload.addEventListener("progress", function(evt) {
									if (evt.lengthComputable) {
										var percentComplete = evt.loaded / evt.total,
										progress = Math.round(percentComplete * 100);
										uploadProgress.find(".progress-bar").css("width", progress + "%");
										if(progress == 100) {
											uploadProgress.addClass("hidden").removeClass("in");
											uploadProgress.find(".progress-bar").css("width", "0%");
										}
									}
								}, false);
								return xhr;
							},
							data: data,
							processData: false,
							contentType: false,
							success: function(data) {
								if(data.status) {
									recordings[key] = data.localfilename;
								}
								title.html(_("Hit the red record button to start recording from your browser"));

								var url = (window.URL || window.webkitURL).createObjectURL(soundBlob);
								$("#jquery_jplayer_"+key).jPlayer( "setMedia", {
									wav: url
								});
							},
							error: function(e) {
								console.log(e);
								console.log("there was an error and it sucked");
							}
						});
					});
					//delete recording
					$("#deleterecording").one("click", function() {
						soundBlob = null; //I think?
						$("#jquery_jrecorder_"+key).jPlayer( "clearMedia" );
						title.html(_("Hit the red record button to start recording from your browser"));
					});
					//stop the recorder
					recorder.stop();
					//export the wav into a blob
					recorder.exportWAV(function(blob) {
						//put the blob in our global
						soundBlob = blob;
						//map URL and get URL
						var url = (window.URL || window.webkitURL).createObjectURL(blob);
						//assign jplayer the blob (cant believe this works)
						player.jPlayer( "setMedia", {
							wav: url
						});
					});
					recording = false;
				} else {
					//map webkit prefix
					window.AudioContext = window.AudioContext || window.webkitAudioContext;
					var context = new AudioContext(),
					gUM = Modernizr.prefixed("getUserMedia", navigator);

					//start the recording!
					gUM({ audio: true }, function(stream) {
						var mediaStreamSource = context.createMediaStreamSource(stream);
						//worker is already loaded but it doesnt seem to cause any issues. eh.
						recorder = new Recorder(mediaStreamSource,{ workerPath: "assets/oembranding/js/recorderWorker.js" });
						recorder.record();
						startTime = new Date();
						//create a normal minutes:seconds timer from micro/milli-seconds
						recordTimer = setInterval(function () {
							var mil = (new Date() - startTime),
									temp = (mil / 1000),
									min = ("0" + Math.floor((temp %= 3600) / 60)).slice(-2),
									sec = ("0" + Math.round(temp % 60)).slice(-2);
							counter.text(min + ":" + sec);
						}, 1000);
						title.text(_("Recording..."));
						recording = true;
					}, function(e) {
						controls.toggleClass("recording");
						alert(_("Your Browser Blocked The Recording, Please check your settings"));
						recording = false;
					});
				}
			});
		});
	} else {
		//hide in browser recording if it does not
		$(".browser-recorder-container").remove();
	}
	/** End In Browser Recording **/

	$("#btnNext").click(function() {
		invalid = false;
		$("*[required]").each(function() {
			/* Basic validation of required controls that aren't handled properly via HTML. */
			switch ($(this).prop("type")) {
			case "select-one":
				if ($(this).val() === "") {
					name = $(this).prop("name");
					if (name !== "") {
						/* Grab the label for this control*/
						alert($("label[for='" + name + "']").text() + " is a required field.");
					} else {
						alert("A required field is not set.");
					}
					invalid = true;
					return invalid;
				}
				break;
			}
		});
		if (invalid === true) {
			return;
		}

		$(this).text('Processing...');

		//are there recordings?
		$.each(recordings, function(k, v){
			$("#" + k).val(v);
		});

		var formData = new FormData($(".fpbx-submit")[0]);

		$.ajax({
			url: "ajax.php?module=oembranding&command=answeroobequestion",
			data: formData,
			contentType: false,
			processData: false,
			type: 'POST'
		}).done(function() {
			window.location.reload()
		});
	});

	$("#btnBack").click(function() {
		$.ajax({
			url: window.ajaxurl,
			data: { command: 'prevoobequestion', module: 'oembranding', pagename: prevpage }
		}).done(function() {
			window.location.reload()
		});
	});

	$("#btnAbort").click(function() {
		$.ajax({
			url: window.ajaxurl,
			data: { command: 'abortoobe', module: 'oembranding' }
		}).done(function() {
			window.location.reload()
		});
	});

	$(".wizard-field").change(function(e) {
		updateVisibility();
	});

	$("[class*='shared-']").change(function(e) {
		updateShared();
	});

	updateVisibility();
	updateShared();
});

function updateVisibility() {
	$("div[visibility-fields]").each(function() {
		fields = $(this).attr("visibility-fields").split(",");

		for (i = 0; i < fields.length; i++) {
			field = fields[i];

			visibility = $(this).attr("visibility-" + field);

			ctrl = $("[name='" + field + "']");
			switch ($(ctrl).prop("type")) {
			case "radio":
				value = $(ctrl).filter(":checked").val();
				break;
			default:
				value = $(ctrl).val();
				break;
			}

			if (value == visibility) {
				$(this).removeClass("hidden");
			} else {
				$(this).addClass("hidden");
			}
		}
	});
}

function updateShared() {
	var regex = /shared-\w*/;
	var inuse = {};
	/* Two-step process.  First enable everything and add the values to a list. */
	$("[class*='shared-']").each(function() {
		var sharedclass = regex.exec($(this).attr('class'));
		$(this).children('option').removeAttr('disabled');
		if ($(this).val() !== '') {
			if ($.inArray(sharedclass, inuse)) {
				inuse[sharedclass] = [];
			}
			inuse[sharedclass].push($(this).val());
		}
	});

	/* Then disable any in-use options that aren't already selected. */
	$("[class*='shared-'] > option:not(:selected)").each(function() {
		var sharedclass = regex.exec($(this).parent().attr('class'));
		if ($.inArray($(this).val(), inuse[sharedclass]) != -1) {
			$(this).attr('disabled', true);
		}
	});
}
