/* To use this script, modify the names below to suit your needs (Or remove both the names). Make sure the last name in the list does not have a comma.
Commas should only go between each name.
Once you've finished modifying the names, copy this entire script. If using Google Chrome,
open up the Developer console with F12 (while on the RSI Website), paste the script, press ENTER key to execute the script.
You will see it say "DONE!" when it finishes"
By default this script will automatically follow all members visible in RR.

YOUTUBE Demo: https://youtu.be/cFpX0IxNDvM
*/


var RROMemberScript =
    {
        baseAddressLive: "https://robertsspaceindustries.com/",
        baseAddressPtu: "https://ptu.cloudimperiumgames.com/",
        maximumContactsPrefilCount: 200,    // The maximum number of contacts this script will add

        // The members of organisation. The redacted or hidden members are included.
        OtherContacts: [

            'illanar',
            'ranalli'
  

        ],

        // The members that will be removed from contactlist. IE: Old members of organisation.
        /**
            OldMembers: [
        
            ],
        **/

        // nothing needs to be filled in here
        addedMembers: [],

        // Get the server base address. Supports PTU and live.
        getBaseAddress: function () {
            if ($("#ptubar").length)
                return this.baseAddressPtu;

            return this.baseAddressLive;
        },
        // getCookie from http://stackoverflow.com/a/11767598 by Paul Sweatte
        // Extracts a cookie from document.cookie
        getCookie: function (cookiename) {
            // Get name followed by anything except a semicolon
            var cookiestring = RegExp("" + cookiename + "[^;]+").exec(document.cookie);
            // Return everything after the equal sign
            return unescape(!!cookiestring ? cookiestring.toString().replace(/^[^=]+./, "") : "");
        },

        // additional headers, here we only use the RSI token from the cookie.
        __hs: function () {
            return { "X-Rsi-Token": this.getCookie('Rsi-Token') };
        },

        /**
         * Follow one Star Citizen.
         * name is the nickname/handle of the player.
         * follow=true -> follow, follow=false -> unfollow
         */
        changeFollow: function (name, follow) {
            var that = this;

            if (!follow || (that.addedMembers.length < that.maximumContactsPrefilCount && that.addedMembers.indexOf(name.toLowerCase()) < 0)) {
                $.ajax({
                    async: false,
                    type: "post",
                    url: that.getBaseAddress() + "api/contacts/" + (follow ? "add" : "erase"),
                    success: function (d) {
                        if (d.msg != 'Validation failed' && d.msg != 'ErrCannotAddItself' && d.msg != 'ErrNoAccountForNickname') {
                            // tell the user if it worked
                            console.log((follow ? "Following " : "Unfollowing ") + name + " -> " + d.msg);

                            if (follow)
                                that.addedMembers.push(name.toLowerCase());
                        }
                    },
                    data: JSON.stringify({
                        nickname: name
                    }),
                    headers: that.__hs()
                });
            }
        },

        /**
         * Erase ALL members in your contacts list.
         */
        eraseAll: function () {
            var that = this;

            $.ajax({ // request a page of members
                async: false,
                type: "post",
                url: that.getBaseAddress() + "api/contacts/list",
                success: function (d) {
                    //console.debug(d);
                    if (d.data.resultset.length) { // still more members available
                        $.each(d.data.resultset, function (i, field) {
                            that.changeFollow(field.nickname, false);
                        });
                        // load next charge/page of members
                        that.eraseAll();
                    }
                },
                data: JSON.stringify({
                    page: 1,
                    query: ""
                }),
                headers: that.__hs()
            });
        },

        /**
         * Follow all members of an organization
         * sid is the SID, Spectrum ID/handle of the organization.
         * follow=true -> follow, follow=false -> unfollow
         * page defaults to 1, dont use it.
         */
        changeOrgFollow: function (sid, follow, page) {
            var that = this;

            page = page || 1;
            $.ajax({ // request a page of members
                async: false,
                type: "post",
                url: that.getBaseAddress() + "api/orgs/getOrgMembers",
                success: function (d) {
                    //console.debug(d); // debug received data
                    if (d.data && d.data.html) { // still more members available
                        // parse to DOM object
                        dt = $('<div></div');
                        dt.html(d.data.html);
                        // (un-)follow all members
                        $('.nick', dt).each(function (i, field) {
                            that.changeFollow(field.innerHTML, follow);
                        });

                        // load next charge/page of members
                        that.changeOrgFollow(sid, follow, page + 1);
                    }
                },
                data: JSON.stringify({
                    symbol: sid.toUpperCase(),
                    page: page
                }),
                headers: that.__hs()
            });
        },

        /**
        * Append extra members
        */
        appendMembers: function (members) {
            var that = this;

            $.each(members, function (i, name) {
                that.changeFollow(name, true);
            });
        },

        /**
        * Remove old members
        */
        removeMembers: function (oldmembers) {
            var that = this;

            $.each(oldmembers, function (i, name) {
                that.changeFollow(name, false);
            });
        },

        /**
        * Execute the script.
        **/
        execute: function () {
            this.eraseAll();
            this.appendMembers(this.OtherContacts);
            // this.removeMembers(this.oldMembers));


            this.changeOrgFollow('RRO', true);

    
  


            console.log('DONE! Added ' + this.addedMembers.length + " members.")

            this.addedMembers.length = [];
        }
    };
RROMemberScript.execute();