GALLERY_UPLOADER_MAX_TAGS = 3;

var TAGS_BINDING = {};

$(function($) {
	$("body").append("<div id=galSuccVoteDiv class=succvotediv>Cпасибо за Ваш голос!</div><div id=sel_avatar class=sel_cover><a class=sel_cover_close href=# onclick='profile_selavatar_close();return false' title='Закрыть'><img src=/img/front/close.gif></a><center>Выберите картинку-аватар для загрузки</center><form method=POST enctype='multipart/form-data' action='/user/upload-avatar'><table cellspacing=2><tr><td class=selavatarComment><span class=comment>Изображение должно быть в одном из форматов JPEG/GIF/PNG; размер изображения не должен превышать 200x400 пикселей, загружаемый файл должен быть не более 35kb</span></tr><tr><th><input type=file name=image id=selavatarImage></tr><tr><th class=selavatarOk><input type=submit class=grad value=' Загрузить ' onclick='return profile_selavatar_check()'></tr></table></form></div>");

	recentGalleryCommentsInit();
	recentGalleryCommentsMyInit();

	$("a.unFavouritePhoto").attr("href", "#").attr("title", "Удалить из избранных").hover(
		function () { $(this).find("img.unFavouriteCross").show() },
		function () { $(this).find("img.unFavouriteCross").hide() }).click(
		function () {
			var favMode = typeof GALLERY_LISTING_FAVOURITE != "undefined";
			if (!favMode && !confirm("Вы действительно хотите удалить фотографию из избранных?")) return false;
			var element = $(this);
			var id = element.attr("binding");
			var serial = element.attr("id").substring(16);
			var options = {
				url: "/gallery/removefav",
				data: { "id" : id },
				dataType: "json",
				success: function(response, status) {
					if (response["ok"]) {
						if (favMode) location.reload();
						else {
							element.hide();
							$("#favouritePhoto" + serial).show();
						}
					}
				}
			}
			$.ajax(options);
			return false;
		});

	$("a.favouritePhoto").attr("href", "#").attr("title", "Добавить в избранные").click(
		function () {
			var element = $(this);
			var id = element.attr("binding");
			var serial = element.attr("id").substring(14);
			var options = {
				url: "/gallery/addfav",
				data: { "id" : id },
				dataType: "json",
				success: function(response, status) {
					if (response["ok"]) {
						element.hide();
						$("#unFavouritePhoto" + serial).show();
					}
				}
			}
			$.ajax(options);
			return false;
		});

	$(".imgBoxImage").hover(
		function() { var serial = $(this).attr("id").substring(11); if ($("#unFavouritePhoto" + serial).is(":hidden")) $("#favouritePhoto" + serial).css("visibility", "visible"); },
		function() { $("#favouritePhoto" + $(this).attr("id").substring(11)).css("visibility", "hidden"); }
	);

	var galleryNoLimits = typeof GALLERY_NO_LIMITS != "undefined";

	$("body").append("<div id=sel_tags class=sel_cover><a class=sel_cover_close href=# onclick='seltag_close();return false' title='Закрыть'><img src=/img/front/close.gif></a><center>Укажите теги для фотографии</center><table cellspacing=2>" + (galleryNoLimits ? "" : "<tr><td class=tagsComment><span class=comment>Вы можете указать не более 3-х тегов для каждой фотографии</span></tr>") + "<tr><td><div class=tagsList></div></tr><tr><th class=tagsOk><input type=button class=grad value=' ОК ' onclick='seltag_select();return false'></tr></table></div>");
	
	if (typeof TAGS_LIST != "undefined") {
		for (var i in TAGS_LIST) {
			$("div.tagsList").append("<input class=tagcb type=checkbox id=tagcb" + i + " binding='" + i + "'><label for=tagcb" + i + " id=tagl" + i + "> <span></span></label><br>");
			$("#tagl" + i + " span").text(TAGS_LIST[i].tag);
		}
		if (!galleryNoLimits)
			$("input.tagcb").change(function () {
				var checked = $("input.tagcb:checked");
				var binding = $(this).attr("binding");
				if (checked.length > GALLERY_UPLOADER_MAX_TAGS)
					for (var i = 0; i != checked.length; i++) {
						var elem = checked.eq(i);
						if (elem.attr("binding") != binding) {
							elem.attr("checked", "");
							break;
						}
					}
			});
		seltags_bind();
	}

	$("div.votediv img").hover(function() { $(this).addClass("activeRate") },
				   function() { $(this).removeClass("activeRate") });
});
img_marks = {};
function img_mark(id) {
	$("#imgmark" + id).css("visibility", img_marks[id] ? "hidden" : "visible");
	if (img_marks[id]) {
		delete img_marks[id];
		$("#aimgmark" + id).attr("title", "Отметить");
	} else {
		img_marks[id] = 1;
		$("#aimgmark" + id).attr("title", "Снять отметку");
	}
	$("#editable" + id).children(".editbar").css("visibility", "hidden");
	var img_marks_nonempty = false;
	for (var key in img_marks) {
		img_marks_nonempty = true;
		break;
	}
	if (img_marks_nonempty) {
		$("#moveto_sel").removeAttr("disabled");
		$("#delete_sel").removeAttr("disabled");
	} else {
		$("#moveto_sel").attr("disabled", true);
		$("#delete_sel").attr("disabled", true);
}
}
function img_edit(id, gal) {
	var result = prompt("Задайте новую подпись для " + (gal ? "фотоальбома": "фотографии"), $("#aimg" + id).attr("title"));
	if (result == null) return;
	var options = {
		url: "/gallery/imgtitle",
		data: { "id": id, "title" : result },
		dataType: "json",
		success: function(response, status) {
			if (response["ok"]) {
				$("#aimg" + id).attr("title", result);
				$("#atitle" + id).attr("title", result);
				$("#atitle" + id).html(response["subtitle_wrapped"]);
			}
			return false;
		}
	};
	$.ajax(options);
}

function img_delete(id) {
	if (confirm("Вы действительно хотите удалить изображение?"))
		location = "/gallery/imgdelete?id=" + id;
}
function imgs_delete() {
	if (confirm("Вы действительно хотите удалить все отмеченные изображения?")) {
		var keys = [];
		for (var key in img_marks)
			keys[keys.length] = key;
		location = "/gallery/imgdelete?id=" + keys.join(",");
	}
}
function gal_delete(id) {
	if (confirm("Вы действительно хотите удалить фотоальбом целиком? Будут удалены все фотографии, входящие в фотоальбом."))
		location = "/gallery/imgdelete?id=" + id;
}
function gal_share(id) {
	if (confirm("Вы действительно хотите сделать фотоальбом публичным? Публичный фотоальбом невозможно превратить обратно в личный."))
		location = "/gallery/galshare?id=" + id;
}

var RECENT_GALLERY_COMMENTS_BOX_WIDTH = 60;
var RECENT_GALLERY_COMMENTS_BOX_HEIGHT = 60;
var RECENT_GALLERY_COMMENTS_OPTIONS = {
		url: "/gallery/getrecentcomments",
		dataType: "json",
		success: function(response, status) {
			recentGalleryCommentsSuccess(response, "");
		},
		error: function(request, status, err) {
			recentGalleryCommentsError("");
			return false;
		}
};
var RECENT_GALLERY_COMMENTS_MY_OPTIONS = {
		url: "/gallery/getrecentcomments",
		data: { "mine" : true },
		dataType: "json",
		success: function(response, status) {
			recentGalleryCommentsSuccess(response, "My");
		},
		error: function(request, status, err) {
			recentGalleryCommentsError("My");
			return false;
		}
};

function recentGalleryCommentsSuccess(response, profile) {
	$("#galleryLastCommentsLoading" + profile).hide();
	$("#galleryLastCommentsTable" + profile).empty();
	if (response["ok"]) {
		if (response.comments.length > 0) {
			for (var i = 0; i != response.comments.length; i++) {
				var comment = response.comments[i];
				$("#galleryLastCommentsTable" + profile).append("<tr id=galleryLastCommentsTr" + profile + comment.id + "><th><a href=/gallery/" + comment.parent_gallery_id + "#photo" + comment.id_gallery + "><img></a><td><span class=recentCommentsAuthor>[<a class=recentCommentsAuthor></a>]</span> <span class=recentCommentsDate></span> <span class=recentCommentsComment></span></tr>");
				$("#galleryLastCommentsTr" + profile + comment.id + " th a").attr("title", comment.photo_title);
				var box = imgGetBox(comment["width"], comment["height"], RECENT_GALLERY_COMMENTS_BOX_WIDTH, RECENT_GALLERY_COMMENTS_BOX_HEIGHT);
				$("#galleryLastCommentsTr" + profile + comment.id + " th img").attr("src", "/img/gallery/" + comment.image_small).css({ "width" : box.w + "px", "height" : box.h + "px" });
				$("#galleryLastCommentsTr" + profile + comment.id + " td a.recentCommentsAuthor").text(comment.author_name.htmlizeSpaces());
				if (comment.id_users) $("#galleryLastCommentsTr" + profile + comment.id + " td a.recentCommentsAuthor").attr("href", "/user/" + comment.id_users + "/profile");
				$("#galleryLastCommentsTr" + profile + comment.id + " td span.recentCommentsDate").text(new Date(comment.created_ts * 1000).format("shortDate"));
				$("#galleryLastCommentsTr" + profile + comment.id + " td span.recentCommentsComment").html(comment.comment_wrapped).attr("title", comment.comment);
			}
			$("#galleryLastCommentsNone" + profile).hide();
			$("#galleryLastComments" + profile).show();
		} else {
			$("#galleryLastComments" + profile).hide();
			$("#galleryLastCommentsNone" + profile).show();
		}
	} else
		recentGalleryCommentsError(profile);
}

function recentGalleryCommentsError(profile) {
	$("#galleryLastCommentsLoading" + profile).hide();
	$("#galleryLastComments" + profile).hide();
	$("#galleryLastCommentsNone" + profile).show();
}

function recentGalleryCommentsInit() {
	if ($("#galleryLastCommentsLoading").length == 0) return;
	$.ajax(RECENT_GALLERY_COMMENTS_OPTIONS);
}

function recentGalleryCommentsMyInit() {
	if ($("#galleryLastCommentsLoadingMy").length == 0) return;
	$.ajax(RECENT_GALLERY_COMMENTS_MY_OPTIONS);
}

function img_gallery_disallow_upload() {
	alert("Администраторы сайта не разрешают вам загружать фотографии и создавать новые фотоальбомы");
	return false;
}

function img_gallery_disallow_create() {
	alert("Администраторы сайта не разрешают вам создавать новые фотоальбомы");
	return false;
}

function img_gallery_upload() {
	tb_show('', '/gallery/upload-select?height=480&width=640', false);
}

function profile_avatar_select() {
	tb_show('', '/user/select-avatar-list?height=480&width=640', false);
}

function profile_avatar_upload() {
	var element = $("#selectAvatarDiv");
	var pos = element.offset();
	$("#sel_avatar").css({ "left" : (pos.left + element.outerWidth()) + "px", "top" : (pos.top + 5) + "px" }).fadeIn(600);
	return false;
}

function profile_selavatar_close() {
	$("#sel_avatar").fadeOut(600);
}

function profile_selavatar_check() {
	return document.getElementById("selavatarimage").value != "";
}

function img_gallery_favowner_remove(id) {
	var options = {
		url: "/gallery/removefavowner",
		data: { "id" : id },
		dataType: "json",
		success: function(response, status) {
			if (response["ok"]) {
				$("#favowner" + id).remove();
				var rows = $("#favowners tr");
				if (rows.length < 2) rows.show();
			}
			return false;
		}
	};
	$.ajax(options);
}

function seltag_open() {
	if ($("#sel_tags").is(":visible")) {
		seltag_close();
		return false;
	}
	var id = $(this).attr("binding");
	$("input.tagcb").attr("checked", "");
	if (typeof TAGS_BINDING[id] != "undefined")
		for (var i = 0; i != TAGS_BINDING[id].length; i++)
			$("#tagcb" + TAGS_BINDING[id][i]).attr("checked", true);
	var element = $(this).parent();
	var pos = element.offset();
	var mode = element.attr("mode");
	$("#sel_tags").css(mode == "nofit" ?
				{ "width" : "250px", "left" : (pos.left + element.outerWidth() - 250) + "px", "top" : (pos.top + element.outerHeight() + 2) + "px" } :
				{ "left" : pos.left + "px", "top" : (mode == "bigtable" ? $(this).offset().top + $(this).outerHeight() + 2 : pos.top) + "px", "width" : element.width() + "px" }).attr("binding", id).fadeIn(600);
	return false;
}

function seltag_close() {
	$("#sel_tags").fadeOut(600);
}

function seltag_select() {
	var joined = [];
	$("input.tagcb:checked").each(function () { joined[joined.length] = $(this).attr("binding") });
	var id = $("#sel_tags").attr("binding");
	TAGS_BINDING[id] = joined;
	$("#image_tags" + id).val(joined.join(","));
	if (joined.length > 0) {
		var names = [];
		for (var i = 0; i != joined.length; i++)
			names[i] = TAGS_LIST[joined[i]].tag;
		$("#tagsA" + id).css("font-style", "normal").text(names.join(", "));
	} else
		$("#tagsA" + id).css("font-style", "italic").text("указать");
	$("#sel_tags").fadeOut(600);
	if (typeof seltag_select_done == "function") seltag_select_done();
}

function seltags_bind() {
	$("a.tags").unbind("click").click(seltag_open).attr({ "title" : "задать теги для фотографии", "href" : "#" });
}
