var e1;
var xob;
var numComments,numPages,oldPgs;
var commentsPage;
var counter=0;
var hasNewComments;
var am ="";


function retContent(page,divID,params,cover)
{
    var redir = false;
    if(cover == undefined){ cover = true; }
    if (document.getElementById)
    {
        e1 = document.getElementById(divID);
        if( e1 == undefined )
        {
        return false;
        }
        xob = (window.ActiveXObject) ? new ActiveXObject("Microsoft.XMLHTTP") : new XMLHttpRequest();
        
        if (xob)
        {
            if (xob.overrideMimeType)
            {
                xob.overrideMimeType("text/html");// set to anticipated content type
            }
            
            if (params)
            { 
                xob.open("post", page, true);
                xob.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
                xob.setRequestHeader("Content-length", params.length);
                xob.setRequestHeader("Connection", "close");
                xob.send(params);
            }else{
                xob.open("get", page, true);
                xob.setRequestHeader("Connection", "close");
                xob.send(null);
            }
            
            if(cover != 'off') { showWait(e1); }
            
            xob.onreadystatechange = function()
            {
                if (xob.readyState < 4)
                {
                    done = false; 
                }else if (xob.readyState == 4){
                    if(xob.status == 200)
                    {    
                        //test if this content is a redirect...
                        if(xob.responseText.substr(0,11) == "<!-- reload")
                        {
                            newstr = xob.responseText.replace(/<!-- reload#/i, "");
                            window.location.href = newstr.replace(/# -->/, "");
                        }else{
                            //is there a function that needs to be called for this page?
                            ftest="on_"+divID;
                            if('function' == eval("typeof "+ftest))
                            {
                                eval(ftest+"('"+divID+"')");
                            }else{
                                // no function found, so just replace the content
                                e1.innerHTML = xob.responseText;
                            }
                        }
                        if(cover != 'off') { showWait(e1); }
                        done=true;
                    }else{
                        e1.innerHTML = 'status: '+ xob.statusText;
                        done=true;
                        
                    }
                    
                } 
                if(done){ 
                    if(cover != 'off') { setTimeout("hideWait()",1000); }
                }
                if(redir) { setTimeout("redirect(redir)",2000); }
                
            } //end function
        } //end if xob
    }
}

function requestForm(formobj, pageName, div)
{
    var str = "";
    var valu = "";
    var cmd = "";

    fs = formobj.elements.length;

    for (var i = 0; i < fs ; i++) {
        switch (formobj.elements[i].type)
        {
        case "text":
        case "hidden":
        case "password":
        case "textarea":
        str += formobj.elements[i].name + "=" + encodeURI(formobj.elements[i].value)+ "&";
        break;
        case "checkbox":
            if (formobj.elements[i].checked)
            {
                str += formobj.elements[i].name + "=" + encodeURI(formobj.elements[i].value) + "&";
            }
            break;
        case "radio":
        str += formobj.elements[i].name + "=" + formobj.elements[i].options[formobj.elements[i].selectedIndex].value + "&";
        break;

        case "select-one":  
        str += formobj.elements[i].name + "=" + formobj.elements[i].options[formobj.elements[i].selectedIndex].value + "&";
        break;
        }
    }
    retContent(pageName, div, str);
}

function showWait(obj1)
{
    pos = findPos(obj1);
    x = document.getElementById("pleasewait");

    if (x != undefined) {
        x.innerHTML = "Loading...Please Wait.";
        x.style.backgroundColor = '#CCCCCC';
        x.style.zOrder = obj1.style.zOrder + 100;
        x.style.left = pos[0] + 'px';
        x.style.top = pos[1] + 'px';
        x.style.height = obj1.scrollHeight + 'px';
        x.style.width = obj1.scrollWidth + 'px';
        x.style.display = "block";
    }
}

function hideWait()
{
    x = document.getElementById("pleasewait");
    x.style.left = -10000 + 'px';
    x.style.top = -10000 + 'px';
    x.style.display='none';
}

function redirect(r)
{
    window.location.href = r;
}

function updateValueWhenExists(inID, inVal)
{
    if(document.getElementById(inID) &&  inVal != "")
    {
        document.getElementById(inID).innerHTML = inVal;
    }else{
        setTimeout("updateValueWhenExists('" + inID + "','" + inVal + "')",250);
    }
    return;
}

function getLastCommentTime()
{
    am += "called getLastCommentTime() function\n";
    retContent("/comments.php?id="+artID+"&act=getLCT","lct_tmp",false,"off");
    return;
}


function loadCommentVal()
{
    
    var newPages;
    comment_hdr_txt = "";
    commtxt = 'Add a<br>Comment';
    //numComments=document.getElementById("comment_tmp").innerHTML;
    if(numComments[0] == "" || numComments[0] =="NaN")
    {
        setTimeout("loadCommentVal()",500);
    }else{
        numPages = numComments[0] % perPage != 0 ? Math.floor(numComments[0]/perPage)+1 :  (numComments[0]/perPage);
        
        if( numComments[0] == 0 ) {    
            comment_hdr_txt = "There are no comments posted yet.";
        }else if( numComments[0] <= 3 ) {
            commtxt = '<span style="font-size: 18px;">'+Number(numComments[0])+'</span><br>Comments';
            if( numComments[0] == 1 ) {
            commtxt = '<span style="font-size: 18px;">'+Number(numComments[0])+'</span><br>Comment';
            }
            comment_hdr_txt = "Here are all of comments submitted by Human Events readers:";
        }else{
            commtxt = '<span style="font-size: 18px;">'+Number(numComments[0])+'</span><br>Comments';
            if(currPage==0 && numPages >=1)
            {
                comment_hdr_txt = "Here are a few of the comments submitted by our readers.";
                comment_hdr_txt += '<a href="/article.php?id='+artID+'&page=1#c1"><b>Click to view all</b></a>';
            }else{
                if(numComments[0] > 3)
                {
                    comment_hdr_txt = "Here are the comments submitted by Human Events readers:";
                }
            }
        }
    }
    oldPgs = Math.floor((numComments[0]-numComments[1])/perPage);
    newPages = numPages-oldPgs < 1 ? 1 : numPages-oldPgs;
    am += "Number of newPages: "+ newPages +"\n";
    if(hasNewComments == 1)
    { 
        if(currPage>oldPgs || (numComments[0]-numComments[1])<4){
            am+="this page has new comments\n";
            // Bookmark: comments hit.
            getComments();
        }
        updateValueWhenExists('numOfComments',commtxt);
        updateValueWhenExists('numOfComments2',Number(numComments[0]));
        updateValueWhenExists('comments_tag',comment_hdr_txt);
        setTimeout("createCommentLinks()",250);
    } //else do not load the comments page
    am += "called loadCommentVal() function\n";
    return false;
}
function getComments()
{
    commentPage = "comments2.php";
    if(currPage > oldPgs || currPage<1){ commentPage="comments.php"; }
    am += "called getComments() function\n -commentPage= "+commentPage+"\n -currPage: "+currPage+" < numPages: "+numPages+"\n";
    retContent(commentPage+"?id="+artID+"&page="+currPage,"comment_block",false);
}
function createCommentLinksOld()
{
    nextLink ="";
    previousLink = "";
    skip2first = "";
    skip2last = "";
    c_m  = "";
    currPage = Number(currPage);
    
    if(currPage!=0 && numPages >= 1)
    {
        nextLink = numPages > currPage ? '&nbsp;&nbsp;<a href="/article.php?id='+artID+'&amp;page='+(currPage+1)+'#c1" class="article_byline" style="text-decoration:underline;">Next</a> ' : "";
        previousLink = currPage > 1 ? ' <a href="/article.php?id='+artID+'&amp;page='+(currPage-1)+'#c1" class="article_byline" style="text-decoration:underline;">Previous</a>&nbsp;&nbsp;' : "";
        skip2first = currPage >= 3 ? '<a href="/article.php?id='+artID+'&amp;page=1#c1" class="article_byline" style="text-decoration:underline;">First</a>&nbsp;&nbsp; ' : "";
        skip2last =  currPage < numPages && numPages >= 3 ? '&nbsp;&nbsp;<a href="/article.php?id='+artID+'&amp;page='+numPages+'#c1" class="article_byline" style="text-decoration:underline;">Last</a> ' : '';
        c_m = '<table border="0" cellpadding="2" cellspacing="0" align="right"><tr><td>';
        c_m += skip2first + "</td><td>" + previousLink + "</td>";
        c_m += "<td nowrap>Page "+ currPage + " of " + numPages + "</td>";
        c_m += "<td>"+ nextLink + "</td><td>" + skip2last
        c_m += "</td></tr></table>";
    }else if(numComments[0] > 3){
        c_m = '<table border="0" cellpadding="2" cellspacing="0" align="right">';
        c_m += '<tr>';
        c_m += '<td><a href="article.php?id='+artID+'&amp;page=1#c1" class="commentlink" style="text-decoration:none;"><img src="'+static_path+'images/article/morecomments.gif" align="middle" border="0" /></a></td>';
        c_m += '<td nowrap><a href="article.php?id='+artID+'&amp;page=1#c1" class="article_headline">Show All Comments</a></td>';
        c_m += '</tr>';
        c_m += '</table>';
    }else{
        c_m = "&nbsp;";
    }
    am += "called createCommentLinks() function\n";
    updateValueWhenExists("pageNumLinks",c_m);
}


function buildReportCommentURL(articleID, commentID, page)
{
    if (page) {
        pageArg = '&page=' + page;
    } else {
        pageArg = '';
    }

    var url = '/reportcomment.php'
        + '?id=' + articleID
        + pageArg
        + '&cid=' + commentID;

    return url;
}


function openReportCommentWindow(url)
{
    var options = 'resizable=no, scrollbars=no, menubar=no, '
        + 'status=no, location=no, toolbar=no, width=400, height=400';

    window.open(url, 'reportcomment', options);

    return false;
}


// Some DOM hijacking.  Needed to work around element class attribute handling in IE vs Firefox.
Element = function () {};

// By setting both, this is not necesssary.
/*
Element.prototype.getAttribute = function (attribute) {
    if (attribute == "class") attribute = "className";
    if (attribute == "for") attribute = "htmlFor";
    return this[attribute];
}
*/

Element.prototype.setAttribute = function (attribute, value)
{
    if (attribute == 'class' || attribute == 'className') {
        this['class'] = value;
        this['className'] = value;
    }

    if (attribute == 'for' || attribute == 'htmlFor') {
        this['for'] = value;
        this['htmlFor'] = value;
    }

    return;
}

document._createElement = document.createElement;

document.createElement = function (tag)
{
    // Call base.
    var element = document._createElement(tag);

    var interface = new Element;
    for (var method in interface) {
        element[method] = interface[method];
    }

    return element;
}



function getComment(id, topLevelStyle)
{
    var baseURL = 'ajaxcomments.php?commentID=' + id;
    var xob = (window.ActiveXObject) ? new ActiveXObject("Microsoft.XMLHTTP") : new XMLHttpRequest();

    onreadystatechange_handle = function ()
    {
        if (xob.readyState < 4 || xob.readyState != 4 || xob.status != 200) {
            return false;
        }

        var rt = xob.responseText;
        var target = document.getElementById('comment_block');

        eval(rt);

        // The comment ID link target.
        var linkTarget = document.createElement('a');
        linkTarget['id'] = 'hec' + comment.comment_id;
        linkTarget['name'] = 'hec' + comment.comment_id;
        target.appendChild(linkTarget);

        // The comment wrapper.
        var commentBox = document.createElement('div');
        commentBox.setAttribute('class', topLevelStyle);

        // Upper portion of comment.
        bodyBox = document.createElement('div');
        bodyBox.setAttribute('class', 'commentbody');

        // Abusive post link.
        var reportURL = buildReportCommentURL(comment.article_id, comment.comment_id, false);
        var reportBox = document.createElement('span');
        reportBox.setAttribute('class', 'commentReportBlock');
        reportBox.innerHTML = ''
            + '<a href="#" '
            + 'onmouseover="window.status=\'Report This Comment\';return true;" '
            + 'onmouseout="window.status=\'\';return true;" '
            + 'onclick="openReportCommentWindow(\'' + reportURL + '\'); " '
            + 'class="reportcomment" '
            + 'title="Report this Comment">'
            + 'Report Abusive Post'
            + '</a>';
        bodyBox.appendChild(reportBox);

        // Add the comment body.
        bodyBox.innerHTML += comment.body + '<br />';
        commentBox.appendChild(bodyBox);


        // Bottom portion of comment.
        // --------------------------


        // Bottom box.
        var bottomBox = document.createElement('div');
        bottomBox.setAttribute('class', 'commentbtm');

        // Date posted box.
        var dateBox = document.createElement('div');
        dateBox.setAttribute('class', 'posted');
        dateBox.appendChild(document.createTextNode(comment.date));
        bottomBox.appendChild(dateBox);

        // Post author box.
        var loc = (comment.location) ? ', ' + comment.location : '';
        var userBox = document.createElement('div');
        userBox.setAttribute('class', 'postby');
        var nameBox = document.createElement('strong');
        nameBox.appendChild(document.createTextNode(comment.username));
        userBox.appendChild(nameBox);
        userBox.appendChild(document.createTextNode(loc));
        bottomBox.appendChild(userBox);

        // Add the bottom section.
        commentBox.appendChild(bottomBox);

        // Add the comment to the page.
        target.appendChild(commentBox);

        return;
    } //end function

    xob.open("get", baseURL, false);
    //xob.setRequestHeader("Connection", "close");
    xob.setRequestHeader("If-Modified-Since", new Date(0));

    xob.send(null);

    onreadystatechange_handle();

    return;
}

/**
 * Retrieves the comment count and comment list.  This data is currently just a blob of javascript.
 * @par Notes
 * In IE, you can't append to document.body until the page has finished loading.  You can however,
 * append to an existing HTML element.
 *
 * @return void
 * @todo   Rename this function.
 * @todo   Refactor PHP scripts to use JSON (more standard).
 */
function getCommentList(articleID, pageNumberArg)
{
    //var timestamp = new Date();
    // var url = 'commentlist.php?id=' + articleID + '&refresh=' + timestamp.getTime();
    var url = 'commentlist.php?id=' + articleID;

    var qs = new Querystring();
    var pageNumber = qs.get('page');

    if (pageNumber != null) {
        url += '&page=' + pageNumber;
    }

    var xob = (window.ActiveXObject) ? new ActiveXObject("Microsoft.XMLHTTP") : new XMLHttpRequest();

    xob.onreadystatechange = function ()
    {
        if (xob.readyState < 4) {
            done = false; 
        } else if (xob.readyState == 4){
            if(xob.status == 200) {    
                var commentData = xob.responseText;
                var countText;

                // This sets commentcount and commentlist.
                eval(commentData);

                // Set the comment counts on the page.
                if (commentcount == 0) {
                    try {
                        var addLinkText = 'Add a<br>Comment';
                        document.getElementById('numOfComments').innerHTML = addLinkText;
                    } catch (err) {
                        // pass.
                    }
                } else {
                    if (commentcount == 1) {
                        var countText = 'Comment';
                    } else {
                        var countText = 'Comments';
                    }
                }

                try {
                    document.getElementById('commentCountText').innerHTML = countText;
                } catch (err) {
                    // pass.
                }
                try {
                    document.getElementById('commentCount1').innerHTML = commentcount;
                } catch (err) {
                    // pass.
                }
                try {
                    document.getElementById('numOfComments2').innerHTML = commentcount;
                } catch (err) {
                    // pass.
                }

                var commentStyle = 'commentA';
                for (var ob in commentlist) {
                    getComment(commentlist[ob], commentStyle);

                    // Alternate the comment style for each row.
                    commentStyle = (commentStyle == 'commentA') ? 'commentB' : 'commentA';
                }

                // If a new comment has been posted (viewID is passed), scroll into
                // view.  This is rough but functional.
                var qs = new Querystring();
                var viewID = qs.get('viewID');
                try {
                    if (viewID != '') {
                        var scrollTarget = document.getElementById('hec' + viewID);
                        scrollTarget.scrollIntoView();
                    }
                } catch (err) {
                    // pass;
                }

                if (commentcount % perPage == 0) {
                    pageCount = commentcount / perPage;
                } else {
                    pageCount = Math.floor(commentcount / perPage) + 1;
                }
                pageCount = pageCount < 1 ? 1 : pageCount;

                var linkHTML = createCommentLinks(commentcount, pageCount, pageNumber );
                var pageLinkBox = document.getElementById('pageNumLinks');
                pageLinkBox.innerHTML += linkHTML;

            } else {
                e1.innerHTML = 'status: '+ xob.statusText;
                done=true;
            }
        }
    } //end function

    xob.open("get", url, true);
    //xob.setRequestHeader("Connection", "close");
    xob.setRequestHeader("If-Modified-Since", new Date(0));
    xob.send(null);
}


function createCommentLinks(numComments, numPages, currPage)
{
    nextLink ="";
    previousLink = "";
    skip2first = "";
    skip2last = "";
    c_m  = "";
    currPage = Number(currPage);

    if (!isNaN(currPage) && currPage != 0 && numPages >= 1 && currPage <= numPages) {
        nextLink = numPages > currPage ? '&nbsp;&nbsp;<a href="/article.php?id='+artID+'&amp;page='+(currPage+1)+'#c1" class="article_byline" style="text-decoration:underline;">Next</a> ' : "";
        previousLink = currPage > 1 ? ' <a href="/article.php?id='+artID+'&amp;page='+(currPage-1)+'#c1" class="article_byline" style="text-decoration:underline;">Previous</a>&nbsp;&nbsp;' : "";
        skip2first = currPage >= 3 ? '<a href="/article.php?id='+artID+'&amp;page=1#c1" class="article_byline" style="text-decoration:underline;">First</a>&nbsp;&nbsp; ' : "";
        skip2last =  currPage < numPages && numPages >= 3 ? '&nbsp;&nbsp;<a href="/article.php?id='+artID+'&amp;page='+numPages+'#c1" class="article_byline" style="text-decoration:underline;">Last</a> ' : '';
        c_m = '<table border="0" cellpadding="2" cellspacing="0" align="right"><tr><td>';
        c_m += skip2first + "</td><td>" + previousLink + "</td>";
        c_m += "<td nowrap>Page "+ currPage + " of " + numPages + "</td>";
        c_m += "<td>"+ nextLink + "</td><td>" + skip2last
        c_m += "</td></tr></table>";
    } else if (numComments > 3) {
        c_m = '<table border="0" cellpadding="2" cellspacing="0" align="right">';
        c_m += '<tr>';
        c_m += '<td><a href="article.php?id='+artID+'&amp;page=1#c1" class="commentlink" style="text-decoration:none;"><img src="'+static_path+'images/article/morecomments.gif" align="middle" border="0" /></a></td>';
        c_m += '<td nowrap><a href="article.php?id='+artID+'&amp;page=1#c1" class="article_headline">Show All Comments</a></td>';
        c_m += '</tr>';
        c_m += '</table>';
    } else {
        c_m = "&nbsp;";
    }

    return c_m;
}

/**
 * Client-side access to querystring name=value pairs
 * Version 1.3
 * 28 May 2008
 * 
 * License (Simplified BSD):
 * http://adamv.com/dev/javascript/qslicense.txt
 */
function Querystring(qs) { // optionally pass a querystring to parse
    this.params = {};
    
    if (qs == null) qs = location.search.substring(1, location.search.length);
    if (qs.length == 0) return;

    // Turn <plus> back to <space>
    // See: http://www.w3.org/TR/REC-html40/interact/forms.html#h-17.13.4.1
    qs = qs.replace(/\+/g, ' ');
    var args = qs.split('&'); // parse out name/value pairs separated via &

    // split out each name=value pair
    for (var i = 0; i < args.length; i++) {
        var pair = args[i].split('=');
        var name = decodeURIComponent(pair[0]);

        var value = (pair.length==2)
            ? decodeURIComponent(pair[1])
            : name;

        this.params[name] = value;
    }
}

Querystring.prototype.get = function(key, default_) {
    var value = this.params[key];
    return (value != null) ? value : default_;
}

Querystring.prototype.contains = function(key) {
    var value = this.params[key];
    return (value != null);
}
