$(document).ready(function() {
	
	$(".spoiler > button").livequery('click', function() {
		$(this).next().toggle();
	});

	$("[class^=bbcode]").livequery('click', function(event) {
		var bbcode = $(this).text();
		var start = $("#TextBody")[0].selectionStart;
		var end = $("#TextBody")[0].selectionEnd;
		var textVal = $("#TextBody").val();
		var selected = textVal.substring(start, end);
		var toSelected = textVal.substring(0, start);
		var fromSelected = textVal.substring(end);
		$("#TextBody").val(toSelected + '[' + bbcode + ']' + selected + '[/' + bbcode + ']' + fromSelected);
		event.preventDefault();
		return false;
	});

	$("[rel=add]").livequery('click', function() {
		$(this).before('<img src="/img/interface/ajax.gif" id="ajax">');
		$(this).closest("[rev=edit]").after('<div rev="edit"></div>');
		$(this).closest("[rev=edit]").next().load($(this).attr('href'), function () {
				$("#ajax").remove();
		});
		return false;
	});

	$("[rel=edit]").livequery('click', function() {
		$(this).before('<img src="/img/interface/ajax.gif" id="ajax">');
		$(this).closest("[rev=edit]").load($(this).attr('href'), function () {
				$("#ajax").remove();
		});
		return false;
	});

	$("[rel=editform]").livequery('click', function() {
		var that = $(this);
		$.ajax({
			   beforeSend: function () {
						that.before('<img src="/img/interface/ajax.gif" id="ajax">');
				},
				type: "POST",
				url: $(this).closest("[rev=edit] form").attr('action'),
				data: $(this).closest("[rev=edit] form").serialize(),
				success: function(data){
						that.closest("[rev=edit]").html(data);
						$("#ajax").remove();
				}
		});
		return false;
	});

	$(".message").fadeIn(1000);
	var time = $(".message").text().length;
	var time = time / 30 * 1000;
					
	setTimeout( function() { 
			$(".message").fadeOut(1000); 
	}, time);
								

	$(".filter").livequery(function(){ 
			$(this).change(function() {
				$(".all").hide();
				var show = '';
				 $(".filter").each(function (i) {
					 show = show + "." + $(this).val();
					 
				});
				$(show).show();
                                $("#items_count").text($(show).show().length);
			});
	});


	$("[rel^=loadajax]").each(function (i) {
		var rel = $(this).attr('rel');
		var targetId = rel.substring(rel.indexOf('>') + 1);
		$(this).load(targetId, function() { $(this).fadeIn(); } );
      });

	$("#show").livequery('click', function() {
		$(".role3").css({'display' : 'inline-block'});
		$(this).hide();
		$("#hide").show();
		return false;
	});

	$("#hide").livequery('click', function() {
		$(".role3").hide();
		$(this).hide();
		$("#show").show();
		return false;
	});
	
	var greeting = $("#help").html();
	$(".hover").hover(
		function () { 
				$("#help").text($(this).attr('alt'));
		}, function () { 
			$("#help").html(greeting); 
		}
	);

	$(".insertmerge").click (function () {
		$('#RevDramaAlert').val($('#RevDramaAlert').val()+$(this).attr('href')+"\n"); 
		return false;
	});

	$(".searchbutton").hover(
		function () { $("#searchhelp").text($(this).attr('value')); },
		function () { $("#searchhelp").text(''); }
	);

	$(".searchbutton").click (function () {
		//$("#PageSearchForm").attr('action', $(this).attr('id'));
		if ($(this).attr('value') == 'dramas') window.location = "/" + $(this).attr('value') + "/search/?method[title]=0&title=" + $("#PageSearch").val() + "&method[nativetitle]=0&nativetitle=" +  $("#PageSearch").val() + "&method[english]=0&english=" +  $("#PageSearch").val() + "&method[aka]=0&aka=" +  $("#PageSearch").val() + "&or=1";
		else window.location = "/" + $(this).attr('value') + "/search/?" + $(this).attr('id') + "=%25" + $("#PageSearch").val() + "%25";
		return false;
	});

	$(".show_status").livequery('click', function() {
		$(".status").hide();
		$(".completed_rewatching").hide();
		$("." + ($(this).attr('id'))).show();
		$("#status").text($(this).attr('href'));
		if ($(this).attr('id') == 'status_3') $(".completed_rewatching").show();
		return false;
	});
                
	$("#ItemStatusId").livequery(function(){ 
			$(this).change(function() {
				switch($(this).val()) {
					case '3':
						$('#ItemProgress option:last').attr('selected','selected');
						break;
				}
				//if ($(this).val() == 3) $('#ItemProgress option:last').attr('selected','selected');
			});
	});

	$("#RevRoleType").livequery(function(e){
		$(this).change(function(e) {
			if ($(this).val() != 'actor') {
				$('#RoleRole').hide();
				$('#RevRoleRole').val(1);
				$('#RoleName').hide();
				$('#RevRoleName').val('-');
				$('#RoleNativename').hide();
				$('#RevRoleNativename').val('-');
				$('#RevRoleKana').val('-');
				$('#RoleKana').hide();
			} else {
				$('#RoleRole').show();
				$('#RevRoleRole').val('');
				$('#RoleName').show();
				$('#RevRoleName').val('');
				$('#RoleNativename').show();
				$('#RevRoleNativename').val('');
				$('#RevRoleKana').val('');
				$('#RoleKana').show();
			}
		});
	});
	
	$("[name^=tip]").livequery(function(e){
		$(this).hover(function(e) {
			var text = $(this).attr('name').substring($(this).attr('name').indexOf(':') + 1);
			$(this).after('<span id="tip" style="display: none"><span>' + text + '</span></span>');
			$("#tip").fadeIn();
		}, function() {
			$("#tip").remove();
		})
	});
	
	$("#cancel").livequery('click', function() {
		$("#big_loader").remove();
		return false;
	});
	
	$("[rel^=ajaxnew]").livequery('click', function() {
		if ($('#formAjax').length) {
				alert('You already have an open form, submit it and try again.');
				return false;
		}
		$("body").after("<div id=\"big_loader\"><img src=\"/img/interface/bigloader.gif\" /></div>");
		$("#big_loader").load($(this).attr('href'),  function() {
				$("#ajaxform input[type=submit]").after("<input id=\"cancel\" type=\"submit\" value=\"Cancel\"/>");
				$("#ajaxform").fadeIn();
		});
		return false;
	});
	
	$("#ajaxform input[type=submit]").livequery('click', function() {
			if ($(this).val() == "Submit") {
				$.ajax({
					type: "POST",
						url: $("#ajaxform form").attr('action'),
						data: $("#ajaxform form").serialize() + "&data[meta][submit]=" + $(this).val(),
						dataType: "json",
						success: function(data) {
							if (data.success == true) {
								$("#ajaxform").html("<span id=\"message\">" + data.message + " Redirecting in 2 seconds or <a href=\"" +  data.redirect + "\"><u>now</u></a>.</span>");
								setTimeout( function() { 
									$("#big_loader").fadeOut(); 
 									top.location.href = data.redirect;
								}, 2000);
							} else {
								$(".field-error").remove();
								$.each(data.errors, function(field, value){
									$("[name='data[" + data.model + "][" + field + "]']").before('<span class="field-error">' + value + '</span>');
								});
								$(".field-error").fadeIn();
							}
						}
				});
			}
			return false;
	});

	$("[rel^=ajax]").livequery('click', function() {
		if ($('#formAjax').length) {
				alert('You already have an open form, submit it and try again.');
				return false;
		}
		var rel = $(this).attr('rel');
		var targetId = rel.substring(rel.indexOf('>') + 1);
		$("#" + targetId).after(" <img id=\"loader\" src=\"/img/interface/loader.gif\" />");
		$("#" + targetId).fadeOut("normal");
		$("#" + targetId).load($(this).attr('href'), function() {
			$("#" + targetId).fadeIn("normal");	
			$("#loader").remove();
		});
		return false;
	});
        
	$("[rel^=formajax]").livequery('click', function() {
		var rel = $(this).attr('rel');
		var targetId = rel.substring(rel.indexOf('>') + 1);
		var dataAjax = $("#formAjax").serialize() + "&data[meta][submit]=" + $(this).val(); + "&data[meta][backlink]=#" + targetId;
		$.ajax({
			beforeSend: function () {
				$("#" + targetId).after(" <img id=\"loader\" src=\"/img/interface/loader.gif\" />");
			},
			type: "POST",
			url: $("#formAjax").attr('action'),
			data: dataAjax,
			success: function(text) {
				if (text.substr(0,1) == '<') {
					$("#" + targetId).html(text);
					$("#loader").remove();
				} else {
					$("#" + targetId).html(text);
				}
			}
		});
		return false;
	});
	
	$("[rel^=formAjan]").livequery('click', function() {
		var dataAjax = $("#formAjax").serialize() + "&data[meta][submit]=" + $(this).val();
		$.ajax({
			type: "POST",
			url: $("#formAjax").attr('action'),
			data: dataAjax,
			dataType: "json",	
			success: function(data) {
				$.each(data, function(i,item){
					eval(item);
				});
			}
		});
		return false;
	});
	

                  $(".faddtolist")
                        .livequery('click', function() {
                                var id = $(this).attr('id').split('_').pop();
                                $("#editfriend").remove();
                                $(".faddtolist").show();
                                $(this).before("<div id=\"editfriend\" style=\"display: inline\" />");
                                $(this).hide();
                                $("#editfriend").html("&nbsp;<img src=\"/img/interface/loader.gif\" />");
                                $("#editfriend").load("/items/editfriend/" + id);
                                return false;
                        });

      

                $(".updatefriend")
                        .livequery('click', function() {
                                var id = $(this).attr('id').split('_').pop();
                                var str = $("#editfriend_form").serialize();
                                var status = $("#ItemStatusId").val();
                                $.ajax({
                                       beforeSend: function () {
                                                $("#editfriend").html("<img src=\"/img/interface/loader.gif\" />");
                                        },
                                       type: "POST",
                                       url: "/items/editfriend/" + id,
                                       data: str + "&data[Item][submit]=" + $(this).val(),
                                       success: function(text){
                                                $("#editfriend").text(text);
                                                $("#faddtolist_" + id).show();
                                       }
                                });
                                return false;
                        });

        });


