﻿var newsIds = new Array();

/* COMMENT AJAX STUFF */
var sendReq = getXmlHttpRequestObject();
var receiveReq = getXmlHttpRequestObject();
var mTimer;

//Gets the browser specific XmlHttpRequest Object
function getXmlHttpRequestObject() {
    if (window.XMLHttpRequest) {
        return new XMLHttpRequest();
    } else if (window.ActiveXObject) {
        return new ActiveXObject("Microsoft.XMLHTTP");
    } else {
        // Failed to create object
    }
}

function addElement(newsId) {
    
  var containerId = 'cTxt' + newsId;
  var container = document.getElementById(containerId);
  
  // inner div
  var divIdName = 'my1Div';
  
  // reference to previous used comment text container (may not be visible)
  var olddiv = document.getElementById('cTxt' + newsIds[0]);
  
  // if we have an open comment box already then remove it
  if (olddiv != null) {
    removeElement('cTxt' + newsIds[0]);
  }
  
  // set containerId to array (only uses first slot)
  newsIds[0] = newsId;
  
  // create new comment element
  var newdiv = document.createElement('div');
  var divIdName = 'my1Div';
  newdiv.setAttribute('id', divIdName);
  newdiv.innerHTML = '<input type="text" id="commentText" size="50" tabindex="0" onblur="closeIfNotSubmit(\'' + newsId + '\');" /> <input onfocus="javascript: postClicked=1;" onclick="javascript:sendComment(\'' + newsId + '\');" type="button" class="newsCommentPostButton" id="btnPostComment" value="Post Comment" />';
  container.appendChild(newdiv);
  container.style.display = 'block';
  document.getElementById("commentText").focus();
}

function closeIfNotSubmit(newsId) {
    setTimeout("closeIfNotSubmit2('" + newsId + "')", 100);
}
function closeIfNotSubmit2(newsId) {
    if (postClicked == 0) {
        removeElement('cTxt' + newsId);
    }
}

function removeElement(containerId) {
  var d = document.getElementById(containerId);
  var olddiv = document.getElementById('my1Div');
  d.removeChild(olddiv);
  d.style.display = 'none';
  
  // set array to blank
  newsIds[0] = null;
}

// retrieves comments for specified newsId and writes them into the specific DIV element for that news item
function getComments(newsId) {
    if (receiveReq.readyState == 4 || receiveReq.readyState == 0) {
	    receiveReq.open("GET", '/djaccount/news/getComments.aspx?newsId=' + newsId, true);

	    receiveReq.onreadystatechange = function () {
                handleReceiveComments(newsId);
            }
	    receiveReq.send(null);
	}
}

// Function for handling the return of comments
function handleReceiveComments(newsId) {
    
	if (receiveReq.readyState == 4) {
	    
	    var xmldoc = receiveReq.responseXML;
	    var comment_nodes = xmldoc.getElementsByTagName("comment");
	    var n_comments = comment_nodes.length;
	    
	    // get obj reference to comments div
	    var commentDiv = document.getElementById('c' + newsId);
	    
	    // remove previous comments
	    commentDiv.innerHTML = '';
	    commentDiv.style.display = 'block';
	    
        // loop through all comments returned from database
        for (i = 0; i < n_comments; i++) {
            var user_node = comment_nodes[i].getElementsByTagName("user");
            var text_node = comment_nodes[i].getElementsByTagName("text");
            var time_node = comment_nodes[i].getElementsByTagName("time");
            var imageurl_node = comment_nodes[i].getElementsByTagName("imageurl");
            var profileurl_node = comment_nodes[i].getElementsByTagName("profileurl");
            
            // get nodes from xml
            var t_user = user_node[0].firstChild.nodeValue;
            var t_time = time_node[0].firstChild.nodeValue;
            var t_text = text_node[0].firstChild.nodeValue 
            var t_imageurl = imageurl_node[0].firstChild.nodeValue;
            var t_profileurl = profileurl_node[0].firstChild.nodeValue;
            
            // make sure the div exists before we start adding comments to it
            if (commentDiv != null) {
                
                // adds comment element to comment container
                addCommentToCommentDiv(commentDiv, t_user, t_time, t_text, t_imageurl, t_profileurl);
            }
        }
	}
}

// adds html element to comment container DIV
function addCommentToCommentDiv(commentDiv, t_user, t_time, t_text, t_imageurl, t_profileurl) {
    var html = '<div class="newsComment">';
    html += '<div class="newsCommentPhoto"><img src="/controls/DisplayImage.aspx?i=' + t_imageurl + '&s=30" /></div>';
    html += '<div class="newsCommentText"><a href="' + t_profileurl + '">' + t_user + '</a> <span class="newsCommentTime">at ' + t_time + '</span><br /><span class="newsCommentUserText">' + t_text + '</span></div>';
    html += '</div>';
                
    commentDiv.innerHTML += html;
    
    scrollCommentBottom(commentDiv);
}

// maintains scroll position to the bottom
function scrollCommentBottom(commentDiv) {
    var test1 = commentDiv.scrollHeight;
    var test2 = commentDiv.offsetHeight;
    if (test1 > 0) // all but Explorer Mac
    {
        commentDiv.scrollTop = commentDiv.scrollHeight;
    }
    else // Explorer Mac;
         //would also work in Explorer 6 Strict, Mozilla and Safari
    {
        commentDiv.scrollTop = commentDiv.offsetHeight;
    }
}

// Add a message to the chat server.
function sendComment(newsId) {
    var commentTextObj = document.getElementById('commentText');
    var commentText = commentTextObj.value;
    postClicked = 1;
    
    if (sendReq.readyState == 4 || sendReq.readyState == 0) {
        
        sendReq.open("POST", '/djaccount/news/postComment.aspx', true);
        sendReq.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
        sendReq.onreadystatechange = function () {
                handleSendComment(newsId);
            }
        
        var param = 'newsId=' + newsId;
        param += '&commentText=' + encodeMyHtml(commentText);
        sendReq.send(param);
    }
}

// When our comment has been sent, update our page.
function handleSendComment(newsId) {	
    if (sendReq.readyState == 4) {
	    // get response
	    var sendResponse = sendReq.responseText;
	    
	    // user not online any more
	    if (sendResponse == '1') {
	        displayError(newsId, 'There was a problem posting your comment.');
	    }
	    
	    removeElement('cTxt' + newsId);
	    
	    getComments(newsId);
	}
}

function encodeMyHtml(htmlCode) {
    encodedHtml = escape(htmlCode);
    encodedHtml = encodedHtml.replace(/\//g, "%2F");
    encodedHtml = encodedHtml.replace(/\?/g, "%3F");
    encodedHtml = encodedHtml.replace(/=/g, "%3D");
    encodedHtml = encodedHtml.replace(/&/g, "%26");
    encodedHtml = encodedHtml.replace(/@/g, "%40");
    return encodedHtml;
} 