/* Changes:
    1.11    Added a warning
    1.10    Do jobs in Cuba as well
    1.09    Added language independant check for Next link on friend search
    1.08    Added pause configuration between friend searches
    1.07    Grab players from the "Friends using Mafia Wars" pages
            We now update the xp and money in the MW header
    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='DoJobsFS 1.11',
            i=0, res,
            xmlHTTP,
            last_url=null,
            resume_msg="",
            retries=0,
            fs_retries=0,
            apps_mw='http://apps.facebook.com/inthemafia/remote/html_server.php?ajax=1&skip_interstitial=1&xw_controller=',
            gifting_url=apps_mw+'gift&xw_action=view',
            mw_url=apps_mw+'stats&xw_action=view&user=',
            friend_search='http://apps.facebook.com/s.php?k=100004000&app_id=10979261223&s=',
            searching=true,
            exp_gained=0,
            cash_gained=0,
            cuban_cash_gained=0,
            do_in_ny=true,
            friends_found=0,
            friends_helped=0,
            friends=[],
            log=[],
            extralog=[],
            first=true,
            wait=-1,
            fs_wait=-1,
            skip=-1,
            content=$('app10979261223_content_row'),
            mafia_size=$("app10979261223_user_group_size").parentNode.parentNode,
            mwtools_div=$('mwtools'),
            running_html =
                '<style type="text/css">'+
                    '.messages img{margin:0 3px}'+
                    '#pl{display:none}'+
                    '#friend_search{margin-left:20px}'+
                '</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" title="Pause" width="14" height="14"></a>'+
                            '<a href="#" id="pl"><img src="http://vern.com/mwtools/pl.gif" title="Play" width="14" height="14"></a>'+
                            '<a href="#" id="cl"><img src="http://vern.com/mwtools/cl.gif" 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 found:</td>'+
                        '<td><span id="friends_found"></span><span id="friend_search"></span></td>'+
                    '</tr>'+
                    '<tr>'+
                        '<td>Friends left:</td>'+
                        '<td id="friends_left"></td>'+
                    '</tr>'+
                    '<tr>'+
                        '<td>Friends helped:</td>'+
                        '<td id="friends_helped"></td>'+
                    '</tr>'+
                    '<tr>'+
                        '<td>Experience gained:</td>'+
                        '<td id="exp_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,
            results=document.evaluate("//input[@name='recipients[]']",document,null,XPathResult.ORDERED_NODE_SNAPSHOT_TYPE,null);
        wait = readCookie('mwtdj_wait'); if (!wait) wait = 1;
        skip = readCookie('mwtdj_skip'); if (!skip) skip = 0;
        fs_wait = readCookie('mwtdj_fswait'); if (!fs_wait) fs_wait = 60;
        config_html =
            '<style type="text/css">'+
                '.messages img{margin:0 3px}'+
            '</style>'+
            '<form name="mwtform">'+
                '<input type="hidden" name="go" id="go" value="1">'+
                '<table class="messages">'+
                    '<tr>'+
                        '<td colspan="3" class="title">'+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>Wait: </td>'+
                        '<td>'+
                            '<input type="text" name="wait" id="wait" value="'+wait+'">'+
                        '</td>'+
                        '<td colspan="2">The delay between requests in seconds.</td>'+
                    '</tr>'+
                    '<tr>'+
                        '<td>Search Wait: </td>'+
                        '<td>'+
                            '<input type="text" name="fs_wait" id="fs_wait" value="'+fs_wait+'">'+
                        '</td>'+
                        '<td colspan="2">The delay (seconds) between friend searches.</td>'+
                    '</tr>'+
                    '<tr>'+
                        '<td>Skip: </td>'+
                        '<td>'+
                            '<input type="text" name="skip" id="skip" value="'+skip+'">'+
                        '</td>'+
                        '<td colspan="2">How many mafia friends to skip before checking.</td>'+
                    '</tr>'+
                    '<tr>'+
                        '<td></td>'+
                        '<td>'+
                            '<a class="sexy_button" id="start">Start</a>'+
                        '</td>'+
                    '</tr>'+
                    '<tr>'+
                        '<td class="bad" colspan="4">'+
                            'WARNING: DoJobs uses friend searches from "'+
                            '<a href="http://apps.facebook.com/s.php?'+
                            'k=100004000&app_id=10979261223">Friends who '+
                            'use Mafia Wars</a>" to get your mafia list. '+
                            'Using Search Wait less than 60 (higher the '+
                            'better) could cause Facebook to give you '+
                            'a temporary friend search block.'+
                        '</td>'+
                    '</tr>'+
                '</table>'+
            '</form>';


        if (!mwtools_div) {
            mwtools_div=document.createElement('div');
            mwtools_div.setAttribute('id','mwtools');
            mwtools_div.innerHTML='<table class="messages"></table>';
            content.insertBefore(mwtools_div,content.firstChild);
        }
        mwtools_div.innerHTML=config_html;
        // fix the mafia count, just in case it line-wrapped
        if (mafia_size)
            mafia_size.innerHTML='<nobr>'+mafia_size.innerHTML.replace(/&nbsp;/g,'')+'</nobr>';
        function get_xmlHTTP() {
            if(window.XMLHttpRequest)
                return new XMLHttpRequest();
            if(window.ActiveXObject)
                return new ActiveXObject("Microsoft.XMLHTTP");
            return null;
        }
        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 request(url) {
            if (document.mwtform.go.value == 1) {
                xmlHTTP.onreadystatechange=state_change;
                xmlHTTP.open("GET",url,true);
                xmlHTTP.send(null);
            } else {
                resume_msg=$('status').innerHTML;
                status('Paused');
            }
            last_url=url;
        }
        function fs_request(url) {
            if (document.mwtform.go.value == 1) {
                fs_xmlHTTP.onreadystatechange=fs_state_change;
                fs_xmlHTTP.open("GET",url,true);
                fs_xmlHTTP.send(null);
            } else {
                fs_status((searching?"paused":""));
            }
            fs_last_url=url;
        }
        $("cl").onclick=function(e) { // close
            $("app10979261223_content_row").removeChild($("mwtools"));
            return false;
        }
        $("start").onclick=function(e) {
            wait = parseInt(document.mwtform.wait.value); createCookie("mwtdj_wait",wait);
            skip = parseInt(document.mwtform.skip.value); createCookie("mwtdj_skip",skip);
            fs_wait = parseInt(document.mwtform.fs_wait.value); createCookie("mwtdj_fswait",fs_wait);
            mwtools_div.innerHTML=running_html;
            $("pl").style.display = 'none';
            $("cl").onclick=function(e) { // close
                delete xmlHTTP['onreadystatechange'];
                delete fs_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';
                status('Resuming: '+resume_msg);
                request(last_url);
                fs_status((searching?"searching...":""));
                fs_request(fs_last_url);
                return false;
            }
            i=skip;
            friends_found=skip;
            fs_status("searching...");
            fs_request_next();
            request_next();
            return false;
        }
        function retry(s) {
            if(retries>9) {
                status(s+'; not retrying any more.');
                document.mwtform.go.value = 0;
            } else {
                function f(){
                    retries++;
                    msg(s+'; retry #'+retries+'...');
                    request(last_url);
                }
                setTimeout(f,3000);
            }
        }
        function fs_retry(s) {
            if(fs_retries>2) {
                msg(s+'; not retrying any more.');
                searching=false;
                fs_status("done (error)");
            } else {
                function f(){
                    fs_retries++;
                    msg(s+'; retry #'+fs_retries+'...');
                    fs_request(fs_last_url);
                }
                setTimeout(f,3000);
            }
        }
        function commas(s) {
            var d;
            while (d=/(\d+)(\d{3}.*)/.exec(s)) {
                s = d[1] + ',' + d[2];
            }
            return s;
        }
        function msg(line) {
            var set = friends_helped;
            $('friends_helped').innerHTML=set;
            set = exp_gained;
            $('exp_gained').innerHTML=set;
            if (cuban_cash_gained == 0) {
                set='$'+commas(cash_gained);
            } else {
                set='$'+commas(cash_gained)+' &nbsp; C$'+commas(cuban_cash_gained);
            }
            $('cash_gained').innerHTML=set;
            log.unshift(line)
            if (log.length>50) {
                line=log.pop();
                if (/(Helped|Found)/.test(line)) {
                    extralog.unshift(line);
                }
            }
            set=log.concat(extralog,"").join("<br/>");
            $("log").innerHTML=set;
            fs_status("");
        }
        function status(s) {
            $('status').innerHTML=s;
        }
        function fs_status(s) {
            $('friends_found').innerHTML=friends_found;
            $('friends_left').innerHTML=friends.length;
            if (s.length > 0)
                $('friend_search').innerHTML=s;
        }
        function mwlink(s) {
            return'<a href="'+mw_url+friends[0].id+'">'+s+'</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) {
            createCookie("mwtdj_skip",i);
            return'<span class="more_in">'+i+'</span> ';
        }
        function request_next() {
            function f() {
                status('Helping '+mwlink(friends[0].name)+in_city()+'...');
                request(help_url(do_in_ny?1:2));
            }
            if (friends.length == 0 && searching) {
                status("Waiting for more friends to be found.");
                setTimeout(request_next,5000);
                return;
            }
            if(friends.length>0) {
                if(first || wait == 0) {
                    first=false;
                    f();
                } else {
                    status('Waiting for '+wait+' seconds...');
                    setTimeout(f,wait*1000);
                }
            } else {
                status('All done');
                msg('');
            }
        }
        function fs_request_next() {
            if (friends.length == 0) {
                fs_request(friend_search+friends_found);
            } else {
                fs_status("wait "+fs_wait+" secs");
                setTimeout(function(){
                    fs_request(friend_search+friends_found)
                },fs_wait*1000);
            }
        }
        function state_change() {
            if(xmlHTTP.readyState==4) {
                if(xmlHTTP.status==200) {
                    var s="",
                        m=[],
                        xp, ca,
                        xpnow, xpnext, xpneed,
                        bonus_item="";
                    s=xmlHTTP.responseText;
                    delete xmlHTTP['onreadystatechange'];
                    // update 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)) {
                        xpnow=m[1];
                        $('app10979261223_user_experience').innerHTML=xpnow;
                    }
                    if(m=/app10979261223_exp_for_next_level[^>]*>([^<]*)</m.exec(s)) {
                        xpnext=m[1];
                        $('app10979261223_exp_for_next_level').innerHTML=xpnext;
                        xpneed=parseInt(xpnext) - parseInt(xpnow);
                        document.getElementsByClassName('stat_title')[5].innerHTML='Exp (Need: '+xpneed+')';
                    }
                    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,'');
                        exp_gained+=parseInt(xp);
                        ca=m[2].replace(/[^0-9]/g,'');
                        if(/C\$/.test(m[2])) {
                            dollar_sign="C$";
                            cuban_cash_gained+=parseInt(ca);
                        } else {
                            dollar_sign="$";
                            cash_gained+=parseInt(ca);
                        }
                        msg(outi(i)+'Helped '+mwlink(m[3])+in_city()+' and received <span class="good">'+xp+' xp</span> and <strong class="money">'+dollar_sign+commas(ca)+'</strong>.'+bonus_item);
                    } else if(m=/You have already helped (.+) on the/.exec(s)) {
                        msg(outi(i)+'Already helped '+mwlink(m[1])+in_city()+'.');
                    } else if(m=/You need to be friends with (.+) to provide help/.exec(s)) {
                        msg(outi(i)+mwlink(m[1])+' is not your friend.');
                        do_in_ny=false;
                    } else if(/You cannot help people who are not your friends/.test(s)) {
                        msg(outi(i)+mwlink(friends[0].name)+' is not your friend.');
                        do_in_ny=false;
                    } else if(/Only your Mafia can provide assistance/.test(s)) {
                        msg(outi(i)+mwlink(friends[0].name)+' is apparently not in your Mafia');
                        do_in_ny=false;
                    } else if (/You are too late/.test(s)) {
                        msg(outi(i)+'No current job for '+mwlink(friends[0].name)+in_city()+'.');
                    } else if (/Error while loading page/.test(s)) {
                        function f(){
                            request(last_url);
                        }
                        msg('Mafia Wars is having problems, pausing...');
                        setTimeout(f,20000);
                        return;
                    } else if (!/class="messages"/.test(s)) {
                        msg(outi(i)+mwlink(friends[0].name)+' does not play Mafia Wars');
                        do_in_ny=false;
                    } else {
                        retry('Unknown response (<a href="'+help_url(do_in_ny?1:2)+'">help url</a>)');
                        return;
                    }
                    m=[];
                    s="";
                    retries=0;
                    if (do_in_ny) {
                        do_in_ny=false;
                    } else {
                        do_in_ny=true;
                        friends=friends.slice(1);
                        i++;
                    }
                    request_next();
                } else {
                    retry('Problem retrieving data');
                    return;
                }
            }
        }
        function fs_state_change() {
            if(fs_xmlHTTP.readyState==4) {
                if(fs_xmlHTTP.status==200) {
                    delete fs_xmlHTTP['onreadystatechange'];
                    var s=fs_xmlHTTP.responseText,
                        m=[],
                        found = 0;
                    s.match(/dd class=.result_name.*?profile.php.id=[0-9]*.*?>.*?<\/a>/g).each(function(person) {//)
                        found++;
                        m=/id=([0-9]*).*?>(.*?)</.exec(person);
                        friends[friends.length]={'id':m[1],'name':m[2]};
                        friends_found++;
                        fs_status("searching...");
                    });
                    if (/class="disclaimer">.*?550.*?</.test(s)) {
                        searching=false;
                        fs_status(" ");
                        msg("Found last friends page, ending friend search.");
                        return;
                    }
                    var numbers=false,
                        nextlink=false,
                        previous="";
                    s.match(/class="pagerpro_a">(.*?)<\/a>/g).each(function(link) {//)
                        m=/>(.*?)<\/a>/.exec(link);
                        var num=(m[1].match(/^[0-9]+$/)?true:false);
                        if ((numbers) && (!num) && (!nextlink) && (previous!=m[1]))
                            nextlink=true;
                        if ((!nextlink) && (num))
                            numbers=true;
                        if ((!numbers) && (!num))
                            previous=m[1];
                    });
                    if (!nextlink) {
                        searching=false;
                        fs_status(" ");
                        msg("No Next link found, ending friend search.");
                        return;
                    }
                    if (found < 10) {
                        searching=false;
                        fs_status(" ");
                        msg("Less than 10 friends on the last friend page, ending friend search.");
                        return;
                    }
                    if (found == 0) {
                        fs_retry('Unknown response during friend search (<a href="'+fs_last_url+'">url</a>)');
                        return;
                    }
                    fs_retries=0;
                    fs_request_next();
                } else if(fs_xmlHTTP.status==302) {
                    msg("We appear to be at the end of the friends list, ending friend search.");
                    searching=false;
                    fs_status(" ");
                    return;
                } else {
                    fs_retry('Problem retrieving friend search data (<a href="'+fs_last_url+'">url</a>)');
                    return;
                }
            }
        }
        xmlHTTP=get_xmlHTTP();
        fs_xmlHTTP=get_xmlHTTP();
        if(!xmlHTTP) {
            alert("Your browser does not support XMLHTTP.");
            return;
        }
    }()
);
// vim: set sw=4 ts=4 et ai:
