﻿function DisplayDiscussionElement(event, control, visibleText, hiddenText, discussionType)
{
    var divs = $($(control).parentNode).select('div');
    var node = $(control).select('b');    
    
    if(divs.length > 0)
    {
        if(divs[0].style.display == 'block' || divs[0].style.display == '')
        {
            $(discussionType).style.display = 'none';
            
            divs[0].style.display = 'none';
            control.className = Constants.StyleSheetClasses.CollapsedNode;
            
            if(node.length > 0)
            {
                if(node[0].innerHTML == hiddenText)
                {
                    node[0].innerHTML = visibleText;
                }
                else
                {
                    node[0].innerHTML = hiddenText;
                }
            }
        }
        else
        {
            $(discussionType).style.display = 'block';
        
            divs[0].style.display = 'block';
            control.className = Constants.StyleSheetClasses.ExpandedNode;
            
            if(node.length > 0)
            {
                if(node[0].innerHTML == hiddenText)
                {
                    node[0].innerHTML = visibleText;
                }
                else
                {
                    node[0].innerHTML = hiddenText;
                }
            }      
        }
    }
}

function HandlePostResult(rpcResult, button)
{
    if(rpcResult != null)
    {
        if(rpcResult.OperationResult)
        {
            $(ClientIDs.PostMessage).update(new Element('img', { 'src': '../../Images/checkmark_small.gif', alt: ''}));
            $(ClientIDs.PostMessage).insert(new Element('span').update(rpcResult.Message));
            $(ClientIDs.CardPostText).value = rpcResult.Data.PostText;
                    
            var popularPost = $('PopularPost' + rpcResult.Data.ID);
            var recentPost = $('RecentPost' + rpcResult.Data.ID);
            
            if(popularPost == null)
            {
            }
            
            if(recentPost == null)
            {
                var postDiv = new Element('div', { 'class': 'post newItem', 'id': 'RecentPost' + rpcResult.Data.ID }).addClassName('post newItem');
                var newPostSpan = new Element('span').update(rpcResult.Data.ParsedPost);
                var postDetails = new Element('div', { 'class': 'postDetails' }).addClassName('postDetails');
                var postedBy = new Element('div', { 'class': 'postedBy' }).addClassName('postedBy');
                var postedByLink = new Element('a', { 'href': 'javascript:void(0);' }).update(rpcResult.Data.PostedByPersonaName);
                var postedByDate = new Element('span').update(' (' + rpcResult.Data.DisplayDatePosted + ')');
                var clearBreak = new Element('br', { 'class': 'clear' }).addClassName('clear');
                var postRating = new Element('div', { 'class': 'postRating' }).addClassName('postRating');
                var postRatingLabel = new Element('div', { 'class': 'postRatingLabel' }).addClassName('postRatingLabel').update('Rating:&nbsp;');
                var starRatingContainer = new Element('div', { 'style': 'float: left;' });
                var starRatingContainer2 = new Element('div', { 'class': 'starRating' }).addClassName('starRating');
                var clearBreak2 = new Element('br', { 'class': 'clear' }).addClassName('clear');
                var lineBreak = new Element('br');
                
                for(var i = 0; i < 10; i++)
                {
                    if(i % 2 == 0)
                    {
                        starRatingContainer2.insert(new Element('img', { 'src': '../../Images/Stars/LeftClearSmall.gif', alt: i + 1 }));
                    }
                    else
                    {
                        starRatingContainer2.insert(new Element('img', { 'src': '../../Images/Stars/RightClearSmall.gif', alt: i + 1 }));
                    }
                }  
                
                starRatingContainer2.insert(lineBreak);
                starRatingContainer.insert(starRatingContainer2);
                postRating.insert(postRatingLabel);
                postRating.insert(starRatingContainer);
                postRating.insert(clearBreak2);
                
                postDiv.insert(newPostSpan);
                postedBy.insert(postedByLink);
                postedBy.insert(postedByDate);
                postDetails.insert(postedBy);
                postDetails.insert(postRating);                                
                postDiv.insert(postDetails);
                postDiv.insert(clearBreak);
                
                var stem = 'bottomMiddle';
        
                // Internet Explorer 7 hack, for some reason, bottomMiddle isn't working on IE.
                if(document.all)
                {
                    stem = 'bottomLeft';                        
                }
                
                var tip = new Tip(postedByLink, {
                        showOn: 'click',
                        title: new Element('a', { 'href': '/Pages/Search/Default.aspx?action=advanced&user=+[' + postedByLink.innerHTML + ']', 'title': 'Find all cards with comments by ' + postedByLink.innerHTML + '.'}).update(postedByLink.innerHTML),
                        hideOn: { element: 'closeButton', event: 'click'},	        
                        stem: stem,
                        hook: { target: 'topMiddle', tip: 'bottomMiddle' },
                        offset: { x: 0, y: -2 },
                        width: '335px',
                        ajax: {
                            url: UserInformationHandler,
                            options: {
                                method: 'get',
                                parameters: { method: 'GetUserInformation', userName: encodeURI(postedByLink.innerHTML), date: new Date().getTime() }                        
                            }
                        }
                    });
                
                var currentPosts = $('RecentPost').select('.post');
                
                if(currentPosts != null && currentPosts.length == 1)
                {
                    if(currentPosts[0].className == 'post zeroItem')
                    {
                        currentPosts[0].remove();
                    }
                }
                
                $('RecentPost').insert(postDiv);
            }
            
            var postSpan = null;
            var postSpan2 = null;
            
            if(popularPost != null)
            {
                postSpan = popularPost.select('span');
            }
            
            if(recentPost != null)
            {
                postSpan2 = recentPost.select('span');
            }
            
            if(postSpan != null && postSpan.length >= 1 && postSpan[0] != null)
            {
                postSpan[0].update(rpcResult.Data.ParsedPost);
            }  
            
            if(postSpan2 != null && postSpan2.length >= 1 && postSpan2[0] != null)
            {
                postSpan2[0].update(rpcResult.Data.ParsedPost);
            }                      
            
            var starContainer = $$('.' + Constants.StyleSheetClasses.PostForm)[0].select('.' + Constants.StyleSheetClasses.StarRating)[0];
            
            UpdateRelatedStarsAfterVote(starContainer, rpcResult.Data.Rating.Rating, rpcResult.Data.Rating.DisplayRating, rpcResult.Data.Rating.TotalVotes, Constants.StyleSheetClasses.Star);
            
            $(ClientIDs.PostDate).update(rpcResult.Data.DisplayDatePosted);
        }
        else
        {
            var linkElement = new Element('a', { 'href': '../Help.aspx#exclamationpoint' }).update(new Element('img', { 'src': '../../Images/exclamation_small.gif', alt: ''}));
            
            $(ClientIDs.PostMessage).update(linkElement);
            $(ClientIDs.PostMessage).insert(new Element('span').update(rpcResult.Message));
        }
    }
    else
    {
        var linkElement = new Element('a', { 'href': '../Help.aspx#exclamationpoint' }).update(new Element('img', { 'src': '../../Images/exclamation_small.gif', alt: ''}));
        
        $(ClientIDs.PostMessage).update(linkElement);
    }
    
    button.disabled = false;
}

function HandlePostDeleteResult(rpcResult, button)
{
    if(rpcResult != null)
    {
        if(rpcResult.OperationResult)
        {
            $(ClientIDs.PostMessage).update(new Element('img', { 'src': '../../Images/checkmark_small.gif', alt: ''}));
            $(ClientIDs.PostMessage).insert(new Element('span').update(rpcResult.Message));
            $(ClientIDs.CardPostText).value = '';
            
            cardDatabase.SetTextBoxValue('blur', $(ClientIDs.CardPostText));
            
            var popularPost = $('PopularPost' + rpcResult.Data);
            var recentPost = $('RecentPost' + rpcResult.Data);
            
            if(popularPost != null)
            {
                popularPost.remove();
            }
            
            if(recentPost != null)
            {
                recentPost.remove();
            }
        }
        else
        {
            var linkElement = new Element('a', { 'href': '../Help.aspx#exclamationpoint' }).update(new Element('img', { 'src': '../../Images/exclamation_small.gif', alt: ''}));
        
            $(ClientIDs.PostMessage).update(linkElement);
            $(ClientIDs.PostMessage).insert(new Element('span').update(rpcResult.Message));
        }
    }
    
    button.disabled = false;
}

function Delete(event, control)
{
    control.disabled = true;
    
    new Ajax.Request(utilitiesHandler , {
            method: 'post',
            parameters: { method: 'DeleteCardComment', printedcarduniqueid: printedCardUniqueID },
            onSuccess:  function(transport) {
                var result = eval('(' + transport.responseText + ')');
                
                HandlePostDeleteResult(result, control);
            },
            onFailure: function(transport) {
                var result = eval('(' + transport.responseText + ')');
                
                HandlePostDeleteResult(result, control);
            }      
        }); 
}

function Post(event, control)
{
    control.disabled = true;
    
    var textArea = $(ClientIDs.CardPostText);
    
    if(textArea.value.length <= maximumPostLength)
    {
        new Ajax.Request(utilitiesHandler , {
                method: 'post',
                parameters: { method: 'CommentOnCard', printedcarduniqueid: printedCardUniqueID, multiverseid: multiverseID, post: textArea.value },
                onSuccess:  function(transport) {
                    var result = eval('(' + transport.responseText + ')');
                    
                    HandlePostResult(result, control);
                },
                onFailure: function(transport) {
                    var result = eval('(' + transport.responseText + ')');
                    
                    HandlePostResult(result, control);
                }      
            });
    }
    else
    {
        var linkElement = new Element('a', { 'href': '../Help.aspx#exclamationpoint' }).update(new Element('img', { 'src': '../../Images/exclamation_small.gif', alt: ''}));
        
        $(ClientIDs.PostMessage).update(linkElement);
        $(ClientIDs.PostMessage).insert(new Element('span').update(maximumPostError.replace('{0}', maximumPostLength)));
        
        control.disabled = false;
    }
}

function ApplyTag(obj, tag)
{
	WrapText(obj, '[' + tag + ']', '[/' + tag + ']');
}

function WrapText(obj, beginTag, endTag)
{
	if(typeof obj.selectionStart == 'number')
	{
		var start = obj.selectionStart;
		var end   = obj.selectionEnd;
		
		obj.value = obj.value.substring(0, start) + beginTag + obj.value.substring(start, end) + endTag + obj.value.substring(end, obj.value.length);
	}
	else if(document.selection)
	{
		obj.focus();
		
		var range = document.selection.createRange();
		
		if(range.parentElement() == obj)
		{
	        if(typeof(range.text) == 'string')
	        {
	            document.selection.createRange().text = beginTag + range.text + endTag;
	        }
	    }
	}
	else
	{
		obj.value += text;
	}		
}

function ApplyTagToSelection(event, control, tag)
{
    ApplyTag($(ClientIDs.CardPostText), tag);
    
    return false;
}

function ToggleButtons(event, control)
{
    var checkBox = $('termsAndConditionsCheckbox');
    
    if(checkBox != null)
    {
        if(checkBox.checked)
        {
            $(ClientIDs.SaveDiscussionPost).disabled = false;
            $(ClientIDs.DeleteDiscussionPost).disabled = false;
        }
        else
        {
            $(ClientIDs.SaveDiscussionPost).disabled = true;
            $(ClientIDs.DeleteDiscussionPost).disabled = true;
        }
    }
}

function ExpandPost(event, control, postID)
{
        new Ajax.Request(utilitiesHandler , {
            method: 'post',
            parameters: { method: 'GetCardComment', postID: postID },
            onSuccess:  function(transport) {
                var result = eval('(' + transport.responseText + ')');
                
                if(result != null)
                {
                    var popularPost = $('PopularPost' + postID);
                    var recentPost = $('RecentPost' + postID);
                    
                    if(popularPost != null)
                    {
                        popularPost.select('span')[0].update(result.Data.ParsedPost);
                    }   
                    
                    if(recentPost != null)
                    {
                        recentPost.select('span')[0].update(result.Data.ParsedPost);
                    }
                }
                
                if(result != null)
                {
                    $(control.parentNode).update(result.Data.ParsedPost);
                }
            }  
        });
}

function RegisterForUserNameClickEvents()
{
    var userNameLinks = $$('.' + Constants.StyleSheetClasses.PostedByLink);
    
    for(var i = 0; i < userNameLinks.length; i++)
    {
        var control = userNameLinks[i];
        var stem = 'bottomMiddle';
        
        if(document.all)
        {
            stem = 'bottomLeft';            
        }
        
        var tip = new Tip(control, {
                        showOn: 'click',
                        title: new Element('a', { 'href': '/Pages/Search/Default.aspx?action=advanced&user=+[' + control.innerHTML + ']', 'title': 'Find all cards with comments by ' + control.innerHTML  + '.'}).update(control.innerHTML),
                        hideOn: { element: 'closeButton', event: 'click'},	        
                        stem: stem,
                        hook: { target: 'topMiddle', tip: 'bottomMiddle' },
                        offset: { x: 0, y: -2 },
                        width: '335px',
                        ajax: {
                            url: UserInformationHandler,
                            options: {
                            method: 'get',
                                parameters: { method: 'GetUserInformation', userName: control.innerHTML, date: new Date().getTime() }                        
                            }
                        }
                    });
    }    
}
