/*
    Warning globals:
*/

    var openReplies = Array;
    var canRate = true;

var dlCommentSys = Class.create ();

dlCommentSys.prototype.initialize = function ()
{
    this.processedCommentIds = Array ();
}

dlCommentSys.prototype.inArray = function (ar, val) {

    for (var i in ar) {
        if (ar [i] === val) return i;
    }

    return -1;
}

dlCommentSys.prototype.getUrlParam = function (param) {
    
    param = param.replace (/[\[]/, "\\\[").replace (/[\]]/, "\\\]");
  
    var regexS = "[\\?&]" + param + "=([^&#]*)";
    var regex = new RegExp (regexS);
    var results = regex.exec (window.location.href);
  
    if (results == null) {
        return "";
    } else {
        return results [1];
    }
}

dlCommentSys.prototype.getUrlSnip = function ()
{
    return (window.location.href.split ('/') [5]);
}

dlCommentSys.prototype.startWidget = function (config) {

    this.instance  = config.instance;
    this.type      = config.type;
    this.container = config.container;
    this.asset     = config.asset;

    if (config.noRatings == true) {
       this.allowRatings = false;
    } else {
        this.allowRatings = true;
        if (commentConfig.app != "TV") 
        this.rater     = new dlRating ();
        else this.rater = Class.create ();
    }

    if (typeof this.asset == "undefined" || isNaN (this.asset) || this.asset == "") {   
        this.asset = this.getUrlParam ("id");        
    }

    if (typeof this.asset == "undefined" || isNaN (this.asset) || this.asset == "") {   
        this.asset = this.getUrlSnip ();        
    }

    if (typeof this.asset == "undefined" || isNaN (this.asset) || this.asset == "") {   
        throw ("An asset id was not defined, bailing out");
        return;
    }

    config.asset = this.asset;

    var headDiv = new Element ("div", {});

    var commentsDiv = new Element ('div', {
        'id' : 'allComments'
    });

    var textDiv = new Element ('div', {
        'id' : 'commentTextDiv'
    });

    if (commentConfig.app != "TV") {

    var a = new Element ('a', {
        'href' : '#reviewForm'
    }).insert ("Submit your rating and review");
    } else {
    var a = new Element ('a', {
        'href' : '#reviewForm'
    }).insert ("Submit your review");
    }

    textDiv.insert (a);

    var headImgDiv = new Element ('div', {
        'id' : 'commentHeadImgDiv'
    });
     
    var headImg = new Element ('img', {
       'src' : "/comments/widgets/commentsAndRatings/images/reviews_header.gif"
    });

    headImgDiv.insert (headImg);

    commentsDiv.insert (headImgDiv);
    commentsDiv.insert (textDiv);
   
    $(this.container).insert (commentsDiv);

    var barDiv = new Element ('div', {
        'id' : 'rateBarDiv'
    });

    $(this.container).insert (barDiv);

    this.doLoginCheck ();
    this.userNameCheck ();
}

dlCommentSys.prototype.userNameCheck = function ()
{
    if (commentConfig.loggedIn == false) {
        return;
    }

    var dLifeUserName = this.readCookie ("dLifeUserName");

    if (dLifeUserName == "null" || dLifeUserName == null || typeof (dLifeUserName) == "undefined") {

        commentConfig.hasUsername = false;
        this.loadUsernameRequired ();
    } else {
        commentConfig.hasUsername = true;
    }
}

dlCommentSys.prototype.doLoginCheck = function ()
{
    if (this.readCookie ('dLifeUserId') != null && this.readCookie ('dLifeUserId') != "null" && this.readCookie ('dLifeUserId') != "undefined") {
        if (isNaN (this.readCookie ('dLifeUserId'))) {
            commentConfig.loggedIn = false;
            this.loadLoginForm ();
            $(this.container).insert (this.loadReplyForm ("asset" + this.asset, this.allowRatings));
        } else { 
            commentConfig.loggedIn = true;
            $(this.container).insert (this.loadReplyForm ("asset" + this.asset, this.allowRatings));
        }
    } else {
        commentConfig.loggedIn = false;
        this.loadLoginForm ();
        $(this.container).insert (this.loadReplyForm ("asset" + this.asset, this.allowRatings));
    }
}

dlCommentSys.prototype.loadLoginForm = function ()
{   
    var rb = $("rateBarDiv");

    rb.update ("");

    rb.style.backgroundColor = "#FEEEEE";
    rb.style.fontSize = "11px";
    rb.style.lineHeight = "11px";
    rb.style.borderBottom ="solid 2px #da4949";
    rb.style.borderTop = "solid 2px #da4949";
    rb.style.textAlign = "center";

    var joinA = new Element ("a", {'href' : '/dLife/diabetes/BlogabetesRegistration'}).insert ("join");
    var loginA = new Element ("a", {'href' : '/dLife/do/BlogabetesLogin'}).insert ("login");

    rb.insert ("To rate and review you need to ");

    rb.insert (joinA);
    rb.insert ("&nbsp;or ");
    rb.insert (loginA);
}

dlCommentSys.prototype.loadUsernameRequired = function ()
{
    var rb = $("rateBarDiv");

    rb.update ("");

    var a = new Element ('a', {
        'name' : 'reviewForm'
    }).insert ("&nbsp;here. ");

    rb.style.height          = "16px";
    rb.style.backgroundColor = "#FEEEEE";
    rb.style.textAlign       = "center";
    rb.style.fontWeight      = "bold";
    rb.style.borderBottom    = "solid 2px #da4949";
    rb.style.borderTop       = "solid 2px #da4949";

    rb.insert ("You need to set up a username. Please click");

    rb.insert (a);
}

dlCommentSys.prototype.getComments = function ()
{
    var that = Object.clone (this);

    var req = new dlAjax ();

    var postBody = ({
        'assetId'     : this.asset,
        'appId'       : commentConfig.app,
        'contentType' : commentConfig.type,
        'status'      : 'active',
        'shallow'     : 'false'
    });
    
    req.generate (postBody, "GetComments");
    
    var callback = function (transport) 
    {    
        var response = transport.responseXML;
        var content = response.getElementsByTagName ("content") [0];

        eval (that.instance).itterateComments (content, 1);
    }
    
    req.send (callback);    
}

dlCommentSys.prototype.getDepth = function (node)
{
    if (node.nodeName == "response") {
        return 0;
    }

    var r = this.getDepth (node.parentNode) + 1;

    return r;
}

dlCommentSys.prototype.itterateComments = function () {

    var node = arguments [0];
    var depth = arguments [1];
    var cid = null;

    if (arguments [2]) {
        var parentCommentId = arguments [2];
    }

    var d = this.getDepth (node);
    
    for (var i = 0; i < node.childNodes.length; i ++) {

        if (node.childNodes [i].nodeName == "comment") { 

            var activeNode = node.childNodes [i];

            var c = new dlComment;
            c.parentInstance = this.instance;

            if (activeNode.getElementsByTagName ("commentid") [0]) {            
                c.id       = activeNode.getElementsByTagName ("commentid") [0].firstChild.nodeValue;
                cid = c.id;
            }

            if (this.inArray (this.processedCommentIds, cid) != -1) continue;
            this.processedCommentIds.push (cid);
            
            if (activeNode.getElementsByTagName ("username") [0]) {
                c.userName = activeNode.getElementsByTagName ("username")  [0].firstChild.nodeValue;
            }
            
            if (activeNode.getElementsByTagName ("datetime") [0]) {
                c.dateTime = activeNode.getElementsByTagName ("datetime")  [0].firstChild.nodeValue;
            }
            
            if (activeNode.getElementsByTagName ("data") [0]) {
                if (activeNode.getElementsByTagName ("data") [0].childNodes.length == 0) continue;
                c.content  = activeNode.getElementsByTagName ("data")      [0].firstChild.nodeValue;
            }

            var userId;

            if (activeNode.getElementsByTagName ("userid") [0]) {
                userId     = activeNode.getElementsByTagName ("userid") [0].firstChild.nodeValue;
            }

            var cookieUserId = this.readCookie ("dLifeUserId");

            if (commentConfig.app != "TV") {

                if (activeNode.getElementsByTagName ("userrating") [0].childNodes.length > 0 && cookieUserId == userId) {

                    if ($("rateHeadImg")) {
                        $("rateHeadImg").parentNode.remove ();
                    }

                    canRate = false;
                    c.rating = activeNode.getElementsByTagName ("userrating") [0].firstChild.nodeValue;
                }
            }

            c.numberOfReplies = 0;
                               
            if (typeof activeNode.getElementsByTagName ("replies") [0] == "undefined") {} else {
                
                if (activeNode.getElementsByTagName ("replies") [0] == null) {

                    c.numberOfReplies = 0;

                } else {

                    for (var j = 0; j < activeNode.getElementsByTagName ("replies") [0].childNodes.length; j ++) {

                        if (activeNode.getElementsByTagName ("replies") [0].childNodes [j].nodeType == 1) {
                            c.numberOfReplies ++;
                        }
                    }
                }
            }

            if (activeNode.getElementsByTagName ("status") [0].firstChild.nodeValue == "active") {
               
                if (parentCommentId != undefined) {

                    parentCommentId = "comment_" + parentCommentId.substr (10, parentCommentId.length);
 
                    $(parentCommentId).insert ({after : c.buildComment (depth)});
                    
                } else {
                    $("allComments").insert (c.buildComment (depth));      
                }

                if (c.numberOfReplies > 0) {
                    depth ++;
                    this.itterateComments (activeNode.getElementsByTagName ("replies") [0], depth);
                    depth --;
                } 
            }
        }
    }
}

dlCommentSys.prototype.loadReplyForm = function (replyId, loadRater) {

    var that = Object.clone (this);

    if (openReplies ["replyform_" + replyId] == "open") {
        return;
    }
    
    var div = new Element ('div', {
        'id' : 'replyform_' + replyId,
        'class' : 'reply'
    });
    
    var img = new Element ('img', {
        'id' : 'revHeadImg',
        'src' : '/comments/widgets/commentsAndRatings/images/addReviews_header.gif'
    });

    if (commentConfig.app == "TV") {} else {

        Event.observe (img, "mouseover", function (e) {that.rater.clearRating.call (that.rater, e);});

        Event.observe (img, "mouseout", function (e) {that.rater.clearRating.call (that.rater, e);});
    }

    var a = new Element ('a', {
        'name' : 'reviewForm'
    });

    var dLifeUserName = this.readCookie ("dLifeUserName");

    if (dLifeUserName == "null" || dLifeUserName == null) {
        dLifeUserName = "Unknown";
    }
       
    var info = new Element ('div', {
        'id' : 'rateInfoDiv',
        'class' : 'replyUsername'
    }).update ("Your name: " + dLifeUserName);

    if (commentConfig.app == "TV") {} else {

        Event.observe (info, "mouseover", function (e) {that.rater.clearRating.call (that.rater, e);});

        Event.observe (info, "mouseout", function (e) {that.rater.clearRating.call (that.rater, e);});
    }
    
    var review = new Element ("div", {});
    
    var ul = new Element ('ul');
     
    var li = new Element ('li', {'class': 'plainText'}).update ("Web page addresses and e-mail addresses turn into links automatically.");
    
    ul.insert (li);
    
    var li = new Element ('li', {'class' : 'plainText'}).update ("Lines and paragraphs break automatically.");
    
    ul.insert (li);
    
    var textarea = new Element ('textarea', {
        'name'  : 'data',
        'class' : 'commentText',
        'rows'  : '8'
    });
    
    var rating = new Element ('div', {});

    var optDiv = new Element ("div", {'class': 'reqDiv'});

    if (loadRater == true) {

        if (canRate == true) {

            optDiv.update ("(Optional)");

            var headImg = new Element ('img', {
               'id'  : 'memberRatings',
               'src' : "/comments/widgets/commentsAndRatings/images/rateandreview.jpg"
            });

            if (commentConfig.app != "TV")

            div.insert (headImg);

            var img2 = new Element ('img', {
               'id'  : 'rateHeadImg',
               'src' : '/comments/widgets/commentsAndRatings/images/addyourrating.jpg'
            });

            if (this.allowRatings == true) {

            Event.observe (img2, "mouseover", function (e) {that.rater.clearRating.call (that.rater, e);});

            Event.observe (img2, "mouseout", function (e) {that.rater.clearRating.call (that.rater, e);});
            }
 
            if (commentConfig.app != "TV")
            rating.insert (img2);

            var reqDiv = new Element ('div', {'class' : 'reqDiv'}).update ("(Required)");

            if (commentConfig.app != "TV")
            rating.insert (reqDiv);

            if (commentConfig.app != "TV")
        
            rating.insert (this.rater.displayRater ());

            var textDiv = new Element ('div', {
                'id' : 'ratingText'
            });

            if ($("dlRating")) {
            if (this.allowRatings == true) {
                Event.observe (textDiv, "mouseover", function (e) {that.rater.clearRating.call (that.rater, e);});

                Event.observe (textDiv, "mouseout", function (e) {that.rater.clearRating.call (that.rater, e);});
            }
            }

            rating.insert(textDiv);
    
            var input = new Element ("input", {
                'name' : 'appId',
                'type' : 'hidden',
                'value' : commentConfig.app 
            });
    
            div.insert (input);
    
            var input = new Element ("input", {
                'id' : 'dlRatingInput',
                'name' : 'dlRatingInput',
                'type' : 'hidden',
                'value' : 0
            });

            div.insert (input);

            var input = new Element ("input", {
                'name' : 'contentType',
                'type' : 'hidden',
                'value' : commentConfig.type
            });
    
            div.insert (input);

        } else {

            var headImg = new Element ('img', {
               'id' : 'memberRatings',
               'src' : "/comments/widgets/commentsAndRatings/images/rateandreview.jpg"
            });

            div.insert (headImg);

            var input = new Element ("input", {
               'name' : 'appId',
               'type' : 'hidden',
               'value' : commentConfig.app
            });

            div.insert (input);

            var input = new Element ("input", {
                'name' : 'contentType',
                'type' : 'hidden',
                'value' : commentConfig.type
            });

            div.insert (input);

        }
    
    } else {
        var input = new Element ("input", {
            'name'  : 'commentId',
            'value' : replyId,
            'type'  : 'hidden'
        });

        optDiv.update ("");

        div.insert (input);
    }

    var input = new Element ("input", {
        'name' : 'sendEmail',
        'type' : 'checkbox'         
    });
   
    div.insert (info);
    div.insert (rating);
    div.insert (review);
    div.insert (img);
    div.insert (optDiv);
    div.insert (a);
    div.insert (textarea);
    div.insert (ul);

    var button = new Element ("img", {
        'src' : '/comments/widgets/commentsAndRatings/images/submit_comment.gif'
    });
   
    Event.observe (button, "click", function (e) {
        that.submitComment.call (that, e);
    });
     
    div.insert (button);
    
    openReplies ["replyform_" + replyId] == "open";

    return div; 
}

dlCommentSys.prototype.addCallback = function (post, node)
{
    var that = Object.clone (this);

    req = new dlAjax ();

    post.assetId = commentConfig.asset;

    var callback = function (transport) {

        var response = transport.responseXML;

        var content = response.getElementsByTagName ("content") [0];

        that.itterateComments (content, 1);

        node.parentNode.removeChild (node);

        var replyForm = null;

        if (commentConfig.loadRater == "false") {
            replyForm = that.loadReplyForm (commentConfig.asset, false);
        } else {
            replyForm = that.loadReplyForm (commentConfig.asset, true)
        }

        $(commentConfig.container).insert (replyForm);

        replyForm.getElementsByTagName ("textarea") [0].focus ();

        if (commentConfig.app != "TV") {

            $("rateBarDiv").style.height          = "18px";
            $("rateBarDiv").style.backgroundColor = "#e3f6ff";
            $("rateBarDiv").style.textAlign       = "center";
            $("rateBarDiv").style.fontWeight      = "bold";
            $("rateBarDiv").style.borderBottom    = "solid 2px #3399cc";

            $("rateBarDiv").update ("Thank you for your rating & review!");
        }
    }

    req.generate (post, "AddComment");
    req.send (callback);
}

dlCommentSys.prototype.submitComment = function (e) {         

    var that = Object.clone (this);

    if (commentConfig.loggedIn != true) {

        if (confirm ("You need to login to rate and review.")) {
            window.location.href = "/dLife/do/BlogabetesLogin"; 
            return false;
        } else {
            return false;
        }

    } else if (commentConfig.hasUsername != true) {

        if (confirm ("You need to create a user name to rate and review.")) {
           window.location.href = "/dLife/do/BlogabetesLogin";
        } else {
            return false;
        }

    } else {

        var node = e.target.parentNode;
 
        var textArea = node.getElementsByTagName ("textarea") [0].value;

        if ((textArea.length == 0) && ($('dlRatingInput').value == 0)) {
            alert ('Please provide a rating before clicking "Submit."');
            return;
        }

        var post = {
            'data' : '<![CDATA[' +  textArea + "]]>"
        }
    
        var inputs = node.getElementsByTagName ("input");
    
        for (var i = 0; i < inputs.length; i ++) {
            if (inputs [i].name == "dlRatingInput") { continue; }
            if (inputs [i].type == "checkbox") {    
                post[inputs [i].name] = inputs [i].checked;
            } else {
                post[inputs [i].name] = inputs [i].value;
            }   
        }
    
        var callback;
     
        var req = new dlAjax ();
     
        if (post.commentId) {

            delete post.status;
            delete post.active;
            delete post.shallow;

            post.assetId = commentConfig.asset;
            post.contentType = commentConfig.type;
            post.appId = commentConfig.app;

            post.sendEmail = "";

            // HAPPENS ON REPLIES
            callback = function (transport) {

                var response = transport.responseXML;

                var content = response.getElementsByTagName ("content") [0];
            
                that.itterateComments (content, 2, node.id);
            
                openReplies [node.parentNode.parentNode.parentNode.parentNode.parentNode.id] = null;

                node.parentNode.removeChild (node);          
            }
        
            req.generate (post, "AddReply");
            req.send (callback);
            
        } else {

            // HAPPENS ON ADDS

            if ($('dlRatingInput')) {
         
                if ($('dlRatingInput').value > 0) {

                   if (commentConfig.app != "TV") {

                    this.rater.submitRating ($('dlRatingInput').value);

                    this.rater.updateLocalPage (this.asset, $('dlRatingInput').value);

                    setTimeout (function () {that.addCallback (post, node);}, 300);

                    }

                } else {
                    this.addCallback (post, node);
                }

            } else {
                this.addCallback (post, node);
            } 
        }
    }
}



dlCommentSys.prototype.readCookie = function (key) {

    var nameEQ = key + "=";
    var ca = document.cookie.split (';');
    
    for (var i = 0; i < ca.length; i ++) {
        var c = ca [i];
        while (c.charAt (0) == ' ') {
            c = c.substring (1, c.length);
        }
        
        if (c.indexOf (nameEQ) == 0) {
            return c.substring (nameEQ.length, c.length);
        }
    }
    return null;
}
