/**
 * JavaScript Library for managing discussion board services
 */

var DiscussionBoard = Class.create();
DiscussionBoard.attributes = [ "npo", "group", "mode", "auth" ];
DiscussionBoard.prototype = {
    initialize: function(stage) {
        // if global, use it; else, create a local version
        if(!stage) {
            var stage = '';
        }
        var base = "http://"+stage+"www.care2.com/c2c/";
        // Thread List
        ajaxEngine.registerRequest('getThreadList', base+'groups/disc_list.html');
        // no need to register element/object, uses automatic HTML responses

        // custom questions
        ajaxEngine.registerRequest('getUpdateCustom', 'http://'+stage+'www.care2.com/passport/services/profile_custom.html');
        // no need to register element/object, uses automatic HTML responses

        // Thread List
        ajaxEngine.registerRequest('getThread', base+'groups/disc.html');
        // no need to register element/object, uses automatic HTML responses

        // Profile/Mini-profile
        ajaxEngine.registerRequest('getProfile', base+'people/profile.html');
        ajaxEngine.registerRequest('getTPAProfile', base+'people/miniprofile.html');

        // reply
        ajaxEngine.registerRequest('getReplyForm', base+'groups/disc_post_reply.html');
        // no need to register element/object, uses automatic HTML responses

        // reply
        ajaxEngine.registerRequest('getNewTopicForm', base+'groups/disc_post.html');
        // no need to register element/object, uses automatic HTML responses

        // about
        ajaxEngine.registerRequest('getInfoAbout', base+'/about.html');
        // no need to register element/object, uses automatic HTML responses

        // moderation
        ajaxEngine.registerRequest('doModeration', base+'/groups/ddb/moderate.html');

        // general returns
        ajaxEngine.registerRequest('doGeneral', base+'/groups/ddb/do.html');


        // no need to register element/object, uses automatic HTML responses
        this.group = 0;
        this.mode = 'XML';
        this.stage = stage;
        this.parser = new JsFromXml();
        this.passthru = locationHandler.passthru;
        this.configurator = {
            board: this,
            ajaxUpdate: function(xml) {
                var data = this.board.parser.parse(xml.firstChild);
                if(this.callbacks[data.cmd]) {
                    this.callbacks[data.cmd](this.board, data);
                }
            },
            callbacks: {
                addTinyMCE: function(board, data) {
                    if(!tinyMCE) { // || window.navigator.appName=="Microsoft Internet Explorer") {
                        return;
                    }
                    // capture submittals
                    var t = $('ddb_button_submit');
                    var b = $(data.id);
                    if(t && b) {
                    	tinyMCE.execCommand('mceAddControl', false, data.id);
                        Event.observe(t, 'click', tinyMCE.triggerSave, false);
                    }
                    return;
                },
                redirect: function(board, data) {
                    if(data.url) {
                        window.location=data.url;
                    }
                },
                redraw: function(board, params) {
                    locationHandler.location.params = params;
                    board.draw(params);
                }
            }
        };
        ajaxEngine.registerAjaxObject('configure', this.configurator);
    },

    ajaxUpdate: function(ajaxResponse) {
        // noop
    },

    // wrap send request to add automatic parameters
    sendRequest: function() {
        var param = [];
        var c = arguments.length;
        for(var i=0;i<c;++i) {
            param.push(arguments[i]);
        }
        param = param.concat(this.passthru.encoded());
        ajaxEngine.sendRequest.apply(ajaxEngine, param);
    },

    run: function(npoID, groupID) {
        discussionBoard.npo = npoID;
        discussionBoard.group = groupID;
        this.auth             = new ThirdPartyAuth({npoID: npoID,
                                                    stage: discussionBoard.stage});

        // update the default passthru implementation
        // and translate my id -> Typo3Id if necessary
        this.passthru.encode = function(key) {
            if(key == 'id') {
                return 'Typo3Id';
            }
            return key;
        };
        this.passthru.decode = function(key) {
            if(key == 'Typo3Id') {
                return 'id';
            }
            return key;
        };

        // give tpa any passthru
        this.auth.passthru = this.passthru;

        // and draw
        this.draw(locationHandler.location.params);
    },
    draw: function(params) {

        if(params['topic']) {
            this.displayInfoAbout(params['topic']);
        } else if(params['pID']) {
            this.displayProfile(params['pID'], null);
        } else if(params['tpa_accountID']) {
            this.displayProfile(null, params['tpa_accountID']);
        } else if('new_topic' == params['post']) {
            this.displayNewTopic();
        } else if('reply' == params['post']) {
            this.displayReply(params['pst']);
        } else if('updateCustom' == params['do']) {
            this.displayUpdateCustom(params);
        } else if('moderate' == params['do']) {
            if('block'==params['action']) {
                this.blockMember(params['accountID'], params['is_passportID']);
            } else if('hide'==params['action']) {
                this.hidePost(params['postID']);
            } else if('unblock'==params['action']) {
                this.unblockMember(params['accountID'], params['is_passportID']);
            } else if('unhide'==params['action']) {
                this.unhidePost(params['postID']);
            }
        } else if(params['pst']) {
            if('reply' == params['do']) {
                this.displayReply(params['pst']);
            } else {
                this.displayThread(params['pst']);
            }
        } else if (params['do']) {
            var camel = params['do']
                .replace(/_([a-z])/g,
                         function(m,l) { return l.toUpperCase(); })
                .replace(/^[a-z]/, function(m) { return m.toUpperCase(); });
            this['display'+camel](params);
        } else {
            this.displayThreadList();
        }
    },

    displayProfileForm: function (params) {
        var tgt = $('ddb_content');
        var str = 'discussionBoard.auth';
        var auth = this.auth;
        // on success - redir to updateCustom
        var url = locationHandler.createURL.apply(locationHandler,
                    [locationHandler.location.baseURL, 'do=updateCustom'].concat(
                                                this.passthru.clear()));
        params.pg = url;

        this.auth.checkLogin(tgt, str, function() {
                                 auth.renderProfileForm(tgt, str, params);
                             });
    },
    displayUpdateCustom: function(params) {
        var _closure = this;
        var tgt = $('ddb_content');
        var str = 'discussionBoard.auth';
        var url = '';
        if(params && params.pg) {
            url = params.pg;
        } else {
            url = locationHandler.createURL.apply(locationHandler,
                    [locationHandler.location.baseURL, 'main=main'].concat(
                                                this.passthru.clear()));
        }
        this.auth.checkLogin(tgt, str, function() {
                                 _closure.sendRequest('getUpdateCustom','service=1',
                                'id=ddb_content', 'C2TPA='+_closure.auth.getSessionId(),
                                'redir='+url);
                             });

    },
    displaySignUpForm: function (params) {
        var update = locationHandler.createURL.apply(locationHandler,
                            [locationHandler.location.baseURL,
                             'do=updateCustom'].concat(this.passthru.clear())
                        );
        if(params['pg']) {
          update += '&pg=' + escape(params['pg']);
        }
        var autoLoginURL = locationHandler.createURL.apply(locationHandler,
                            [locationHandler.location.baseURL,
                             'do=auto_login'].concat(this.passthru.clear())
                        );
        params.pg = update;
        this.auth.renderSignUpForm($('ddb_content'), 'discussionBoard.auth',
                                   params, autoLoginURL);
    },

    displayThread: function(threadID) {
        $('ddb_content').innerHTML = "<i>Loading thread " + threadID + "...</i>";
        discussionBoard.sendRequest('getThread', 'gpp='+this.group, 'pst='+threadID, 'service=1',
                               'id=ddb_content', 'C2TPA='+this.auth.getSessionId(),'npoID='+this.auth.getNpoId());

    },

    displayReply: function(threadID) {
        $('ddb_content').innerHTML = '<i>Loading reply form...</i>';
        if(!this.auth.getSessionId()) {
            this.displayLogin({pg: '?post=reply&pst='+threadID});
            return;
        }
        var foo = this;
        this.auth.checkLogin($('ddb_content'), 'discussionBoard.auth', function () {
            var params = [locationHandler.location.baseURL, 'pst='+threadID].concat(
                                                discussionBoard.passthru.clear());
            var url = locationHandler.createURL.apply(locationHandler, params);
            var url2 = locationHandler.location.baseURL;
            discussionBoard.sendRequest('getReplyForm', 'gpp='+foo.group, 'pst='+threadID, 'service=1',
                               'id=ddb_content', 'C2TPA=' + foo.auth.getSessionId(),
                                'onSuccess='+escape(url),
                                'baseURL='+escape(url2));
        });
        // may be logged in, or may not be, here.
    },

    displayNewTopic: function() {
        $('ddb_content').innerHTML = '<i>Loading new topic form...</i>';
        var foo = this;
        this.auth.checkLogin($('ddb_content'), 'discussionBoard.auth', function () {
            var params = [locationHandler.location.baseURL, 'main=main'].concat(
                                                discussionBoard.passthru.clear());
            var url = locationHandler.createURL.apply(locationHandler, params);
            var url2 = locationHandler.location.baseURL;
            discussionBoard.sendRequest('getNewTopicForm',
                                   'gpp='+foo.group,
                                   'id=ddb_content',
                                   'C2TPA=' + foo.auth.getSessionId(),
                                   'js=1',
                                    'onSuccess='+escape(url),
                                    'baseURL='+escape(url2) );
                              });
        // may be logged in, or may not be, here.
    },

    displayThreadList: function() {
        $('ddb_content').innerHTML = "<i>Loading posts...</i>";
        discussionBoard.sendRequest('getThreadList', 'gpp=' + this.group, 'id=ddb_content',  'service=1',
                               'C2TPA='+this.auth.getSessionId(),'npoID='+this.auth.getNpoId());
    },

    displayInfoAbout: function(topic) {
        $('ddb_content').innerHTML = "<i>Loading information...</i>";
        discussionBoard.sendRequest('getInfoAbout', 'id=ddb_content',  'service=1',
                               'C2TPA='+this.auth.getSessionId(), 'topic='+topic,
                               'npoID='+discussionBoard.npo);

    },

    updateTrackingStatus: function(msg, threadID, action) {
        $('ddb_content').innerHTML = "<i>"+msg+"</i>";
        discussionBoard.sendRequest('doGeneral', 'id=configure',  'service=1',
                               'C2TPA='+this.auth.getSessionId(), 'do='+action+'_tracking_thread',
                               'threadID='+threadID, 'groupID='+this.group);


    },
    stopTracking: function(threadID) {
        this.updateTrackingStatus('Processing update...', threadID, 'stop');
    },
    startTracking: function(threadID) {
        this.updateTrackingStatus('Processing update...', threadID, 'start');
    },

    displayProfile: function(profileID, tpa_accountID) {
        var pID = profileID;
        if(!pID) {
            pID = tpa_accountID;
        }

        $('ddb_content').innerHTML = "<i>Loading profile " + pID + "...</i>";
        if(profileID) {
            discussionBoard.sendRequest('getProfile', 'pid=' + profileID, 'id=ddb_content', 'service=1',
                               'C2TPA='+this.auth.getSessionId(), 'npoID='+discussionBoard.npo);
        } else {
            discussionBoard.sendRequest('getTPAProfile', 'id=ddb_content', 'service=1',
                               'tpa_accountID='+tpa_accountID, 'C2TPA='+this.auth.getSessionId(),
                               'npoID='+discussionBoard.npo);
        }
    },

    displayLogin: function(params) {
        this.auth.renderLoginForm($('ddb_content'), 'discussionBoard.auth' /* name of global */, params);
    },

    displayAutoLogin: function(params) {
        this.auth.autoLogin(params['email'], params['password'], params['pg']);
    },

    logout: function() {
        this.auth.logout();
    },

    deletePost: function(postID) {
        discussionBoard.sendRequest('doModeration', 'gpp='+this.group, 'pst='+postID, 'service=1',
                               'action=delete', 'id=ddb_content', 'C2TPA='+this.auth.getSessionId(),
                               'confirm='+locationHandler.location.params['confirm']);

    },

    blockMember: function(accountID, is_passportID) {
        $('ddb_content').innerHTML = "<i>Blocking user " + accountID + "...</i>";
        discussionBoard.sendRequest('doModeration', 'gpp='+this.group, 'accountID='+accountID,
                                'is_passportID='+is_passportID, 'service=1', 'action=block',
                                'id=ddb_content', 'C2TPA='+this.auth.getSessionId());

    },

    hidePost: function(postID) {
        $('ddb_content').innerHTML = "<i>Hiding post " + postID + "...</i>";
        var confirmed = 0;
        if(locationHandler.location.params['confirm']) {
            confirmed = 1;
        }
        discussionBoard.sendRequest('doModeration', 'gpp='+this.group, 'postID='+postID, 'service=1',
                               'action=hide', 'id=ddb_content', 'C2TPA='+this.auth.getSessionId(),
                               'confirm='+confirmed);

    },

    unblockMember: function(accountID, is_passportID) {
        $('ddb_content').innerHTML = "<i>Unblocking user " + accountID + "...</i>";
        discussionBoard.sendRequest('doModeration', 'gpp='+this.group, 'accountID='+accountID,
                                'is_passportID='+is_passportID, 'service=1', 'action=unblock',
                                'id=ddb_content', 'C2TPA='+this.auth.getSessionId());

    },

    unhidePost: function(postID) {
        $('ddb_content').innerHTML = "<i>Unhiding post " + postID + "...</i>";
        discussionBoard.sendRequest('doModeration', 'gpp='+this.group, 'postID='+postID, 'service=1',
                               'action=unhide', 'id=ddb_content', 'C2TPA='+this.auth.getSessionId());

    }



};
