/* BEGIN: Define everything in anonymous function to prevent name spilling */
(function(){
    /* -----> */
    
    /* Disable existing toolbar functions */
    if (window.toolbar) {
        window.toolbar = function(){
        };
    }
    
    /* Declare namespaces updated in this file: Redeclaration is fine */
    CNET.namespace('CNET.Blog.Toolbar');
    
    /* BEGIN: AjaxConfig Toolbar Class */
    CNET.Blog.Toolbar.AjaxConfig = function(){
        this.url = null;
        this.urlParams = {};
        this.requestMethod = 'GET';
        this.success = null;
        this.failure = null;
        this.scope = null;
        this.timeout = null;
    };
    /* END: AjaxConfig Toolbar Class */
    
    /* BEGIN: Interact Toolbar Class */
    CNET.Blog.Toolbar.Interact = function(){
        this.id = null;
        this.idContainer = null;
        this.ajaxGetDetails = new CNET.Blog.Toolbar.AjaxConfig();
        this.ajaxSendVote = new CNET.Blog.Toolbar.AjaxConfig();
        this.enableCommentModule = true;
        this.numTalkbacks = 0;
        this.toolbarButtons = ['share', 'print', 'email', 'recommend', 'vote'];
        this.toolbarSectionDivider = ['email'];
        this.title = '';
        this.diggBodyText = '';
        this.diggTopic = '';
        this.emailTitle = '';
        this.absoluteUrl = 'http://blogs.zdnet.com/Apple/?p=1054';
        this.relativeUrl = '?p=1054';
        this.commentUrl = '?p=1054#comments';
        this.votingId = 'Apple_1054';
        
        this.recommend = {};
        this.recommend.contentId = this.idContainer;
        this.recommend.hasVoted = false;
        this.recommend.userId = null;
        this.recommend.thumbsUp = true;
        this.recommend.thumbsDown = true;
        this.recommend.encodedTitle = '';
        this.recommend.encodedUrl = '';
        this.recommend.rpcHost = '';
        this.recommend.loginUrl = '';
        this.recommend.returnUrl = '';
        this.recommend.cookieResults = '';
        
        this.voting = {};
        this.voting.contentId = this.idContainer;
        this.voting.rating = 0;
        this.voting.voteCount = 0;
        
        this.node = {};
        this.node.interact = null;
        this.node.comments = null;
        this.node.voteButton = null;
        this.node.toolbar = null;
        this.styles = {};
        this.styles.voteButtonClassName = '';
        
        this._renderComplete = false;
    };
    
    /* BEGIN: Interact Toolbar Member Functions */
    CNET.Blog.Toolbar.Interact.prototype = {
        init: function(){
            YAHOO.util.Event.onContentReady(this.idContainer, this.render, this, true);
        },
        cancelClick: function(e){
            if (e.preventDefault) {
                e.preventDefault();
            }
            return false;
        },
        handleMouseoverShare: function(){
            YAHOO.util.Dom.addClass(this.element, 'drill');
        },
        handleMouseoutShare: function(){
            YAHOO.util.Dom.removeClass(this.element, 'drill');
        },
        handlePrintClick: function(e){
            window.print();
            return this.cancelClick(e);
        },
        handleDiggLinkClick: function(e){
            var url = 'http://digg.com/submit?phase=2&url=' + encodeURIComponent(this.absoluteUrl) + '&title=' + encodeURIComponent(this.title) + '&bodytext=' + encodeURIComponent(this.diggBodyText) + '&topic=' + encodeURIComponent(this.diggTopic);
            window.open(url, 'digg');
            return this.cancelClick(e);
        },
        handleDeliciousLinkClick: function(e){
            window.open('http://del.icio.us/post?v=4&noui&jump=close&url=' + encodeURIComponent(this.absoluteUrl) + '&title=' + encodeURIComponent(this.title), 'delicious', 'toolbar=no,width=700,height=400');
            return this.cancelClick(e);
        },
        handleThumbsUpClick: function(e){
            if (this.recommend.userId == '') {
                this.recommend.userId = '0';
            }
            var voteUrl = "http://" + this.recommend.rpcHost + "/rpc.php?url=" + this.recommend.encodedUrl + "&rid=" + this.recommend.userId + "&title=" + this.recommend.encodedTitle;
            sendVote(1, this.recommend.cookieResults, this.recommend.contentId, voteUrl);
            return this.cancelClick(e);
        },
        handleThumbsDownClick: function(e){
            if (this.recommend.userId == '') {
                this.recommend.userId = '0';
            }
            var voteUrl = "http://" + this.recommend.rpcHost + "/rpc.php?url=" + this.recommend.encodedUrl + "&rid=" + this.recommend.userId + "&title=" + this.recommend.encodedTitle;
            sendVote(-1, this.recommend.cookieResults, this.recommend.contentId, voteUrl);
            return this.cancelClick(e);
        },
        updateComments: function(){
            var commentsNode = this.createTalkBackSection();
            this.node.interact.insertBefore(commentsNode, this.node.comments);
            this.node.interact.removeChild(this.node.comments);
            this.node.comments = commentsNode;
        },
        updateVoteButton: function(){
            var voteButton = this.createVoteButton(this.styles.voteButtonClassName);
            this.node.toolbar.insertBefore(voteButton, this.node.voteButton);
            this.node.toolbar.removeChild(this.node.voteButton);
            this.node.voteButton = voteButton;
        },
        render: function(){
            var i, len;
            
            var interactNode = document.getElementById(this.idContainer);
            this.node.interact = interactNode;
            if (this.enableCommentModule) {
                var commentsNode = this.createTalkBackSection();
                interactNode.appendChild(commentsNode);
                this.node.comments = commentsNode;
            }
            var toolbarNode = interactNode.appendChild(document.createElement('UL'));
            this.node.toolbar = toolbarNode;
            toolbarNode.className = 'toolbar';
            for (i = 0, len = this.toolbarButtons.length; i < len; i++) {
                var button = this.toolbarButtons[i];
                
                var j, jlen, classMainLink = '';
                for (j = 0, jlen = this.toolbarSectionDivider.length; j < jlen; j++) {
                    if (this.toolbarSectionDivider[j] == button) {
                        classMainLink = 'last';
                    }
                }
                if (button == 'share') {
                    toolbarNode.appendChild(this.createShareButton(classMainLink));
                }
                else 
                    if (button == 'print') {
                        toolbarNode.appendChild(this.createPrintButton(classMainLink));
                    }
                    else 
                        if (button == 'email') {
                            toolbarNode.appendChild(this.createEmailButton(classMainLink));
                        }
                        else 
                            if (button == 'save') {
                            // TODO: Add Save button
                            }
                            else 
                                if (button == 'recommend') {
                                    toolbarNode.appendChild(this.createRecommendButton(classMainLink));
                                }
                                else 
                                    if (button == 'vote') {
                                        var voteButton = this.createVoteButton(classMainLink);
                                        toolbarNode.appendChild(voteButton);
                                        this.node.voteButton = voteButton;
                                        this.styles.voteButtonClassName = classMainLink;
                                    }
                                    else 
                                        if (button == 'pdf') {
                                        // TODO: Add PDF button
                                        }
            }
            this._renderComplete = true;
        },
        createTalkBackSection: function(){
            var text = 'TalkBack';
            if (this.numTalkbacks) {
                var n = parseInt('' + this.numTalkbacks, 10);
                if (n == 0) {
                    text = '<span>TalkBack</span>';
                }
                else 
                    if (this.numTalkbacks > 1) {
                        text = this.numTalkbacks + ' <span>TalkBacks</span>';
                    }
                    else {
                        text = this.numTalkbacks + ' <span>TalkBack</span>';
                    }
            }
            var commentsNode = document.createElement('DIV');
            commentsNode.className = 'cmntCount';
            commentsNode.innerHTML = '<a href="' + this.commentUrl + '">' + text + '</a>';
            return commentsNode;
        },
        createShareButton: function(){
            var shareButton = document.createElement('LI');
            var shareLink = shareButton.appendChild(document.createElement('A'));
            
            shareLink.href = '#';
            shareLink.title = 'Share';
            
            shareButton.className = 'share pops';
            var optsShare = shareButton.appendChild(document.createElement('DIV'));
            optsShare.id = 'optsShare_' + this.votingId;
            YAHOO.util.Event.addListener(shareButton, 'mouseover', this.handleMouseoverShare, this, {
                element: shareButton
            });
            YAHOO.util.Event.addListener(shareButton, 'mouseout', this.handleMouseoutShare, this, {
                element: shareButton
            });
            
            /* Build the list */
            var shareOptions = optsShare.appendChild(document.createElement('UL'));
            
            var diggOption = shareOptions.appendChild(document.createElement('LI'));
            var buzzOption = shareOptions.appendChild(document.createElement('LI'));
            var twitterOption = shareOptions.appendChild(document.createElement('LI'));
            var fbOption = shareOptions.appendChild(document.createElement('LI'));
            var googOption = shareOptions.appendChild(document.createElement('LI'));
            var deliciousOption = shareOptions.appendChild(document.createElement('LI'));
            var stumbleOption = shareOptions.appendChild(document.createElement('LI'));
            var redditOption = shareOptions.appendChild(document.createElement('LI'));
            var newsVineOption = shareOptions.appendChild(document.createElement('LI'));
            var technoOption = shareOptions.appendChild(document.createElement('LI'));
            var linkedinOption = shareOptions.appendChild(document.createElement('LI'));
            
            /* Build the links */
            
            var diggLink = diggOption.appendChild(document.createElement('A'));
            var buzzLink = buzzOption.appendChild(document.createElement('A'));
            var twitterLink = twitterOption.appendChild(document.createElement('A'));
            var fbLink = fbOption.appendChild(document.createElement('A'));
            var googLink = googOption.appendChild(document.createElement('A'));
            var deliciousLink = deliciousOption.appendChild(document.createElement('A'));
            var stumbleLink = stumbleOption.appendChild(document.createElement('A'));
            var redditLink = redditOption.appendChild(document.createElement('A'));
            var newsVineLink = newsVineOption.appendChild(document.createElement('A'));
            var technoLink = technoOption.appendChild(document.createElement('A'));
            var linkedinLink = linkedinOption.appendChild(document.createElement('A'));
            
            
            diggLink.className = 'digg';
            diggLink.href = '#';
            diggLink.title = 'Send to digg';
            buzzLink.className = 'buzz';
            buzzLink.href = 'http://buzz.yahoo.com/buzz?targetUrl=' + this.absoluteUrl + '&headline=' + encodeURIComponent(this.title) + '&category=science';
            buzzLink.target = '_blank';
            twitterLink.className = 'tweet';
            twitterLink.href = 'http://twitter.com/home?status=' + encodeURIComponent(this.title) + '+' + this.absoluteUrl;
            twitterLink.target = '_blank';
            fbLink.className = 'fb';
            fbLink.href = 'javascript:var d=document,f=\'http://www.facebook.com/share\',l=d.location,e=encodeURIComponent,p=\'.php?src=bm&v=4&i=1208544185&u=\'+e(l.href)+\'&t=\'+e(d.title);1;try{if (!/^(.*\.)?facebook\.[^.]*$/.test(l.host))throw(0);share_internal_bookmarklet(p)}catch(z) {a=function() {if (!window.open(f+\'r\'+p,\'sharer\',\'toolbar=0,status=0,resizable=0,width=626,height=436\'))l.href=f+p};if (/Firefox/.test(navigator.userAgent))setTimeout(a,0);else{a()}}void(0)';
            googLink.className = 'goog';
            googLink.href = 'http://www.google.com/bookmarks/mark?op=add&title=' + encodeURIComponent(this.title) + '&bkmk=' + this.absoluteUrl;
            googLink.target = '_blank';
            deliciousLink.className = 'del';
            deliciousLink.href = '#';
            deliciousLink.title = 'Add to del.icio.us';
            stumbleLink.className = 'su';
            stumbleLink.href = 'http://www.stumbleupon.com/submit?url=' + this.absoluteUrl;
            stumbleLink.target = '_blank';
            redditLink.className = 'reddit';
            redditLink.href = 'http://reddit.com/submit?url=' + this.absoluteUrl + '&title=' + encodeURIComponent(this.title);
            redditLink.target = '_blank';
            newsVineLink.className = 'nv';
            newsVineLink.href = 'http://www.newsvine.com/_wine/save?popoff=1&u=' + this.absoluteUrl + '&h=' + encodeURIComponent(this.title);
            newsVineLink.target = '_blank';
            technoLink.className = 'techno';
            technoLink.href = 'http://technorati.com/faves?add=' + this.absoluteUrl;
            technoLink.target = '_blank';
            linkedinLink.className = 'linkedin';
            linkedinLink.href = 'http://www.linkedin.com/shareArticle?mini=true&url=' + this.absoluteUrl + '&title=' + encodeURIComponent(this.title) + '&source=ZDNet';
            linkedinLink.target = '_blank';
            
            /* Attach Event Handlers */
            YAHOO.util.Event.addListener(diggLink, 'click', this.handleDiggLinkClick, this, true);
            YAHOO.util.Event.addListener(deliciousLink, 'click', this.handleDeliciousLinkClick, this, true);
            
            return shareButton;
        },
        createPrintButton: function(){
            var printButton = document.createElement('LI');
            printButton.className = 'print';
            var printLink = printButton.appendChild(document.createElement('A'));
            printLink.title = 'Print';
            printLink.href = "#";
            printLink.appendChild(document.createTextNode('Print'));
            YAHOO.util.Event.addListener(printLink, 'click', this.handlePrintClick, this, true);
            return printButton;
        },
        createEmailButton: function(classMainLink){
            var emailButton = document.createElement('LI');
            emailButton.className = 'email';
            var emailLink = emailButton.appendChild(document.createElement('A'));
            emailLink.href = 'mailto:?subject=' + encodeURIComponent(this.emailTitle) + '&body=' + encodeURIComponent(this.title + "\n" + this.absoluteUrl + "\n");
            emailLink.className = classMainLink;
            emailLink.title = 'Email';
            emailLink.appendChild(document.createTextNode('Email'));
            return emailButton;
        },
        createRecommendButton: function(){
            var recommendButton = document.createElement('LI');
            recommendButton.id = 'voteStatus' + this.recommend.contentId;
            if (this.recommend.hasVoted) {
                recommendButton.className = 'thanks';
                return recommendButton;
            }
            else {
                recommendButton.className = 'recommend';
                var thumbsUpLink = recommendButton.appendChild(document.createElement('A'));
                thumbsUpLink.className = 'thmbUp';
                thumbsUpLink.title = 'Recommend this article';
                thumbsUpLink.href = "#";
                thumbsUpLink.appendChild(document.createTextNode('Thumbs Up'));
                var thumbsDownLink = recommendButton.appendChild(document.createElement('A'));
                thumbsDownLink.className = 'thmbDwn';
                thumbsDownLink.title = "Don't recommend this article";
                thumbsDownLink.href = "#";
                thumbsDownLink.appendChild(document.createTextNode('Thumbs Down'));
                YAHOO.util.Event.addListener(thumbsUpLink, 'click', this.handleThumbsUpClick, this, true);
                YAHOO.util.Event.addListener(thumbsDownLink, 'click', this.handleThumbsDownClick, this, true);
            }
            return recommendButton;
        },
        createVoteButton: function(){
            var voteButton = document.createElement('LI');
            voteButton.className = 'vote';
            var voteCount = voteButton.appendChild(document.createElement('DIV'));
            voteCount.className = 'votecount';
            voteCount.id = 'votes' + this.votingId;
            voteCount.title = 'How many people recommended this article';
            voteCount.appendChild(document.createTextNode((this.voteCount < 0 ? this.voteCount : '+' + this.voteCount)));
            var voteTotal = voteButton.appendChild(document.createElement('DIV'));
            voteTotal.className = 'votetotal';
            voteTotal.id = 'vote_text' + this.votingId;
            voteTotal.title = 'Total votes';
            voteTotal.appendChild(document.createTextNode(this.voteTotal));
            
            return voteButton;
        }
    };
    /* END: Interact Toolbar Member Functions */
    CNET.Blog.Toolbar.Interact.allToolbars = [];
    CNET.Blog.Toolbar.Interact.service = {};
    CNET.Blog.Toolbar.Interact.service.url = 'http://service.zdnet.com/service/spot/toolbar.json';
    CNET.Blog.Toolbar.Interact.service.domain = 'blogs.zdnet.com';
    CNET.Blog.Toolbar.Interact.service.contentId = [];
    CNET.Blog.Toolbar.Interact.service.responseSave = 'CNET.Blog.Toolbar.Interact.commentsAndVotes';
    CNET.Blog.Toolbar.Interact.service.responseCallback = 'CNET.Blog.Toolbar.Interact.updateAllToolbars';
    CNET.Blog.Toolbar.Interact.commentsAndVotes = {};
    CNET.Blog.Toolbar.Interact.service.callService = function(){
        var service = CNET.Blog.Toolbar.Interact.service;
        var completeUrl = service.url +
        '?ct=' +
        service.domain +
        '&cid=' +
        service.contentId.join(',') +
        '&tv=' +
        service.responseSave +
        '&fn=' +
        service.responseCallback;
        YAHOO.util.Get.script(completeUrl, {
            onSuccess: function(){
            }
        });
    }
    CNET.Blog.Toolbar.Interact.updateAllToolbars = function(){
        var i, len;
        
        allRenderComplete = true;
        for (i = 0, len = CNET.Blog.Toolbar.Interact.allToolbars.length; i < len; i++) {
            var tb = CNET.Blog.Toolbar.Interact.allToolbars[i];
            if (!tb._renderComplete) {
                allRenderComplete = false;
            }
        }
        
        if (!allRenderComplete) {
            setTimeout(CNET.Blog.Toolbar.Interact.updateAllToolbars, 300);
            return;
        }
        
        for (i = 0, len = CNET.Blog.Toolbar.Interact.allToolbars.length; i < len; i++) {
            var tb = CNET.Blog.Toolbar.Interact.allToolbars[i];
            var cv = CNET.Blog.Toolbar.Interact.commentsAndVotes;
            if ((typeof cv[tb.id] === 'object') && (cv[tb.id])) {
                tb.numTalkbacks = cv[tb.id].comments;
                tb.voting.rating = cv[tb.id].rating;
                tb.voting.voteCount = cv[tb.id].timesRated;
                tb.updateComments();
                tb.updateVoteButton();
            }
        }
    }
    /* END: Interact Toolbar Class */

    /* <----- */
})();
/* END: Define everything in anonymous function call to prevent name spilling */

