//------------------------------------------------------------------------------
//
//------------------------------------------------------------------------------

function ShowLoading(block)
{
    $("#general-tip").show();
	if(block) $("#background").show();
}

function HideLoading()
{
    $("#general-tip").hide();
	$("#background").hide();
}

function GetDate()
{
    //var Months = ["января","февраля","марта","апреля","мая","июня","июля","августа","сентября","октября","ноября","декабря"];
    var Months = ["янв","фев","мар","апр","мая","июн","июл","авг","сен","окт","ноя","дек"];
    var Now = new Date();
    var Minutes = Now.getMinutes();
    Minutes = Minutes < 10 ? "0" + Minutes : Minutes;
    return Now.getDate() + " " + Months[Now.getMonth()] + " " + Now.getFullYear() + " " + Now.getHours() + ":" + Minutes;
}

$(window).bind("load", function(){
    if (!uid && $(".comments #c0").length > 0)
    {
        $(".comments #c0")[0].innerHTML = '<p class="no-access">Гости не могут оставлять комментарии. <a href="/auth/">Войти</a> или <a href="/register/">зарегистрироваться</a></p>';
    }
    if (Cooldown > 0)
    {
        ContinueCooldown();
    }
});

//------------------------------------------------------------------------------
//
//------------------------------------------------------------------------------

var Interval;

function StopCooldown()
{
    Cooldown = 0;
    $("input[@type=button].publish").each(function()
    {
        this.disabled = false;
    });
}

function StartCooldown()
{
    if (IsModerator)
    {
        Cooldown = 0;
        return;
    }
    Cooldown = 120;
    $("input[@type=button].publish").each(function()
    {
        this.disabled = true;
    });
    TimeLeft();
    Interval = setInterval("TimeLeft()", 1000);
}

function ContinueCooldown()
{
    if (IsModerator)
    {
        Cooldown = 0;
        return;
    }
    $("input[@type=button].publish").each(function()
    {
        this.disabled = true;
    });
    TimeLeft();
    Interval = setInterval("TimeLeft()", 1000);
}

function TimeLeft()
{
    Cooldown--;
    if (Cooldown > 0)
    {
        $("input[@type=button].publish").each(function()
        {
            this.disabled = true;
            this.value = this.value.replace(/\s\(\d?\d:\d\d\)/, "");
            var min = Math.round(Cooldown / 60 - 0.5);
            var sec = Cooldown % 60;
            if (sec < 10)
            {
                sec = "0" + sec;
            }
            this.value = this.value + " (" + min + ":" + sec + ")";
        });
    }
    else
    {
        $("input[@type=button].publish").each(function()
        {
            this.disabled = false;
            this.value = this.value.replace(/\s\(\d?\d:\d\d\)/, "");
        });
        clearInterval(Interval);
    }
}

function ApplyFriend(Login)
{
    ShowLoading();
    if ($.ajax({url: "/users/" + Login + "/apply-friend/", async: false}).responseText == 1)
    {
        $(".alert").hide("fast");
    }
    HideLoading();
}

function DenyFriend(Login)
{
    ShowLoading();
    if ($.ajax({url: "/users/" + Login + "/deny-friend/", async: false}).responseText == 1)
    {
        $(".alert").hide("fast");
    }
    HideLoading();
}

function RateUser(id, rate, elem)
{
    if (!uid)
    {
        alert("Гости не могут голосовать.");
        return;
    }
    ShowLoading();
    if ($.ajax({url: "/community/rateuser/" + id + "/" + rate + "/", async: false}).responseText == 1)
    {
        var RatingElem = elem.parentNode.childNodes[0];
        var Rating = parseInt(RatingElem.innerHTML);
        Rating = rate == 'plus' ? Rating + 1 : Rating - 1;
        RatingElem.innerHTML = Rating;
    }
    HideLoading();
}

function RateComment(rate, elem)
{
    if (!uid)
    {
        alert("Гости не могут голосовать.");
        return;
    }
    ShowLoading();
    var CommentID = elem.parentNode.parentNode.parentNode.id.replace(/c/, "");
    if ($.ajax({url: "/lenta/ratecomment/" + CommentID + "/" + rate + "/", async: false}).responseText == 1)
    {
        var RatingElem = elem.parentNode.childNodes[0];
        var Rating = parseInt(RatingElem.innerHTML);
        Rating = rate == 'plus' ? Rating + 1 : Rating - 1;
        RatingElem.innerHTML = Rating > 0 ? "+" + Rating : Rating;
        RatingElem.className = Rating == 0 ? "" : (Rating > 0 ? "positive" : "negative");
    }
    HideLoading();
}

function DeleteComment(CommentID)
{
    if (window.confirm("Удалить комментарий?"))
    {
        ShowLoading();
        var Metaobject = $("#c0 input[@name=metaobject]")[0].value;
        var Object = $("#c0 input[@name=object]")[0].value;
        if ($.ajax({url: "/lenta/deletecomment/" + CommentID + "/" + Metaobject + "/" + Object + "/", async: false}).responseText == 1)
        {
            $("#c" + CommentID).hide("fast");
        }
        HideLoading();
    }
}

function RateService(rate, elem)
{
    if (!uid)
    {
        alert("Гости не могут голосовать.");
        return;
    }
    ShowLoading();
    var ServiceID = elem.parentNode.parentNode.parentNode.id.replace(/s/, "");
    if ($.ajax({url: "/services/rate/" + ServiceID + "/" + rate + "/", async: false}).responseText == 1)
    {
        var RatingElem = elem.parentNode.childNodes[0];
        var Rating = parseInt(RatingElem.innerHTML);
        Rating = rate == 'plus' ? Rating + 1 : Rating - 1;
        RatingElem.innerHTML = Rating;
    }
    HideLoading();
}

function RateNews(rate, elem)
{
    if (!uid)
    {
        alert("Гости не могут голосовать.");
        return;
    }
    ShowLoading();
    var NewsID = elem.parentNode.parentNode.parentNode.id.replace(/n/, "");
    if ($.ajax({url: "/lenta/ratenews/" + NewsID + "/" + rate + "/", async: false}).responseText == 1)
    {
        var RatingElem = elem.parentNode.childNodes[0];
        var Rating = parseInt(RatingElem.innerHTML);
        Rating = rate == 'plus' ? Rating + 1 : Rating - 1;
        RatingElem.innerHTML = Rating;
    }
    HideLoading();
}

function DeleteNews(NewsID)
{
    if (window.confirm("Удалить новость?"))
    {
        ShowLoading();
        if ($.ajax({url: "/lenta/deletenews/" + NewsID + "/", async: false}).responseText == 1)
        {
            $("#n" + NewsID)[0].innerHTML = "<p><em>Новость удалена.</em></p>";
        }
        HideLoading();
    }
}

var CurLiID = "";
var ReplyCommentID = 0;

function SubmitComment(LiID)
{
    CurLiID = LiID;
    ShowLoading();
    $("#" + LiID + " .error").remove();
    $("#" + LiID + " .publish")[0].disabled = true;
    var Text = $("#" + LiID + " textarea")[0].value;
    if (Text == "")
    {
        $('<div class="error">Введите текст комментария</div>').insertBefore("#" + LiID + " textarea");
        $("#" + LiID + " .publish")[0].disabled = false;
        HideLoading();
    }
    $("#" + LiID + " input[@type=button]")[0].disabled = true;
    $.post("/lenta/postcomment/", {
        "metaobject":$("#c0 input[@name=metaobject]")[0].value,
        "object":$("#c0 input[@name=object]")[0].value,
        "text":$("#" + LiID + " textarea")[0].value.replace(/\n/mig, "_RN_"),
        "_id":ReplyCommentID
    }, function(CommentID)
    {
        if (ReplyCommentID == 0)
        {
            $(GenerateCommentHtml(CommentID, 0, Text)).insertBefore("#c0");
        }
        else
        {
            var PaddingLeft = parseInt($("#c" + ReplyCommentID)[0].style.paddingLeft);
            PaddingLeft += 26;
            var Li = $("ul.comments li");
            var InsertAfterID = 0;
            var PassedReplyToComment = false;
            var PassedReplies = false;
            for (i = 0; i < Li.length; i++)
            {
                if (Li[i].id == ReplyCommentID)
                {
                    PassedReplyToComment = true;
                }
                if (parseInt(Li[i].style.paddingLeft) == PaddingLeft && PassedReplyToComment)
                {
                    InsertAfterID = Li[i].id;
                }
                else
                {
                    if (PassedReplyToComment)
                    {
                        PassedReplies = true;
                    }
                }
                if (PassedReplies)
                {
                    break;
                }
            }
            if (InsertAfterID)
            {
                $(GenerateCommentHtml(CommentID, PaddingLeft, Text)).insertAfter("#" + InsertAfterID);
            }
            else
            {
                $(GenerateCommentHtml(CommentID, PaddingLeft, Text)).insertAfter("#c" + ReplyCommentID);
            }
        }
        $("#c" + CommentID + " a.user")[0].style.background = $("#c0 a.user")[0].style.background;
        if ($("ul.comments h2").length == 1)
        {
            $("<h2>Комментарии:</h2>").insertBefore("#c" + CommentID);
        }
        ReplyCommentID = 0;
        $("#" + LiID + " input[@type=button]")[0].disabled = false;
        StartCooldown();
        HideLoading();
    });
    CancelComment(CurLiID);
}

function GenerateCommentHtml(CommentID, PaddingLeft, Text)
{
    var Login = $("#c0 .user b")[0].innerHTML;
    var AuthorLogin = $(".infobar .user b")[0].innerHTML;
    Text = Text.replace(/\n/mig, "<br />");
    return '<li class="comment' + (AuthorLogin == Login ? ' author' : '') + '" id="c' + CommentID + '"  style="padding-left:' + PaddingLeft + 'px;">' +
        '<a name="c' + CommentID + '"></a>' +
    	'<div class="infobar">' +
    		'<a class="user" href="/users/' + Login + '/"><b>' + Login + '</b></a>' +
    		'<span class="date">' + GetDate() + '</span>' +
    		'<span title="Рейтинг комментария" class="rating"><b class="">0</b><a title="Нравится" class="up" href="javascript:void(0);" onclick="RateComment(\'plus\', this);"></a><a title="Не нравится" class="down" href="javascript:void(0);" onclick="RateComment(\'minus\', this);"></a></span>' +
    		'<a class="reply" href="javascript:void(0);" onclick="ReplyComment(' + CommentID + ');">Ответить</a>' +
    		(IsModerator ? '<a class="delete" href="javascript:void(0);" onclick="DeleteComment(\'' + CommentID + '\');">Удалить</a>' : '') +
    	'</div>' +
    	'<div class="text">' + Text + '</div>' +
    '</li>';
}

function CancelComment(LiID)
{
    $("#" + LiID + " textarea")[0].value = "";
    $("#" + LiID + " .publish")[0].disabled = false;
    if (LiID != "c0")
    {
        $("#" + LiID).remove();
    }
}

function ReplyComment(CommentID)
{
    if (!uid)
    {
        alert("Гости не могут оставлять комментарии.");
        return;
    }
	if ($('li[@rel=c'+CommentID+']').is(':visible'))
	{
		$('li[@rel=c'+CommentID+']').remove();
		return;
	}
	if ($('#cR').is(':visible'))
	{
		$('#cR').remove();
	}
    ReplyCommentID = CommentID;
    var Login = $("#c0 .user b")[0].innerHTML;
    var PaddingLeft = $("#c" + CommentID)[0].style.paddingLeft;
    PaddingLeft += 26;
    var CommentForm = '<li class="comment" id="cR" rel="c'+CommentID+'" style="display:none; padding-left:' + PaddingLeft + 'px;">' +
            	'<div class="comment-reply">' +
    				'<div class="infobar">' +
    					'<i class="isreply"></i>' +
    					'<a class="user" href="/me/"><b>' + Login + '</b></a>' +
    				'</div>' +
    				//'<div class="text">' + $("#c" + CommentID + " .text")[0].innerHTML + '</div>' +
    				'<form action="/lenta/postcomment/" target="service" method="post" id="comment-form">' +
    					'<textarea name="text"></textarea>' +
    					'<span class="cancel aslink" onclick="CancelComment(\'cR\');">Отмена</span>' +
    					//'<!--input class="preview" type="submit" value="Предпросмотр" /-->' +
    					'<input class="publish" type="button" value="Написать" onclick="SubmitComment(\'cR\');" />' +
    				'</form>' +
    			'</div>' +
			'</li>';
	CurLiID ="cR";
    $(CommentForm).appendTo("#c" + CommentID);
	$("#cR").show('fast', function()
	{
		$("#cR textarea").focus();
	});
	$("#cR a.user")[0].style.background = $("#c0 a.user")[0].style.background;
}

function RatePhoto(rate, elem)
{
    if (!uid)
    {
        alert("Гости не могут голосовать.");
        return;
    }
    ShowLoading();
    if ($.ajax({url: "/photos/action=ratephoto/id=" + Photos[CurPhoto].id + "/" + rate + "/", async: false}).responseText == 1)
    {
        var RatingElem = elem.parentNode.childNodes[0];
        var Rating = parseInt(RatingElem.innerHTML);
        Rating = rate == 'plus' ? Rating + 1 : Rating - 1;
        RatingElem.innerHTML = Rating;
        Photos[CurPhoto].rating = Rating;
    }
    HideLoading();
}

var CurPhoto = 0;

function RotatePhotos(i)
{
    ShowLoading();
    ProfilePhotosCancelEditPhotoAbout();
    $(".album-thumbs li")[CurPhoto].className = "";
    if (i === '-1')
    {
        CurPhoto--;
    }
    else if (i === '+1')
    {
        CurPhoto++;
    }
    else
    {
        CurPhoto = i;
    }

    if (CurPhoto == Photos.length)
    {
        CurPhoto = 0;
    }
    if (CurPhoto == -1)
    {
        CurPhoto = Photos.length - 1;
    }
    if (Photos[CurPhoto] == null)
    {
        RotatePhotos('+1');
    }
    else
    {
        $("#photo-img")[0].src = '/@images/' + Photos[CurPhoto].path;
        $("#photo-comment")[0].innerHTML = Photos[CurPhoto].comment;
        $("#photo-rating")[0].innerHTML = Photos[CurPhoto].rating;
        $("#photo-dt")[0].innerHTML = Photos[CurPhoto].dt;
        $(".album-thumbs li")[CurPhoto].className = "cur";
        document.location.hash = CurPhoto;
        HideLoading();
    }
}

//------------------------------------------------------------------------------
// Profile
//------------------------------------------------------------------------------

function ProfileDeletePhoto()
{
    if (window.confirm("Удалить фотографию?"))
    {
        $.ajax({url: "/me/deletephoto/", async: false});
        $("#photo").hide("fast");
        $("#photo-delete-link").hide("fast");
    }
}

$(window).load(function()
{
    if (document.getElementById("upload-fotos-form"))
    {
        $('#upload-fotos-form select[@name=album_id]').bind('change', function()
        {
        	var newname = $('#upload-fotos-form input[@name=name]');
        	if ($(this).find('option:selected').attr('value') == '0')
        	{
        		newname.show();
        		newname.select();
        	}
        	else
        	{
        		newname.hide();
        	}
        });
        if ($('#upload-fotos-form select[@name=album_id]')[0].options.length == 1)
        {
            var newname = $('#upload-fotos-form input[@name=name]');
            newname.show();
    		newname.select();
        }
    }
});

//------------------------------------------------------------------------------
// Photos
//------------------------------------------------------------------------------

var ProfilePhotosAddCounter = 0;

function ProfilePhotosAddFileInput(obj)
{
	ProfilePhotosAddCounter++;
    $(obj).parent('div:first').after('<div class="fileinput"><input name="photo_' + ProfilePhotosAddCounter + '" type="file" /> <b onclick="ProfilePhotosAddFileInput(this)" class="plus">+</b> <b onclick="ProfilePhotosRemoveFileInput(this)" class="minus">&minus;</b></div>')
}

function ProfilePhotosRemoveFileInput(obj)
{
	$(obj).parent('div:first').remove();
}

function ProfilePhotosEditAlbumTitle(AlbumID)
{
	$("div.photo-title h1").html('<form action="/photos/action=renamealbum/id=' + AlbumID + '/" method="post" target="service">'+
		'<input name="name" class="title" value="'+$('div.photo-title h1')[0].innerHTML+'" />' +
		'<div class="buttons"><input type="submit" value="Сохранить" onclick="ShowLoading();" /> <input type="button" value="Отмена" onclick="ProfilePhotosCancelEditAlbumTitle();" /></div>'+
		'</form>');
	$('div.photo-title input').focus();
	$('div.photo-title div.edit').hide();
}

function ProfilePhotosCancelEditAlbumTitle()
{
	$("div.photo-title h1")[0].innerHTML = $("div.photo-title input")[0].value;
	$("div.photo-title div.edit").show();
}

function ProfilePhotosDeleteAlbum(AlbumID)
{
    if (window.confirm("Удалить альбом?"))
    {
        ShowLoading();
        $.ajax({url: "/photos/action=deletealbum/id=" + AlbumID + "/", async: false});
		document.location.href = $('a[@rel=user-albums-link]').attr('href') || "/photos/";
    }
}

function ProfilePhotosEditPhotoAbout()
{
	$('div.photo-about div.text')[0].innerHTML = '<form action="/photos/action=commentphoto/id=' + Photos[CurPhoto].id + '/" method="post" target="service">'+
		'<textarea name="comment">' + $('div.photo-about div.text')[0].innerHTML + '</textarea>'+
		'<br /><input type="submit" value="Сохранить" onclick="ShowLoading();" /> <input type="button" value="Отмена" onclick="ProfilePhotosCancelEditPhotoAbout();" />'+
		'</form>';
	$('div.photo-about textarea').focus();
	$('div.photo-about div.edit').hide();
}

function PhotosUpdatePhotoAbout()
{
    Photos[CurPhoto].comment = $('div.photo-about textarea')[0].value;
}

function ProfilePhotosCancelEditPhotoAbout()
{
	if ($('div.photo-about textarea').length > 0)
	{
        $('div.photo-about div.text')[0].innerHTML = $('div.photo-about textarea')[0].value;
    	$('div.photo-about div.edit').show();
	}
}

function ProfilePhotosDeletePhoto()
{
	var ask_delete = "Удалить фотографию?";
	if($('ul.album-thumbs').children(':visible').length == 1) ask_delete = "Удалить единственную фотографию (вместе с альбомом)?";
    if (window.confirm(ask_delete))
    {
        ShowLoading();
        $.ajax({url: "/photos/action=deletephoto/id=" + Photos[CurPhoto].id + "/", async: false});
        Photos[CurPhoto] = null;
        $($(".album-thumbs li")[CurPhoto]).hide();
        if( $('ul.album-thumbs').children(':visible').length > 0) {
			RotatePhotos('+1');
		} else {
			document.location.href = $('a[@rel=user-albums-link]').attr('href') || "/photos/";
		}
        HideLoading();
    }
}
