﻿$(function () {
	var canKeyboardNav = true;

	$(".ie").load("/public/ie.html"); // Load the IE warning into a div with a class of ie

	$("input, textarea")
    .focus(function () { canKeyboardNav = false; })
    .blur(function () { canKeyboardNav = true; });

	$(".notice").fadeIn(2500);

	$(".close").click(function () {
		$(this).parent().slideFadeToggle();
		return false;
	});

	$(".select-text").click(function () {
		var t = $(this);
		if (t.val() != this.defaultValue) { t.val(this.defaultValue); }
		t.select();
		return false;
	});

	$("#share").click(function () {
		$("#sharing").slideFadeToggle();
		return false;
	});

	$("#tumblr-share").click(function () {
		$("#embed-details:visible").slideFadeToggle();
		$("#tumblr-details").slideFadeToggle();
		return false;
	});

	$("#embed").click(function () {
		$("#tumblr-details:visible").slideFadeToggle();
		$("#embed-details").slideFadeToggle();
		return false;
	});

	$(document).keydown(function (e) {
		if (canKeyboardNav) {
			if (e.keyCode == 37) {
				keyboard_nav($("#prev"));
				return false;
			}

			if (e.keyCode == 39) {
				keyboard_nav($("#next"));
				return false;
			}
		}
	});

	function keyboard_nav(link) {
		if (link.length) { window.location.href = link.attr('href'); }
	}

	$("#fb-share").click(function (e) {
		var url = document.location.href;
		window.open('http://www.facebook.com/sharer.php?u=' + encodeURI(url) + '&t=' + encodeURIComponent(document.title), "Share on Facebook", 'width=620,height=440');
		e.preventDefault();
		return false;
	});

	$("#twitter-share").click(function (e) {
		var url = document.location.href;
		window.open('http://twitter.com/share?url=' + encodeURI(url)
			+ '&text=' + encodeURIComponent(document.title)
			+ '&via=THE_GIFNINJA',
			"Share on Twitter", 'width=620,height=240');
		e.preventDefault();
		return false;
	});

	$("#stumble-share").click(function () {
		var url = document.location.href;
		window.open('http://www.stumbleupon.com/submit?url=' + encodeURI(url)
			+ '&title=' + encodeURIComponent(document.title),
			"Share on StumbleUpon", 'width=620,height=440');
		e.preventDefault();
		return false;
	});

	/*
	var e = document.createElement('script');
	e.type = 'text/javascript';
	e.src = document.location.protocol +
	'//connect.facebook.net/en_US/all.js';
	e.async = true;
	document.getElementById('fb-root').appendChild(e);
	*/

	$(["/public/images/loading.gif"]).preload();

	//initFB();



	$("#logout").click(function () {
		FB.logout();
	});

	$("#from-facebook").click(function () {
		FB.login(function (response) {
			if (response.session && response.perms) {
				FB.api('/me/albums', function (albums) {
					for (album in albums.data) {
						$("#main").append("<h2 id='album_" + albums.data[album].id + "'>" + albums.data[album].name + "</h2>");
						FB.api(albums.data[album].id + "/photos", function (photos) {
							for (photo in photos.data) {
								$("#album_" + albums.data[album].id).append("<img src='" + photos.data[photo].source + "' />");
							}
						});
					}
				});
			}

		}, { perms: 'user_photos,user_photo_video_tags' });

		return false;
	});


	$(".tip").tooltip({
		offset: [4, 0],
		effect: 'slide',
		opacity: .9
	});

	$("#searchcontainer :text").labelify({ labelledClass: "inline_label" });
	$(".labelify").labelify({ labelledClass: "inline_label" });
	$("textarea").labelify({ labelledClass: "inline_label" });

	$("#new_comment_form textarea").focus(function () {
		var pf = $("#new_comment_form p:last");
		if (pf.is(":hidden")) {
			pf.slideFadeToggle();
		}
	});

	$("#new_comment_form a").click(function () {
		var buttons = $("#new_comment_buttons");
		if (buttons.is(":visible")) {
			$("#new_comment_form textarea").val("");
			$("#new_comment_buttons").slideFadeToggle();
		}
		return false;
	});

	$("#new_comment_form").submit(function () {
		var form = this;
		$(this).slideFadeToggle(function () {
			$("#new_comment_wait").slideFadeToggle(function () {

				$.ajax({ type: "POST",
					url: form.action,
					data: $(form).serialize(),
					success: function (data) {
						$(".comment-list").prepend($(data).hide());

						//$("#new_comment_wait, #add_new_comment").slideFadeToggle(function () {
						$(".comment-list li:first").slideFadeToggle(function () {
							$(this).effect('highlight', { color: 'yellow' }, 1500);
							$("#new_comment_wait").hide();
							$("#add_new_comment").slideFadeToggle();
						});
						//});
					},
					error: function (xhr) {
						if (xhr.status === 401) {
							$("#new_comment_wait").slideFadeToggle(function () {
								$(this).after("<div class='tooltip'>Please <a href='/login?ReturnUrl=" + location.pathname + "'>log in</a> to make comments.</div>");
								$(".tooltip").slideFadeToggle();
							});
						}
					}
				});

			});
		});

		return false;
	});

	$("#add_new_comment").click(function () {
		$("#new_comment_form textarea").val("");
		$("#add_new_comment, #new_comment_form").slideFadeToggle();
	});

	$("#contact").click(function () {


	});

	$('#FileData').uploadify({
		'uploader': '/public/swf/uploadify.swf',
		'script': '/animated-gifs/upload',
		'folder': "/" + $("#workspace").val(),
		'cancelImg': '/public/images/cancel.png',
		'multi': true,
		'auto': true,
		'simUploadLimit': 1,
		'queueSizeLimit': 130,
		'sizeLimit': 20971520,
		'onError': uploadifyError,
		'onAllComplete': function (event, data) {
			if (data.errors == 0) {
				sortImages();
			} else {
				alert("There was an error uploading your file. Please ensure that your file is smaller than 20MB and try again.");
				$("#FileData").uploadifyClearQueue();
			}
		}
	});

	$('#SplitGifButton').uploadify({
		'uploader': '/public/swf/uploadify.swf',
		'script': '/split-animated-gif/upload',
		'folder': "/" + $("#workspace").val(),
		'cancelImg': '/public/images/cancel.png',
		'multi': false,
		'auto': true,
		'simUploadLimit': 1,
		'queueSizeLimit': 50,
		'sizeLimit': 20971520,
		'onError': uploadifyError,
		'onAllComplete': function (event, data) {
			if (data.errors == 0) {
				splitGif();
			} else {
				alert("There was an error uploading your file. Please ensure that your file is smaller than 20MB and try again.");
				$("#SplitGifButton").uploadifyClearQueue();
			}
		}
	});

	function uploadifyError(event, ID, fileObj, errorObj) {
		if (errorObj.type == "File Size") {
			alert("There was an error uploading your file. Please ensure that your file is smaller than 20MB and try again.");
			$('#FileData').uploadifyCancel(ID);
			$('#SplitGifButton').uploadifyCancel(ID);
		}
	}

	$("#gif-info .show-button").click(function () {
		var button = $(this);
		$.ajax({ type: "POST",
			url: "/votes",
			data: $.param({ animatedGifID: $(this).siblings("input").val(), value: $(this).val() }, true),
			success: function (data) {
				button.parent().prepend("<div class='pop' style='float:left'>Thanks!</div><br class='clear' />");
				$('.pop').slideFadeToggle(function () {
					setTimeout(function () {
						$('.pop').slideFadeToggle(function () {
							$('.pop').next().remove();
							$('.pop').remove();
						})
					}, 3000);
				});
			},
			error: function (xhr) {
				if (xhr.status === 401) {
					$(".tooltip").remove();
					button.parent().append("<div class='tooltip'><fb:login-button>Please login to rate a gif.</fb:login-button></div>");
					initFB();
					$(".tooltip").slideFadeToggle();
				}
				if (xhr.status === 403) {
					button.parent().append("<div class='pop'>Awww, that's so cute! Keep trying. :D</div>");
					$('.pop').slideFadeToggle();
				}
			}
		});
		return false;
	});

	$("span.fb_share_no_count").each(function () {
		$(this).removeClass("fb_share_no_count");
		$(".fb_share_count_inner", this).html("0");
	});

});


$("a.delete").live("click", function () {
	var link = $(this);
	$.post(this.href, { "_method": "delete" }, function () {
		link.closest("article.post").slideFadeToggle();
	});
	return false;
});

function checkTitle() {
	if ($("#Title").val().length == 0) {
		var label = $("#Title").parent().prev().find("label");
		label.text("Title is required!");
		label.effect("shake", { times: 10 }, 100);
		return false;
	}
	return true;
}

$("#sort_images").live("click", function () {
	if (!checkTitle()) { return false; }

	var image_array = new Array();
	var imgs = $("#main form img").not("#preview");

	imgs.each(function (i, img) {
		image_array[i] = img.src.substring(img.src.lastIndexOf("/") + 1);
	});

	$("#main form").find(":submit").attr("value", "Please wait!").attr("disabled", "disabled");

	showOverlay();

	$.post($("#main form").attr("action"), $.param({ images: image_array, workspace: $("#workspace").val(), delay: $("#delay").val(), title: $("#Title").val(), caption: $("#Caption").val() }, true), function (data) {
		if (data.redirect) {
			window.location.href = data.redirect;
		} else {
			setSortImages(data);
		}
	});
	return false;
});

function showOverlay() {
	$("#overlay").overlay({
		mask: { color: '#000', loadSpeed: 200, opacity: 0.9 },
		load: true
	});
}

$("#video_to_gif").live("click", function () {
	if (!checkTitle()) { return false; }

	var form = $(this).closest("form");
	form.find(":button").attr("value", "Please wait!").attr("disabled", "disabled");

	showOverlay();

	$.post(form.attr("action"), $.param({ workspace: $("#workspace").val(), delay: $("#delay").val(), title: $("#Title").val(), caption: $("#Caption").val() }, true), function (data) {
		if (data.redirect) {
			window.location.href = data.redirect;
		} else {
			setSortImages(data);
		}
	});
	return false;
});

$("#quick_preview").live("click", runAnimation);


function sortImages() {
	$("#main").slideFadeToggle(function () {
		var f = $("#sort_images_form");
		$.post(f.attr("action"), f.serialize(), function (data) {
			$("#main").removeClass("loading");
			setSortImages(data);
		});

		$("#main").addClass("loading").fadeIn().html("");
	});
}

function splitGif() {
	$("#main").slideFadeToggle(function () {
		var f = $("#split_gif_form");
		$.post(f.attr("action"), f.serialize(), function (data) {
			$("#main").removeClass("loading").html(data);
		});

		$("#main").addClass("loading").fadeIn().html("");
	});

}

function setSortImages(data) {
	$("#main").html(data);

	$("#images.sortable").sortable();
	$("#images.sortable").disableSelection();

	var max_val = parseInt($(data).find("#maxval").val());
	var val = parseInt($(data).find("#val").val());

	$("#slider").slider({
		range: "min",
		min: 0,
		max: max_val,
		value: val,
		slide: function (event, ui) {
			var v = parseInt(ui.value);
			$("#delay").val(max_val - v + 1);
			runAnimation();
		}
	});

	runAnimation();
}

function runAnimation() {
	var i = 0;
	var count = $("#images img").length;

	if (runAnimation.prototype.h) { clearInterval(runAnimation.prototype.h); }
	runAnimation.prototype.h = setInterval(function () {
		if ($("#preview").length == 0) {
			clearInterval(runAnimation.prototype.h);
			return;
		}
		$("#preview").attr("src", $("#images img")[i++ % count].src);

	}, $("#delay").val() * 10);
}

$.fn.slideFadeToggle = function (easing, callback) {
	return this.animate({ opacity: 'toggle', height: 'toggle' }, "fast", easing, callback);
};

$.fn.labelify = function (settings) {
	settings = jQuery.extend({
		text: "title",
		labelledClass: ""
	}, settings);
	var lookups = {
		title: function (input) {
			return $(input).attr("title");
		},
		label: function (input) {
			return $("label[for=" + input.id + "]").text();
		}
	};
	var lookup;
	var jQuery_labellified_elements = $(this);
	return $(this).each(function () {
		if (typeof settings.text === "string") {
			lookup = lookups[settings.text]; // what if not there?
		} else {
			lookup = settings.text; // what if not a fn?
		};
		// bail if lookup isn't a function or if it returns undefined
		if (typeof lookup !== "function") { return; }
		var lookupval = lookup(this);
		if (!lookupval) { return; }

		// need to strip newlines because the browser strips them
		// if you set textbox.value to a string containing them    
		$(this).data("label", lookup(this).replace(/\n/g, ''));
		$(this).focus(function () {
			if (this.value === $(this).data("label")) {
				this.value = this.defaultValue;
				$(this).removeClass(settings.labelledClass);
			}
		}).blur(function () {
			if (this.value === this.defaultValue) {
				this.value = $(this).data("label");
				$(this).addClass(settings.labelledClass);
			}
		});

		var removeValuesOnExit = function () {
			jQuery_labellified_elements.each(function () {
				if (this.value === $(this).data("label")) {
					this.value = this.defaultValue;
					$(this).removeClass(settings.labelledClass);
				}
			})
		};

		$(this).parents("form").submit(removeValuesOnExit);
		$(window).unload(removeValuesOnExit);

		if (this.value !== this.defaultValue) {
			// user already started typing; don't overwrite their work!
			return;
		}
		// actually set the value
		this.value = $(this).data("label");
		$(this).addClass(settings.labelledClass);

	});
};

$.fn.preload = function () {
	this.each(function () {
		$('<img/>')[0].src = this;
	});
}

FB.init({
	appId: fbAppId, cookie: true, status: true, xfbml: true
});

FB.Event.subscribe('auth.login', function () {
	FB.api('/me', function (user) {
		if (user != null) {
			$.post("/ninja_me", user, function () {
				location.reload();
			});
		}
	});
});
