
$j=jQuery.noConflict();

var uuid = '';
var mit150_maxvotes = 10;
var mit150_ballot = {
    maxvotes: mit150_maxvotes,
    nvotes: 0,
    items: {},
    voted: false
};

function reset_all() {
    set_actionbox("vote");
    $j.cookie("150voted", null);
    $j.cookie("150vote", null);
    initballot('');
    setupballot();
}

function set_actionbox(state) {
    if (state == "voted") {
        $j("#ballotactionbox").slideUp("slow");
        $j("#ballotvotedbox").slideDown("slow");
        $j(".ballotlist-box").unbind(".vote");
        $j("#ballot-reset").hide();
        $j("#ballot-vote").hide();
        mit150_ballot.voted = true;
        tiptext('');
    } else if (state == "vote") {
        $j("#ballot-reset").show();
        $j("#ballot-vote").show();
        $j("#ballotactionbox").show();
        $j("#ballotvotedbox").hide();
        mit150_ballot.voted = false;
    }
}

// Sends a ballot to the server
function record_callback() {
    var vote = "vote&uuid=" + uuid + "&votes=";
    var i = 1;
    var item;
    $j.cookie("uuid", uuid);
    for (item in mit150_ballot.items) {
        vote += item;
        if (i++ < mit150_ballot.nvotes) {
            vote += ',';
        }
    }

    $j.get("/150/newapi", vote, function(data) {
        set_actionbox("voted");
        $j.cookie("150voted", $j.cookie("150vote"), {expires: 10000});
        votehelper('');
    });
}

// Can be used to re-initialize
function initballot(s) {
    mit150_ballot.maxvotes = mit150_maxvotes;
    mit150_ballot.nvotes = 0;
    mit150_ballot.items = {};

    // Clear out all the existing votes
    $j.cookie("150vote", null);
    unvote_housekeeping($j(".ballotlist-box"));
    votehelper(s);

}

// Constructs the contents of the tooltip box.
// helpline contents are put into a tag with id=helpline for additional styling
function tiptext(helpline) {
    var t = "";
    var item;
    var tmp;
    var i = 0;

    if(mit150_ballot.voted) {
        t += "You voted for";
    } else {
        t += '<p id="votesleft">You have ' + (mit150_maxvotes - mit150_ballot.nvotes);
        if (mit150_maxvotes - mit150_ballot.nvotes === 1) {
            t += ' vote left</p>';
        } else {
            t += ' votes left</p>';
        }
    }

    if (helpline.length > 0) {
        t += '<p id="helpline">' + helpline + '</p>';
    } else {
        if (mit150_ballot.nvotes === 0) {
            t += '<p id="helpline">' + 'Click the box to vote for this item' + '</p>';
        }
    }

    if (mit150_ballot.nvotes > 0) {
        tmp = new Array(mit150_ballot.nvotes);
        for (item in mit150_ballot.items) {
            tmp[i] = mit150_ballot.items[item];
            i += 1;
        }
        tmp.sort();

        if(mit150_ballot.voted === false) {
            t += '<p id="voteline">' + 'Your votes so far:' + '</p>';
        }

        t += "<ul>";
        for (var j = 0; j < i; j++) {
            t += "<li>" + tmp[j] + "</li>";
        }
        t += "</ul>";
    }
    return t;
}

// Deals with things that are common to vote/unvote.
function votehelper(helpline) {
    $j.cookie("150vote", JSON.stringify(mit150_ballot));
    $j('#tooltip').children(".body").html(tiptext(helpline));
}

function vote_housekeeping(item) {
    // Turn on the record button
    $j("#ballot-vote").unbind("click");
    $j("#ballot-vote").bind("click", record_callback);

    item.css("background", "#ec008c url(/150/wp-content/themes/mit150b/img/x.png) no-repeat center");
    item.unbind(".vote");
    item.bind("click.vote", unvote_callback);
}

function unvote_housekeeping(item) {
    if (mit150_ballot.nvotes == 0) {
        // Turn off the record button
        $j("#ballot-vote").unbind("click");
    }
    item.css("background", "none transparent");
    item.unbind(".vote");
    item.bind("click.vote", vote_callback);
}

// Callback
// "Punches" the ballot, adds that item to the list of votes,
// sets up the ability to unvote, and makes sure you don't vote
// for too many items
function vote_callback(e) {
    if (mit150_ballot.nvotes < mit150_maxvotes) {
        vote_housekeeping($j(this));
        mit150_ballot.nvotes = mit150_ballot.nvotes + 1;
        mit150_ballot.items[$j(this).attr("id")] = $j(this).parent().find(".title").text();
        votehelper('');
    } else {
        votehelper('You have already used all of your votes');
    }
}

function item_title(id) {
    return($j("#" + id).parent().find(".title").text());
}
// Callback
// Undoes a single vote
function unvote_callback(e) {
    unvote_housekeeping($j(this));
    if(mit150_ballot.nvotes > 0) {
        delete mit150_ballot.items[$j(this).attr("id")];
        mit150_ballot.nvotes = mit150_ballot.nvotes - 1;
        votehelper('');
    }
}

// Set a single item into the "voted" state.
function setvoted(id) {
    var box = "#" + id;
    vote_housekeeping($j(box));
}

// Inits the entire page - called at page load time
function setupballot(myuuid) {
    var item;

    uuid = myuuid;

    // Is the permanent 150voted cookie set? Then set the session cookie
    // using the info from the permanent one.
    if ($j.cookie("150voted") != null) {
        $j.cookie("150vote", $j.cookie("150voted"));
    }

    // If there's a cookie full of votes already, use that.
    // This lets people go to a different page and come back
    if ($j.cookie("150vote") && $j.cookie("150vote").length > 0) {
        mit150_ballot = JSON.parse($j.cookie("150vote"));
        for (item in mit150_ballot.items) {
            setvoted(item);
        }
    } else {
        initballot('');
    }

    // $j("#ballot").hide();
    // setTimeout('$j("#ballot").show("slow")', 5000);

    // If the voted cookie is set, then don't let people vote again
    if ($j.cookie("150voted")) {
        $j("#ballotactionbox").hide();
        $j("#ballotvotedbox").show();
        $j(".ballotlist-box").unbind(".vote");
        mit150_ballot.voted = true;
    } else {
        // $j("#ballotcontrols").hide();
        // setTimeout('$j("#ballotcontrols").show("slow")', 5000);
    }

    votehelper('');
    $j(".ballotlist-box").tooltip({
        delay: 0,
        bodyHandler: function() {
            return tiptext('');
        }
    });
    $j(".ballotlist-box").unbind("click"); // Undoes the tooltip's click binding
        
    $j("#ballot-reset").tooltip({
        delay: 0,
        bodyHandler: function() {
            return tiptext('Click to erase all of your votes');
        }
    });
    $j("#ballot-reset").unbind("click"); // Undoes the tooltip's click binding

    $j("#ballotvotedbox").tooltip({
        delay: 0,
        bodyHandler: function() {
            return tiptext('');
        }
    });
    $j("#ballotvotedbox").unbind("click"); // Undoes the tooltip's click binding
    //        $j("#ballotvotedbox").bind("onmouseover", tiptext('')); // Undoes the tooltip's click binding
    
    $j("#ballot-vote").tooltip({
        delay: 0,
        bodyHandler: function() {
            var t = "";
            if (mit150_ballot.nvotes == 0) {
                t += "You have not voted for anything yet!";
            } else {
                t += "Click to record your vote.";
            }
            if (mit150_ballot.nvotes < mit150_maxvotes) {
                t += "<br />Note: You can still add " +
                    (mit150_maxvotes-mit150_ballot.nvotes) + " items to your ballot!<br />" +
                    "You may only vote once - only click this button when<br />" +
                    " you are done voting.";
            }
            return tiptext(t);
        }
    });
    $j("#ballot-vote").unbind("click"); // Undoes the tooltip's click binding
    
    // FOR DEBUGGING ONLY!!!
//    $j("#reset-all").bind("click", reset_all);

    if(mit150_ballot.voted === false) {
        $j(".ballotlist-box").bind("click.vote", vote_callback);
        $j("#ballot-reset").bind("click", function() {
            initballot('Your ballot has been reset');
        });
    }
}

function setupresults() {

}

function fix_blogexcerpt_images () {
    var max_width = 265;
    $j(".blogexcerpt").children("img").each(function(i) {
        var width = $j(this).attr("width");
        if (width > max_width) {
            $j(this).attr("width", max_width);
            $j(this).attr("height", (max_width/width) * $j(this).attr("height"));
        }
    });
}
