/* Changes:
    1.05    Support different fb page layout
    1.04    Added config box
            Made "uncheck Show in News Feed" configurable
            Made friend list string configurable
            Made wait time configurable
            Made max confirmations configurable
*/

javascript:(//)
    function() {
        var version="ConfirmAll 1.05",
            content=document.getElementsByClassName('sidebar_item requests')[0],
            mwtools_div=$('mwtools'),
            wait,
            show,
            list,
            max;
        if (!content)
            content=document.getElementsByClassName('PYMK_Reqs_Sidebar')[0];
        wait = readCookie('mwtca_wait'); if (wait == null) wait = "1.0";
        max  = readCookie('mwtca_max');  if (max  == null) max  = 200;
        show = readCookie('mwtca_show'); if (show == null) show = "";
        list = readCookie('mwtca_list'); if (list == null) list = "mafia";
        if (!mwtools_div) {
            mwtools_div=document.createElement('div');
            mwtools_div.setAttribute('id','mwtools');
            mwtools_div.setAttribute('id','mwtools');
            if (content)
                content.appendChild(mwtools_div);
        }
        mwtools_div.innerHTML=
            '<hr style="background-color:#bbd;color:#bbd;border:solid 1px #bbd;margin:0 5px 9px"/>'+
            '<div class="sidebar_item_header clearfix">'+
                '<h2 class="withoption">'+version +'</h2>'+
                '<div class="option">'+
                    '<a href="http://vern.com/mwtools/">Vern\'s MW Tools</a>'+
                '</div>'+
            '</div>'+
            '<div class="sidebar_item_body clearfix" id="mwtools_main">'+
                '<form name="mwtform" onsubmit="return false">'+
                '<table>'+
                    '<tr>'+
                      '<td>Show in News Feed?</td>'+
                      '<td><input type="checkbox" name="show" '+show+'/></td>'+
                    '</tr>'+
                    '<tr>'+
                      '<td>Add to list:</td>'+
                      '<td><input type="text" name="list" value="'+list+'" size="10"/></td>'+
                    '</tr>'+
                    '<tr>'+
                      '<td>Max confirms:</td>'+
                      '<td><input type="text" name="max" value="'+max+'" size="10"/></td>'+
                    '</tr>'+
                    '<tr>'+
                      '<td>Seconds between:</td>'+
                      '<td><input type="text" name="wait" value="'+wait+'" size="10"/></td>'+
                    '</tr>'+
                    '<tr>'+
                      '<td></td>'+
                      '<td><input type="button" name="start" id="start" value="Start" class="inputbutton"/></td>'+
                    '</tr>'+
                '</table>'+
                '</form>'+
            '</div>';
        window.scroll(0,0);
        function createCookie(name,value) {
            // expire one month from now
            var expires = new Date();
            expires.setDate(expires.getDate()+30);
            document.cookie = name+"="+value+";expires="+expires.toGMTString()+"; path=/";
        }
        function readCookie(name) {
            var c, i,
                nameEQ = name + "=",
                ca = document.cookie.split(';');
            for(i=0;i < ca.length;i++) {
                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;
        }
        function log(line) {
            var log_p=document.createElement('p');
            log_p.innerHTML=line;
            $("mwtools_main").appendChild(log_p);
            window.scroll(0,0);
        }
        function event(evntname, obj) {
            var evt = document.createEvent("MouseEvents");
            evt.initMouseEvent(evntname, true, true, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
            obj.dispatchEvent(evt);
        }
        function setList(max,list) {
            log("Setting friend list to '"+list+"'...");
            var request = document.evaluate( "//span[contains(text(),'Add to list')]", document, null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null ),
                friendlist,
                friendlistfound,
                i, j;
            if (request.snapshotLength>0) {
                for (i=0; i<request.snapshotLength; i++) {
                    if (i>=max) break;
                    event('mousedown', request.snapshotItem(i));
                    friendlist = document.evaluate( "//a[@class='UISelectList_Label']", document, null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null );
                    if (friendlist.snapshotLength>0) {
                        friendlistfound=false;
                        for (j=0; j<friendlist.snapshotLength; j++) {
                            if (friendlist.snapshotItem(j).innerHTML.toLowerCase().indexOf(list.toLowerCase()) != -1) {
                                event('mouseup',friendlist.snapshotItem(j));
                                friendlistfound=true;
                                break;
                            }
                        }
                        if (!friendlistfound) {
                            if (confirm("Warning: You have no friends list that contains the word '"+list+"'.\nWould you like to skip adding new people to a friends list?")) {
                                break;
                            } else {
                                log("Canceling ConfirmAll because no '"+list+"' friend list found.");
                                return false;
                            }
                        }
                    } else {
                        if (confirm("Warning: You have no friends lists.  This means you can't easily filter your friends into different categories.  We recommend having a 'Mafia' friend list to add Mafia people to.\nWould you like to skip adding new people to a friends list?")) {
                            break;
                        } else {
                            log("Canceling ConfirmAll because no friend lists exist.");
                            return false;
                        }
                    }
                }
            } else {
                log("Warning: Could not find 'Add to list' button.  This can happen if you have already selected a friend list.");
            }
            return true;
        }
        function unShowInFeed(max) {
            log('Unchecking "Show in News Feed" checkboxes...');
            var i, checkboxes=document.getElementsByClassName("inputcheckbox");
            for (i=0; i<checkboxes.length && i<max; i++) {
                if (i>=max) break;
                if (checkboxes[i].checked)
                    if (checkboxes[i].id.indexOf("news_feed") != -1)
                        checkboxes[i].click();
            }
        }
        function confirm(max,wait) {
            log("Clicking Confirm buttons...");
            var request = document.evaluate( "//div[@id='friend_connect']//input[@class='inputbutton' and @value='Confirm']", document, null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null ),
                i=0,
                //add_url = 'http://apps.facebook.com/inthemafia/remote/html_server.php?xw_controller=friendbar&xw_action=send_add&fid=',

                timer = setInterval( function() {
                    if (( request.snapshotItem(i) == null) || (i>=max)) {
                        clearInterval(timer);
                        log("All done. "+i+" friend request"+(i==1?"":"s")+" confirmed.");
                    }
                    else {
                        //id=/friend_connect[^0-9]*([0-9]*)/.exec(request.snapshotItem(i).onclick);
                        request.snapshotItem(i).click();
                    }
                    i++;
                }, wait*1000);
        }
        $("start").onclick=function(e) {
            var retval = true;
            wait = document.mwtform.wait.value; createCookie("mwtca_wait",wait);
            max  = document.mwtform.max.value;  createCookie("mwtca_max" ,max);
            list = document.mwtform.list.value; createCookie("mwtca_list",list);
            if (document.mwtform.show.checked)
                show = "checked";
            else
                show = "";
            createCookie("mwtca_show",show);
            $("mwtools_main").innerHTML="";
            if (list != "")
                retval = setList(max,list);
            if (retval) {
                if (show == "")
                    unShowInFeed(max);
                confirm(max,wait);
            }
        }
        if (!content) {
            alert("Cannot find where to attach configuration box.  Attempting to run with defaults");
            $("start").onclick();
        }
})();
