/* Changes:
    1.13    Fix friendarray count errors when non-mafia friends are excluded
            Fix for a 32 bit uid error
    1.12    Recombined DoJobs and DoJobsG
            Gave user-selectable option to use user inputted list
            Implemented compatibility with firefox 2.0
            Pulled some functionality out and put it in toolkit.js
            Added repeat option to do jobs over and over.
    1.08    Do jobs in cuba
            Grab player IDs from javascript
            Grab names from javascript (only available on gifting page)
    1.07    Minor changes for version control, etc.
    1.06    Added check to see if you're helping yourself
            Added new version check
    1.05    Added bonus item reporting
            Fix for non-friend response wording change
    1.04    Reduced the number of log lines to 50 (plus any successful
            assists above the 50 mark).
    1.03    Added a pause button and made it so pressing Cancel on the inputs
            aborts things without changing anything
*/
javascript:(//)
    function() {
        var version='DoJobs 1.13',
            i=0, m,
            num,
            xmlHTTP,
            last_url=null,
            apps_mw='http://apps.facebook.com/inthemafia/remote/html_server.php?ajax=1&skip_interstitial=1&xw_controller=',
            mw_url=apps_mw+'stats&xw_action=view&user=',
            xp_title=null,
            do_in_ny=true,
            friends_helped=0,
            friends=[],
            savedfriends=[],
            friendarray=[],
            log_keep=/(Helped|Found)/,
            first=true,
            note="",
            wait,
            skip,
            redo,
            log,
            list,
            mwtools_div=$('mwtools'),
            running_html =
                '<style type="text/css">'+
                    '.messages img{margin:0 3px}'+
                    '#pl{display:none}'+
                '</style>'+
                '<table class="messages">'+
                    '<tr>'+
                        '<td width="20%"><a href="http://vern.com/mwtools/">Vern\'s MW Tools</a></td>'+
                        '<td class="title">'+version+'</td>'+
                        '<td style="text-align:right">'+
                            '<a href="#" id="pa"><img src="http://vern.com/mwtools/pa.gif" alt="" title="Pause" width="14" height="14"></a>'+
                            '<a href="#" id="pl"><img src="http://vern.com/mwtools/pl.gif" alt="" title="Play" width="14" height="14"></a>'+
                            '<a href="#" id="cl"><img src="http://vern.com/mwtools/cl.gif" alt="" title="Close" width="14" height="14"></a>'+
                            '<form name="mwtform">'+
                                '<input type="hidden" name="go" id="go" value="1">'+
                            '</form>'+
                        '<td>'+
                    '</tr>'+
                    '<tr>'+
                        '<td>Friends helped:</td>'+
                        '<td id="friends_helped"></td>'+
                    '</tr>'+
                    '<tr>'+
                        '<td>Experience gained:</td>'+
                        '<td id="xp_gained"></td>'+
                    '</tr>'+
                    '<tr>'+
                        '<td>Money gained:</td>'+
                        '<td id="cash_gained"></td>'+
                    '</tr>'+
                    '<tr>'+
                        '<td>Status:</td>'+
                        '<td id="status" colspan="2"></td>'+
                    '</tr>'+
                    '<tr>'+
                        '<td valign="top">Log:</td>'+
                        '<td id="log" colspan="2"></td>'+
                    '</tr>'+
                '</table>',
            config_html;
        wait = MWT.readCookie('mwtdj_wait');
        skip = MWT.readCookie('mwtdj_skip');
        redo = MWT.readCookie('mwtdj_redo');
        log  = MWT.readCookie('mwtdj_log');
        list = MWT.readCookie('mwtdj_list');
        if (wait) wait=wait.replace(/[^0-9]/g,'');
        if (skip) skip=skip.replace(/[^0-9]/g,'');
        if (log)  log = log.replace(/[^0-9]/g,'');
        if (list) list=list.replace(/[^0-9]/g,'');
        if ((wait == null) || (wait.length == 0)) wait = 1;
        if ((skip == null) || (skip.length == 0)) skip = 0;
        if ((redo == null) || (redo.length == 0)) redo = "";
        if ((log  == null) || (log.length  == 0)) log  = 50;
        if ((list == null) || (list.length == 0)) list = 0;
        config_html =
            '<style type="text/css">'+
                '.messages img{margin:0 3px}'+
                '.instructions{color:#999}'+
            '</style>'+
            '<form name="mwtform">'+
                '<input type="hidden" name="go" id="go" value="1">'+
                '<table class="messages">'+
                    '<tr>'+
                        '<td colspan="3" class="title" width="66%">'+version+' Configuration</td>'+
                        '<td style="text-align:right;font-size:0.8em">'+
                            '<a href="http://vern.com/mwtools/">Vern\'s MW Tools</a>'+
                            '<a href="#" id="cl"><img src="http://vern.com/mwtools/cl.gif" title="Close" width="14" height="14"></a>'+
                        '</td>'+
                    '</tr>'+
                    '<tr>'+
                        '<td width="12%">Wait: </td>'+
                        '<td width="10%">'+
                            '<input type="text" name="wait" id="wait" size="6" value="'+wait+'">'+
                        '</td>'+
                        '<td colspan="2"> The delay between requests in seconds.</td>'+
                    '</tr>'+
                    '<tr>'+
                        '<td>Skip: </td>'+
                        '<td>'+
                            '<input type="text" name="skip" id="skip" size="6" value="'+skip+'">'+
                        '</td>'+
                        '<td colspan="2"> How many mafia friends to skip before checking.</td>'+
                    '</tr>'+
                    '<tr>'+
                        '<td>Log: </td>'+
                        '<td>'+
                            '<input type="text" name="log" id="log" size="6" value="'+log+'">'+
                        '</td>'+
                        '<td colspan="2"> Length of log before truncating (0 for infinite).</td>'+
                    '</tr>'+
                    '<tr>'+
                        '<td>List: </td>'+
                        '<td>'+
                            '<select name="list" id="list">'+
                                '<option value="0"'+(list==0?" selected":"")+'>Internal List</option>'+
                                '<option value="1"'+(list==1?" selected":"")+'>Manual List</option>'+
                            '</select>'+
                        '</td>'+
                        '<td colspan="2"> Select which source to use to find your list of mafia.</td>'+
                    '</tr>'+
                    '<tr>'+
                        '<td>Restart: </td>'+
                        '<td>'+
                            '<input type="checkbox" name="redo" id="redo" '+redo+'/>'+
                        '</td>'+
                        '<td colspan="2"> Restart processing at the start when we reach the end.</td>'+
                    '</tr>'+
                    '<tr>'+
                        '<td></td>'+
                        '<td>'+
                            '<a class="sexy_button" id="start">Start</a>'+
                        '</td>'+
                    '</tr>'+
                    '<tr>'+
                        '<td colspan="4" id="note"></td>'+
                    '</tr>'+
                    '<tr id="manual_list">'+
                        '<td>Friend List:</td>'+
                        '<td colspan="3"><textarea name="friendlist" id="friendlist" class="instructions" rows="25" cols="50">'+
                            'Enter in this box a list of your mafia.\n'+
                            'Enter an ID and (optional) Name, one per line.\n'+
                            'Lines that do not begin with a number will be discarded.\n'+
                            '\n'+
                            'Examples:\n'+
                            '2342442345,Bob Dobolina\n'+
                            '1478921278 Joe Cool\n'+
                            '7898798343\n'+
                        '</textarea></td>'+
                    '</tr>'+
                '</table>'+
            '</form>';


        mwtools_div.innerHTML=config_html;
        $("cl").onclick=function(e) { // close
            $("app10979261223_content_row").removeChild($("mwtools"));
            return false;
        }
        $("list").onchange=function(e) {
            if ($("list").value == 0)
                $("manual_list").style.display = 'none';
            else
                $("manual_list").style.display = 'table-row';
        }
        $("list").onchange();
        $("friendlist").onfocus=function(e) {
            $("friendlist").value="";
            $("friendlist").style.color="#000";
            $("friendlist").onfocus=null;
        }
        $("start").onclick=function(e) {
            wait = document.mwtform.wait.value; MWT.createCookie("mwtdj_wait",wait);
            skip = document.mwtform.skip.value; MWT.createCookie("mwtdj_skip",skip);
            log  = document.mwtform.log.value;  MWT.createCookie("mwtdj_log", log);
            list = document.mwtform.list.value; MWT.createCookie("mwtdj_list",list);
            if (document.mwtform.redo.checked)
                redo = "checked";
            else
                redo = "";
            MWT.createCookie("mwtdj_redo",redo);
            // load manually entered list, if requested
            if (list == 1) {
                friends=[];
                friendarray=document.mwtform.friendlist.value.split("\n");
                for (i=0; i<friendarray.length; i++) {
                    if (m=/^([0-9]+)[,\s]*(.*)$/.exec(friendarray[i])) {
                        friends[i] = {'id':m[1]};
                        if (m[2])
                            friends[i].name = m[2];
                    }
                }
                delete friendarray;
                // clear note out of log, since it's not relevant
                MWT.logs = [];
            }
            // Replace config page with running page
            mwtools_div.innerHTML=running_html;
            $("pl").style.display = 'none';
            $("cl").onclick=function(e) { // close
                delete xmlHTTP['onreadystatechange'];
                $("app10979261223_content_row").removeChild($("mwtools"));
                return false;
            }
            $("pa").onclick=function(e) { // pause
                document.mwtform.go.value = 0;
                $("pa").style.display = 'none';
                $("pl").style.display = 'inline';
                return false;
            }
            $("pl").onclick=function(e) { // play
                document.mwtform.go.value = 1;
                $("pl").style.display = 'none';
                $("pa").style.display = 'inline';
                MWT.status('Resuming: '+MWT.resume_msg);
                MWT.request(xmlHTTP,state_change,last_url);
                return false;
            }
            if (redo != "")
                savedfriends = friends;
            MWT.log('Found '+friends.length+' mafia friends.');
            if (skip > 0) {
                MWT.log('Skipping '+skip+' friends.');
                friends=friends.slice(skip);
            }
            i=skip;
            request_next();
            return false;
        }
        function extra_status() {
            $('friends_helped').innerHTML=friends_helped;
        }
        function mwlink(s) {
            var name = s;
            if (!name && friends[0]) {
                if (friends[0].name)
                    name = friends[0].name;
                else
                    name = friends[0].id;
            }
            if ((!name) || (friends.length<=0)) {
                return "unknown player (friends left:"+friends.length+")";
            }
            return'<a href="'+mw_url+friends[0].id+'">'+name+'</a>';
        }
        function help_url(city) {
            return apps_mw+'job&xw_action=give_help&target_id='+friends[0].id+'&job_city='+city;
        }
        function in_city() {
            return " in "+(do_in_ny?"New York":"Cuba");
        }
        function outi(i) {
            MWT.createCookie("mwtdj_skip",i);
            return'<span class="more_in">'+i+'</span> ';
        }
        function request_next() {
            function f() {
                MWT.status('Helping '+mwlink()+in_city()+'...',extra_status);
                last_url=MWT.request(xmlHTTP,state_change,help_url(do_in_ny?1:2));
            }
            if(friends.length>0) {
                if(first || wait == 0) {
                    first=false;
                    f();
                } else {
                    if ((!friends[0]) || (!friends[0].id)) {
                        MWT.log(outi(i)+'Skipping '+mwlink()+' (missing ID).');
                        do_in_ny=true;
                        friends=friends.slice(1);
                        i++;
                        request_next();
                    } else {
                        MWT.pausing(wait,f);
                    }
                }
            } else {
                if (redo == "") {
                    MWT.status('All done',extra_status);
                    MWT.log('');
                } else {
                    MWT.log('Starting again at beginning.');
                    i=0;
                    friends=savedfriends;
                    request_next();
                }
            }
        }
        function state_change() {
            if(xmlHTTP.readyState==4) {
                if(xmlHTTP.status==200) {
                    var s="",
                        m=[],
                        xp, ca,
                        xp_now, xp_next, xp_need,
                        bonus_item="",
                        count, j, jl, current;
                    s=xmlHTTP.responseText;
                    delete xmlHTTP['onreadystatechange'];
                    // chop off the Facebook stuff from the beginning
                    if (/UIStandardFrame_Content/.test(s))
                        s=s.substr(s.indexOf("UIStandardFrame_Content"));
                    /*var testwin = window.open("","testwin","height=500,width=800");
                    testwin.document.write("<html><body><p>Test Output:</p><pre>");
                    testwin.document.write(s);
                    testwin.document.write("</pre></body></html>");
                    testwin.document.close();*/
                    // upate some header items
                    if (m=/app10979261223_user_cash[^>]*>([^<]*)</m.exec(s)) {
                        ca=$('app10979261223_user_cash_nyc');
                        if(ca) ca.innerHTML=m[1];
                        ca=$('app10979261223_user_cash_cuba');
                        if(ca) ca.innerHTML=m[1];
                    }
                    if(m=/app10979261223_user_experience[^>]*>([^<]*)</m.exec(s)) {
                        xp_now=m[1];
                        $('app10979261223_user_experience').innerHTML=xp_now;
                    }
                    if(m=/app10979261223_exp_for_next_level[^>]*>([^<]*)</m.exec(s)) {
                        xp_next=m[1];
                        $('app10979261223_exp_for_next_level').innerHTML=xp_next;
                        xp_need=parseInt(xp_next) - parseInt(xp_now);
                        // backwards compatibility for getElementsByClassName
                        if (!xp_title) {
                            if (document.getElementsByClassName) {
                                xp_title=document.getElementsByClassName('stat_title')[5];
                            } else {
                                count=0;
                                for (j=0, jl=document.getElementsByTagName('span').length; j<jl; j++) {
                                    current = document.getElementsByTagName('span')[j];
                                    if (/stat_title/.test(current.className)) {
                                        count++;
                                    }
                                    if (count>5) {
                                        xp_title=current;
                                        break;
                                    }
                                }
                            }
                        }
                        xp_title.innerHTML='Exp (Need: '+xp_need+')';
                    }
                    if(m=/<div[^>]*app10979261223_level_bar[^>]* width:\s*([0-9%]*)/.exec(s))
                        $('app10979261223_level_bar').style.width=m[1];
                    // now check the response messages
                    if(m=/Special Bonus:.*?You gained ([^<]*).<span/.exec(s)) {
                        bonus_item="<br/>"+outi(i)+" -- Bonus: "+m[1];
                    }
                    if(m=/You received (.*?) experience point.*? and (.*?) for helping (.*?) complete the job/.exec(s)) {
                        friends_helped++;
                        xp=m[1].replace(/[^0-9]/g,'');
                        MWT.xp_gained+=parseInt(xp);
                        ca=m[2].replace(/[^0-9]/g,'');
                        if(/C\$/.test(m[2])) {
                            dollar_sign="C$";
                            MWT.cuban_cash_gained+=parseInt(ca);
                        } else {
                            dollar_sign="$";
                            MWT.cash_gained+=parseInt(ca);
                        }
                        MWT.log(outi(i)+'Helped '+mwlink(m[3])+in_city()+' and received <span class="good">'+xp+' xp</span> and <strong class="money">'+dollar_sign+MWT.commas(ca)+'</strong>.'+bonus_item,log,log_keep);
                    } else if(m=/You have already helped (.+?) on the/.exec(s)) {
                        MWT.log(outi(i)+'Already helped '+mwlink(m[1])+in_city()+'.',log,log_keep);
                    } else if(m=/You need to be friends with (.+?) to provide help/.exec(s)) {
                        MWT.log(outi(i)+mwlink(m[1])+' is not your friend.',log,log_keep);
                        do_in_ny=false;
                    } else if(/You cannot help people who are not your friends/.test(s)) {
                        MWT.log(outi(i)+mwlink()+' is not your friend.',log,log_keep);
                        do_in_ny=false;
                    } else if(/Only your Mafia can provide assistance/.test(s)) {
                        MWT.log(outi(i)+mwlink()+' is apparently not in your Mafia',log,log_keep);
                        do_in_ny=false;
                    } else if (/You are too late/.test(s)) {
                        //MWT.log(outi(i)+'FOO: '+(friends[0].name?friends[0].name:"no name")+':'+(friends[0].id?friends[0].id:"no id")+'.',log,log_keep);
                        MWT.log(outi(i)+'No current job for '+mwlink()+in_city()+'.',log,log_keep);
                    } else if (/Error while loading page/.test(s)) {
                        MWT.pausing(20,'Mafia Wars is having problems',
                            function(){MWT.request(xmlHTTP,state_change,last_url);});
                        return;
                    } else if (!/class="messages"/.test(s)) {
                        MWT.log(outi(i)+mwlink()+' does not play Mafia Wars',log,log_keep);
                        do_in_ny=false;
                    } else {
                        MWT.retry(9,'Unknown response (<a href="'+help_url(do_in_ny?1:2)+'">help url</a>)',xmlHTTP,state_change,last_url);
                        return;
                    }
                    m=[];
                    s="";
                    MWT.retries=0;
                    if (do_in_ny) {
                        do_in_ny=false;
                    } else {
                        do_in_ny=true;
                        friends=friends.slice(1);
                        i++;
                    }
                    request_next();
                } else {
                    MWT.retry(9,'Problem retrieving data (<a href="'+last_url+'">url</a>)',xmlHTTP,state_change,last_url);
                    return;
                }
            }
        }
        xmlHTTP=MWT.get_xmlHTTP();
        xmlHTTP.statechange=state_change;
        if(!xmlHTTP) {
            alert("Your browser does not support XMLHTTP.");
            return;
        }

        // Let's load up our mafia friends
        friendarray = FBIntern.CacheUtil.CacheUtilServer.userfriends;
        if (typeof(a10979261223_groups_levels) == "undefined"){
            donames=false;
            note=version+' could not find any names for the Internal Mafia list. This is nothing to be alarmed about but just be aware that the people you cannot help will come up as numbers instead of names.';
            $("note").innerHTML=note;
            MWT.log(note);
        } else {
            donames=true;
        }
        if (donames) {
            num = 0;
            for (i=0; i<friendarray.length; i++) {
                if (friendarray[i] in a10979261223_groups_levels)
                    friends[num++] = {'id':friendarray[i],'name':a10979261223_groups_levels[friendarray[i]]};
            }
        }
        if (friends.length == 0)
            for (i=0; i<friendarray.length; i++)
                friends[i] = {'id':friendarray[i]};
        friends.sort(function(a,b) { return ((a.name < b.name) ? -1 : ((a.name > b.name) ? 1 : (a.id < b.id ? -1 : (a.id > b.id ? 1 : 0)))) });
        // if skip is at or beyond the end, start back at zero
        if (skip >= friends.length -1)
            document.mwtform.skip.value=0;
    }()
);
// vim: set sw=4 ts=4 et ai:
