var SLIDELOG_COMMENT_CREATOR_TD_TEMPLATE = '<a href="{user_view_url}" title="{login}"><img src="{user_thumbnail}" class="user_small_thumbnail"></a>';
var SLIDELOG_COMMENT_INFO_TD_TEMPLATE = '' +
          '<a href="{user_view_url}" title="{login}">{login}</a>' +
          '<span class="postTime">({time_ago} {time_units} ago)</span>';

var SLIDELOG_COMMENT_REMOVE_LINK_TEMPLATE = '' +
		'<a class="remove_link" href="javascript: RemoveComment({id_resource}, {id_comment});" title="Delete">Delete</a>' + 
		'<div onmousedown="OnButtonMouseDown(this);" onmouseout="OnButtonMouseOut(this);" onmouseover="OnButtonMouseOver(this);" onclick="return OnButtonClick(this, \'RemoveComment({id_resource}, {id_comment})\');" class="close_button">' +
			'<div>' +
				'<div>' + 
					'<div class="center"></div>' +
				'</div>' +
			'</div>' +
		'</div>';

var SLIDELOG_GRAPHIC_COMMENT_CONTENT = '' +
		'<table class="comment_content" cellpadding="0" cellspacing="0">' +
			'<tr>' +
				'<td>' +
					'<table style="background: url(\'{image_url}\') no-repeat;" onclick="LoadCommentToPlayer({id_comment}, {id_resource});"' + 
						'onmouseover="ShowGraphicCommentMask({id_comment});" onmouseout="HideGraphicCommentMask({id_comment});"' +
						'class="graphic_comment" cellpadding="0" cellspacing="0">' +
						'<tr>' +
							'<td style="padding: 0px;">' +
								'<img src="/images/overlay_view.gif" class="graphic_comment_mask" id="graphicCommentMask{id_comment}" style="display: none;">' +
							'</td>' + 
						'</tr>' +
					'</table>' +
				'</td>' +
				'<td class="graphic_comment_text" id="commentText{id_comment}">{comment}</td>' +
			'</tr>' +
		'</table>';
        
var SLIDELOG_COMMENT_CONTENT = '<p id="commentText{id_comment}">{comment}</p>';

var SLIDELOG_COMMENTS_OPTIONS = new Object();
SLIDELOG_COMMENTS_OPTIONS.COMMENTS_PER_PAGE = 4;
SLIDELOG_COMMENTS_OPTIONS.GRAPHICAL_COMMENTS_PER_PAGE = 2;


function OpenPostCommentForm(resource)
{
    SwitchVisibility("post_comment_form" + resource);
    return false;
}

function ClosePostCommentForm(resource)
{
    SwitchVisibility("post_comment_form" + resource);
}

function PostComment(resource)
{
    var commentField = GetElement("comment" + resource);
    var comment = Trim(commentField.value);
    var idResource = resource;

    if (comment == "")
    {
        alert("Please enter text of the comment!");
        return;
    }
    
    SendComment(comment, idResource);

    commentField.value = "";
    ClosePostCommentForm(resource); 
}

function SendComment(comment, idResource)
{
    var valuesAr = 
    [
        idResource,
        comment,
        1,
        1,
        GetSlidelogCommentsPage("commentsPageNavigator" + idResource),
        SLIDELOG_COMMENTS_OPTIONS.COMMENTS_PER_PAGE  
    ];
    
    var varsAr = 
    [
        "id_resource",
        "comment",
        "text_comments",
        "all_comments",
        "page",
        "resources_per_page"
    ];
    
    ShowSlidelogCommentsLoadProgress(idResource);
    
    var queryString = UriSerialize(varsAr, valuesAr);
    var postCommentScript = "/add_resource_comment.php";
    
    ajaxpage(postCommentScript, OnSendSlidelogComment, queryString);
}

function OnSendSlidelogComment(response)
{   
    var result = ParseQueryString(response);

    var returnCode = parseInt(GetQueryStringParam(result, "code"));
    if (returnCode)
    {
        var countComments = parseInt(GetQueryStringParam(result, "count_comments"));
        var idResource = parseInt(GetQueryStringParam(result, "id_resource"));
        var comments = new Array();
        for (var i = 0; i < countComments; ++i)
        {
            var comment = new Object();
            comment.id_comment      = GetQueryStringParam(result, "id_comment" + i);
            comment.comment         = GetQueryStringParam(result, "comment" + i);
            comment.login           = GetQueryStringParam(result, "login" + i);
            comment.time_ago        = GetQueryStringParam(result, "time_ago" + i);
            comment.time_units      = GetQueryStringParam(result, "time_units" + i);
            comment.user_view_url   = GetQueryStringParam(result, "user_view_url" + i);
            comment.image_url       = GetQueryStringParam(result, "image_url" + i);
            comment.marker_xml      = GetQueryStringParam(result, "marker_xml" + i);
            comment.user_thumbnail  = GetQueryStringParam(result, "user_thumbnail" + i); 
            comment.view_url        = GetQueryStringParam(result, "view_url" + i);
            comment.is_text_comment = GetQueryStringParam(result, "is_text_comment" + i) && true;
            comment.is_removable    = GetQueryStringParam(result, "is_removable" + i) && true;
            comment.id_resource     = idResource;
            
            comments.push(comment);
        }

        var countAllComments = parseInt(GetQueryStringParam(result, "count_all_comments"));
        if (countAllComments > 0)
        {
            ShowCommentsTable(idResource);
        }
        else
        {
        	HideCommentsTable(idResource);
        }
        UpdateSlidelogCommentsCount(idResource, countAllComments);
        UpdatePageNavigator(idResource, countAllComments)
        UpdateSlidelogComments(idResource, comments);
    }
}

function UpdateSlidelogCommentsCount(idResource, countAllComments)
{
    GetElement("commentsCount"+idResource).innerHTML = countAllComments;
    GetElement("commentsHeaderCount"+idResource).innerHTML  = countAllComments;
}

function UpdatePageNavigator(idResource, countAllComments)
{
    var commentsPerPage = 10;

    var navigatorUpdater = function(idPageNavigator, idContainer, countAllComments, commentsPerPage)
    {
        if (countAllComments > commentsPerPage)
        {
            var container = GetElement(idContainer);
            if (container)
                container.style.display = '';
        }

        var countPages = Math.ceil(countAllComments / commentsPerPage);
        SetFullPageNavigatorCountPages(idPageNavigator, countPages);
    }

    commentsPerPage = SLIDELOG_COMMENTS_OPTIONS.COMMENTS_PER_PAGE;
    
    var idPageNavigator = 'commentsPageNavigator' + idResource;
    var idPageNavigatorContainer = 'comments_nav_container' + idResource;
    var idPageNavigatorBottom = 'commentsPageNavigatorBottom' + idResource;
    var idPageNavigatorBottomContainer = 'comments_nav_container_bottom' + idResource;

    navigatorUpdater(idPageNavigator, idPageNavigatorContainer, countAllComments, commentsPerPage);
    navigatorUpdater(idPageNavigatorBottom, idPageNavigatorBottomContainer, countAllComments, commentsPerPage);
}

function UpdateSlidelogComments(idResource, comments)
{
    var commentsTable = GetElement("comments_table" + idResource);
    commentsTable.cellSpacing = 0;
    commentsTable.cellPadding = 0;
    ClearSlidelogComments(commentsTable, idResource);
    HideSlidelogCommentsLoadProgress(idResource);

    for (var i = 0; i < comments.length; ++i)
    {
        var comment = comments[i];
        var tr = commentsTable.insertRow(2*i);
        
        var infoTable = document.createElement("table");
        infoTable.cellSpacing = 0;
        infoTable.cellPadding = 0;
        infoTable.style.width = "100%";
        
        infoTableTr = infoTable.insertRow(0);
        
        var creatorTd = infoTableTr.insertCell(0);
        creatorTd.className = "avatar";
        creatorTd.innerHTML = ParseTemplate(SLIDELOG_COMMENT_CREATOR_TD_TEMPLATE, comment);
        
        var infoTd = infoTableTr.insertCell(1);
        infoTd.className = "info";
        infoTd.innerHTML = ParseTemplate(SLIDELOG_COMMENT_INFO_TD_TEMPLATE, comment);
        
        if (comment.is_removable)
        {
        	var removeLinkTd = infoTableTr.insertCell(2);
        	removeLinkTd.className = "remove_link_container";
        	removeLinkTd.innerHTML = ParseTemplate(SLIDELOG_COMMENT_REMOVE_LINK_TEMPLATE, comment);
        }
        
        tr.insertCell(0).appendChild(infoTable);
        
        tr = commentsTable.insertRow(2*i + 1);
        var commentTd = tr.insertCell(0);
        commentTd.colSpan = 2;
        commentTd.className = "text";
        if (comment.is_text_comment)
        {
        	commentTd.innerHTML = ParseTemplate(SLIDELOG_COMMENT_CONTENT, comment);
        }
        else
        {
        	commentTd.innerHTML = ParseTemplate(SLIDELOG_GRAPHIC_COMMENT_CONTENT, comment);
        }
            
        AddWordWrap("commentText" + comment.id_comment, 64);    
    }

    
    commentsTable.style.display = '';
}

function ClearSlidelogComments(commentsTable, resource)
{
    var countComments = commentsTable.rows.length;
    --countComments;
        
    for (var i = 0; i < countComments; ++i)
        commentsTable.deleteRow(0);
}

function ShowSlidelogCommentsLoadProgress(resource)
{
    var commentsTable = GetElement("comments_table" + resource);
    var countComments = commentsTable.rows.length - 1;
    
    if (GetElement('comments-container' + resource).style.display == 'none')
    {
    	GetElement('comments-container' + resource).style.display = '';
    	if (!countComments)
    	{
    		var tr = commentsTable.insertRow(0);
    		var placeholder = tr.insertCell(0);
    		placeholder.style.height = "100px";
    	}
    }
    
    for (var i = 0; i < countComments; ++i)
    	commentsTable.rows.item(i).style.visibility = "hidden";
    
    GetElement("commentsLoadContainer" + resource).style.visibility = '';
    GetElement("commentsLoadIcon" + resource).style.top = -(GetElementHeight("comments_table" + resource) / 2) + "px";
}

function HideSlidelogCommentsLoadProgress(resource)
{
	GetElement("commentsLoadContainer" + resource).style.visibility = 'hidden';
}

/* Graphic Comments */

var g_loadedGraphicComment = 0;

function ShowGraphicCommentMask(idComment)
{
    GetElement("graphicCommentMask" + idComment).style.display = '';
}

function HideGraphicCommentMask(idComment)
{
    GetElement("graphicCommentMask" + idComment).style.display = 'none';
}

function LoadCommentToPlayer(idComment, idPlayer)
{
    if (g_loadedGraphicComment == idComment)
    {    
        GetFlashApp("onlinePlayer" + idPlayer).clearMarkerComment();
        UpdateGraphicCommentMask(idComment, false);
        g_loadedGraphicComment = 0;
    }
    else
    {
        if (g_loadedGraphicComment)
        {
            UpdateGraphicCommentMask(g_loadedGraphicComment, false);    
        }
        
        g_loadedGraphicComment = idComment;
        GetFlashApp("onlinePlayer" + idPlayer).loadMarkerComment(g_loadedGraphicComment);
        UpdateGraphicCommentMask(g_loadedGraphicComment, true);
    }
}

function UpdateGraphicCommentMask(idComment, isSelected)
{
    GetElement("graphicCommentMask" + idComment).className = (isSelected ? "graphic_comment_mask_hide" : "graphic_comment_mask");
}

function RefreshComments(isTextComments, idResource)
{
    ShowSlidelogCommentsLoadProgress(idResource);

    var page = 1;
    page = GetSlidelogCommentsPage("commentsPageNavigator" + idResource);
    page = parseInt(page);
    page = Math.max(page, 1);

    var commentsPerPage = SLIDELOG_COMMENTS_OPTIONS.COMMENTS_PER_PAGE;

    var values = [idResource, 1, 1, page, commentsPerPage];
    var vars = ["id_resource", "text_comments", "all_comments", "page", "resources_per_page"];

    var queryString = UriSerialize(vars, values);
    var postCommentsScript = "/add_resource_comment.php";

    ajaxpage(postCommentsScript, OnSendSlidelogComment, queryString);
}

function PrepareGraphicCommentPlaceholder(idResource)
{
	ShowSlidelogCommentsLoadProgress(idResource);
}

function ClosePostForm(idResource)
{
    GetElement("post_form" + idResource).style.display = 'none';
}

function OpenPostForm(idResource, idPost, event)
{
    var x = GetMouseOnEventXPosition(event);
    
    InitWildfire(
    	idResource, 
    	'divWildfirePost' + idResource, 
    	'playerEmbedHtml' + idResource, 
    	idPost, 
    	function ()
    	{
    		var postForm = GetElement("post_form" + idResource);
    		postForm.style.left = x - 75;
    		postForm.style.display = '';
    	},
    	function ()
    	{
    		ClosePostForm(idResource);
    	}
    );
    
    return false;
}


function OnChangeSlidelogCommentsPage(idResource)
{
    RefreshComments(false, idResource);
}

function ShowCommentsTable(idResource)
{
    var commentsTable = GetElement('comments-container' + idResource);
    if (commentsTable)
        commentsTable.style.display = '';
}

function HideCommentsTable(idResource)
{
	var commentsTable = GetElement('comments-container' + idResource);
	if (commentsTable)
		commentsTable.style.display = 'none';
}

function GetSlidelogCommentsPage(idPager)
{
    var page = 1;

    var pageNavigator = GetElement(idPager);
    if (pageNavigator)
        page = pageNavigator.currentPage;
    return page;        
}

function SetCommentsPage(idResource, page)
{
    var idPageNavigator = "commentsPageNavigator" + idResource;
    var idPageNavigatorBottom = "commentsPageNavigatorBottom" + idResource;

    SetPageNavigatorPage(idPageNavigator, page);
    SetPageNavigatorPage(idPageNavigatorBottom, page);
}

function SetPageNavigatorPage(idPageNavigator, page)
{
    var pageNavigator = GetElement(idPageNavigator);
    if (pageNavigator)
    {
        if (pageNavigator.currentPage != page)
            UpdateFullPageNavigator(idPageNavigator, page);
    }        
}

function InsertSlidelogCommentsPageNavigator(idResource, commentsCount, commentsPerPage, pagerId, pagerContainerId)
{
	var onChangePageHandler = function()
    {
        SetCommentsPage(idResource, this.currentPage);
        OnChangeSlidelogCommentsPage(idResource);
    }
	
    idResource = parseInt(idResource);
    commentsCount = parseInt(commentsCount);
    commentsPerPage = parseInt(commentsPerPage);
    var pages = Math.ceil(commentsCount / commentsPerPage);
    pages = Math.max(pages, 1);

    var pagerContainer = GetElement(pagerContainerId);

    CreateFullPageNavigator(pagerContainerId, pagerId, pages, onChangePageHandler);
    SetFullPageNavigatorCustomSettings(pagerId, 1, 1, 1);
    UpdateFullPageNavigator(pagerId, 1);

    if (pages <= 1 && pagerContainer)
        pagerContainer.style.display = 'none';    
}

function RemoveComment(idResource, idComment)
{
	var paramNames  = ["id_resource", "id_comment"];
	var paramValues = [idResource,   idComment];
	
	if (confirm(LNG_DELETE_COMMENT_CONFIRMATION))
	{
		ShowSlidelogCommentsLoadProgress(idResource);
		ajaxpage('/remove_resource_comment.php', function (response) { OnCommentRemoved(idResource, response); }, UriSerialize(paramNames, paramValues));
	}
}

function OnCommentRemoved(idResource, response)
{
	var result = ParseQueryString(response);
    var returnCode = parseInt(GetQueryStringParam(result, "code"));
    
    RefreshComments(0, idResource);
}
