// snapscores js library
// requires jquery 1.3.2

if (! ("console" in window) || ! ("firebug" in console)) {
    var names = ["log", "debug", "info", "warn", "error", "assert", "dir", "dirxml", "group"
                 , "groupEnd", "time", "timeEnd", "count", "trace", "profile", "profileEnd"];
    window.console = {};
    for (var i = 0; i <names.length; ++i) window.console[names[i]] = function() {};
}


var util = {
    reduce_text: function(text) {
        var re = /[\s\W]+/g;
        return text.replace(re, "_").toLowerCase();
    },
    url: function(url) {
        location.href = url;
    },
    flatten: function(obj) {
        return ($.isArray(obj)) ? obj[0] : obj;        
    }
};

var avatars = {
    _dict: {},
    add: function(uid, img) {
        img = util.flatten(img);
        this._dict[uid] = $(img).clone();
    },
    get: function(id) {
        return this._dict[id];
    },
    has: function(id) {
        return ! (this._dict[id] == undefined);
    }
};

var loadAvatars = function() {
    $("fb\\:profile-pic").each(function() {
      avatars.add($(this).attr("uid").toString(), $(this).find("img"));
    });
};

if (!Array.indexOf) {
        Array.prototype.indexOf = function(obj){
            for(var i=0; i<this.length; i++){
                if(this[i]==obj){
                    return i;
                }
            }
            return -1;
        };
    }
    
Array.max = function( array ){
    return Math.max.apply( Math, array );
};
Array.min = function( array ){
    return Math.min.apply( Math, array );
};

Boolean.parse = function(string) {
    switch(string.toLowerCase()) {
        case "true": case "yes": case "1": return true;
        case "false": case "no": case "0": case null: return false;
        default: return Boolean(string);
    }
};

var bool = Boolean.parse;

Date.prototype.toDateString = function () {
    return [this.getMonth() < 9 ? '0' + (this.getMonth() + 1) : this.getMonth() + 1, 
            this.getDate() < 10 ? '0' + this.getDate() : this.getDate(), 
            this.getFullYear()].join ('/');
    };

Date.prototype.addDays = function (n) {
    var d = new Date (this.getTime());
    d.setDate (d.getDate() + n);
    return d;
};

Date.prototype.getTimezone = function() {
    
    function isDST(date) {
        var 
            tmSummer = new Date(Date.UTC(2005, 6, 30, 0, 0, 0, 0)),
            so = -1 * tmSummer.getTimezoneOffset(),
            tmWinter = new Date(Date.UTC(2005, 12, 30, 0, 0, 0, 0)),
            wo = -1 * tmWinter.getTimezoneOffset(),
            o = -1 * date.getTimezoneOffset();
        return wo >= so ? wo === o : so === o;
    }

    var standards = {
        '-120':'GST',
        '-150':'NT',
        '-180':'BRT',
        '-210':'VET',
        '-240':'AST',
        '-300':'EST',
        '-360':'CST',
        '-420':'MST',
        '-480':'PST',
        '-510':'MIT',
        '-540':'AKST',
        '-60':'CVT',
        '-600':'CKT',
        '-720':'BIT',
        '0':'GMT',
        '120':'EET',
        '180':'MSK',
        '210':'IRST',
        '240':'AST',
        '270':'AFT',
        '300':'PKT',
        '330':'IST',
        '345':'NPT',
        '360':'BST',
        '390':'MST',
        '480':'CST',
        '540':'JST',
        '570':'ACST',
        '60':'CET',
        '600':'AEST',
        '630':'LHST',
        '660':'MAGT',
        '690':'NFT',
        '720':'FJT',
        '765':'CHAST',
        '780':'PHOT',
        '840':'LINT'
    };

    var daylights = {
        '-120':'UYST',
        '-180':'CLST',
        '-240':'EDT',
        '-300':'CDT',
        '-360':'MDT',
        '-420':'PDT',
        '-90':'NDT',
        '120':'CEST',
        '180':'EEST',
        '300':'AMST',
        '60':'BST',
        '630':'ACDT',
        '660':'AEDT'
    };
    
    var 
        map = isDST(this) ? daylights : standards,
        offset = -1 * this.getTimezoneOffset();
        
    return map[offset.toString()];
};

    
String.prototype.contains = function(substring) {
        return (this.indexOf(substring)!=-1);
    };
    
String.prototype.capitalize = function() {
    return this.charAt(0).toUpperCase() + this.substr(1);
};
    
String.prototype.toTitleCase = function() {
    return this.replace(/([\w&`'‘’"“.@:\/\{\(\[<>_]+-? *)/g, function(match, p1, index, title) {
        if (index > 0 && title.charAt(index - 2) !== ":" &&
            match.search(/^(a(nd?|s|t)?|b(ut|y)|en|for|i[fn]|o[fnr]|t(he|o)|vs?\.?|via)[ \-]/i) > -1)
            return match.toLowerCase();
        if (title.substring(index - 1, index + 1).search(/['"_{(\[]/) > -1)
            return match.charAt(0) + match.charAt(1).toUpperCase() + match.substr(2);
        if (match.substr(1).search(/[A-Z]+|&|[\w]+[._][\w]+/) > -1 || 
            title.substring(index - 1, index + 1).search(/[\])}]/) > -1)
            return match;
        return match.charAt(0).toUpperCase() + match.substr(1);
    });
};

String.prototype.isJSON = function() {
    var str = this.replace(/\\./g, '@').replace(/"[^"\\\n\r]*"/g, '');
    return (/^[,:{}\[\]0-9.\-+Eaeflnr-u \n\r\t]*$/).test(str);
};

function setISO8601(string, adjust_tz) {
    
    adjust_tz = adjust_tz || false;
    
    var regexp = "([0-9]{4})(-([0-9]{2})(-([0-9]{2})" +
        "(T([0-9]{2}):([0-9]{2})(:([0-9]{2})(\.([0-9]+))?)?" +
        "(Z|(([-+])([0-9]{2}):([0-9]{2})))?)?)?)?";
    
    var d = string.match(new RegExp(regexp));
    
    // console.log(string, d);
    
    var offset = 0;
    var date = new Date(Date.UTC(Number(d[1]), 0, 1));

    // console.log(Number(d[1]), 0, 1);
    
    // console.debug('date %s', date);

    if (d[3]) { date.setUTCMonth(d[3] - 1); }
    if (d[5]) { date.setUTCDate(d[5]); }
    if (d[7]) { date.setUTCHours(d[7]); }
    if (d[8]) { date.setUTCMinutes(d[8]); }
    if (d[10]) { date.setUTCSeconds(d[10]); }
    if (d[12]) { date.setUTCMilliseconds(Number("0." + d[12]) * 1000); }
    if (d[14]) {
        offset = (Number(d[16]) * 60) + Number(d[17]);
        offset *= ((d[15] == '-') ? 1 : -1);
    }

    // console.log('date again %s', date);

    if (adjust_tz) {
        offset -= date.getTimezoneOffset();
    }
    
    time = (Number(date) + (offset * 60 * 1000));
    date.setTime(Number(time));
    return date;
};

function datemax(dates) {
    var a = $.map(dates, function(d) {
        return d.getTime();
    });
    var result = Math.max(a);
    return new Date(result);
}

function timezoneString(str) {
    var d = setISO8601(str);
    return d.getTimezone();
}

// ppk's browser detect routine
// see http://www.quirksmode.org/js/detect.hml
var BrowserDetect = {
    init: function () {
        this.browser = this.searchString(this.dataBrowser) || "An unknown browser";
        this.version = this.searchVersion(navigator.userAgent)
            || this.searchVersion(navigator.appVersion)
            || "an unknown version";
        this.OS = this.searchString(this.dataOS) || "an unknown OS";
    },
    searchString: function (data) {
        for (var i=0;i<data.length;i++) {
            var dataString = data[i].string;
            var dataProp = data[i].prop;
            this.versionSearchString = data[i].versionSearch || data[i].identity;
            if (dataString) {
                if (dataString.indexOf(data[i].subString) != -1)
                    return data[i].identity;
            }
            else if (dataProp)
                return data[i].identity;
        }
    },
    searchVersion: function (dataString) {
        var index = dataString.indexOf(this.versionSearchString);
        if (index == -1) return;
        return parseFloat(dataString.substring(index+this.versionSearchString.length+1));
    },
    dataBrowser: [
        {
            string: navigator.userAgent,
            subString: "Chrome",
            identity: "Chrome"
        },
        {   string: navigator.userAgent,
            subString: "OmniWeb",
            versionSearch: "OmniWeb/",
            identity: "OmniWeb"
        },
        {
            string: navigator.vendor,
            subString: "Apple",
            identity: "Safari",
            versionSearch: "Version"
        },
        {
            prop: window.opera,
            identity: "Opera"
        },
        {
            string: navigator.vendor,
            subString: "iCab",
            identity: "iCab"
        },
        {
            string: navigator.vendor,
            subString: "KDE",
            identity: "Konqueror"
        },
        {
            string: navigator.userAgent,
            subString: "Firefox",
            identity: "Firefox"
        },
        {
            string: navigator.vendor,
            subString: "Camino",
            identity: "Camino"
        },
        {       // for newer Netscapes (6+)
            string: navigator.userAgent,
            subString: "Netscape",
            identity: "Netscape"
        },
        {
            string: navigator.userAgent,
            subString: "MSIE",
            identity: "Explorer",
            versionSearch: "MSIE"
        },
        {
            string: navigator.userAgent,
            subString: "Gecko",
            identity: "Mozilla",
            versionSearch: "rv"
        },
        {       // for older Netscapes (4-)
            string: navigator.userAgent,
            subString: "Mozilla",
            identity: "Netscape",
            versionSearch: "Mozilla"
        }
    ],
    dataOS : [
        {
            string: navigator.platform,
            subString: "Win",
            identity: "Windows"
        },
        {
            string: navigator.platform,
            subString: "Mac",
            identity: "Mac"
        },
        {
            string: navigator.userAgent,
            subString: "iPhone",
            identity: "iPhone/iPod"
        },
        {
            string: navigator.platform,
            subString: "Linux",
            identity: "Linux"
        }
    ]

};
BrowserDetect.init();

// global user state
// Will be populated in include/blank.mako
var ffr = {
    fb_uid: "",
    has_facebook_connected: false,
    has_twitter_connected: false,
    logged_in: false,
    fanfeedr_uid: 0
};

/**
 * Wrap the given function, sending a facebook popup for
 * extended permission if we haven't asked the user already
 * for this session and the user doesn't have the perms.
 */
var checkFBPublish = function(e, fn) {
    // this is an invalid case - should always be called when user is
    // logged in or chained with userRequired().
    if (!ffr.logged_in) {
        return false;
    }
    
    // attribute is undefined, so ask
    if (ffr.block_perms == undefined && ffr.has_facebook_connected) {
        fb_api.users_hasAppPermission("publish_stream", 
            function(result) {
                if (result == 0) {
                    // no permissions, do the dialog
                    FB.Connect.showPermissionDialog("publish_stream", 
                        function(resp) {
                            // empty string == dismissed pop-up
                            ffr.block_perms = ! bool(resp.toString()); 
                            fn(e, { block_perms: ffr.block_perms });
                        });
                } else {
                    // has the perms
                    ffr.block_perms = false;
                    fn(e, {block_perms : ffr.block_perms});
                }
            });
    }
    // attribute is defined.  server will check
    // for perms separately
    else {
        fn(e, {block_perms : ffr.block_perms});
    }
};

function overlay(content, opts) {
        
    opts = $.extend({
        position: "center",
        copyColors: false
    }, opts);

    // e.stopImmediatePropagation();
    
    function copyColors(elem1, elem2) {
        var colors = {
            'background-color': elem1.css("background-color"),
            'color': elem1.css("color")
        };
        elem2.css(colors);
    }

    var existingBox = Boxy.get($("#box_content"));

    if (!! existingBox) {
        existingBox.show();
    } else {

        var boxContent = $("<div></div>")
            .attr("id", "box_content")
            .append(content.show());
            
        if (opts.copyColors) {
            copyColors(content, boxContent);
            boxContent.css("border","1px solid white");
        }

        var box = new Boxy(boxContent, { modal: false, show: false });

        var guessedHeight = box.estimateSize()[1];

        box.show();
        if (opts.position == 'bottom') {
            box.center('y');
            box.moveToY($(window).height() - 50 - guessedHeight);
        } else if (opts.position == 'top') {
            box.center('y');
            box.moveToY(10);
        } else {
            box.center();
        }
    }
}
    
function modalOverlay(content, opacity, opts) {
    
    opts = $.extend({
        position: "center",
        closebox: false,
        cascade: false
    }, opts);

    // e.stopImmediatePropagation();
    
    opacity = opacity || 0.7;
    
    var key = '#box_content',
        existingBox = Boxy.get($(key));
    
    if ((!opts.cascade) && (!!existingBox)) {
        existingBox.show();
    } else {
        
        function makeBox() {
            boxContent = $("<div></div>")
                .attr("id", "box_content")
                .append(content.show());

            var closebox = $("<a href=\"#\" title=\"Close this box\" class=\"close_box\"><img src=\"/img/icons/red_close_box.png\" alt=\"close_box\"/></a>");
            closebox.click(function() {
                box.hide();
                return false;
            });

            if (opts.closebox) {
                boxContent.append(closebox);
            }
            
            var box = new Boxy(boxContent, { modal: true, show: false, opacity: opacity });

            var guessedHeight = box.estimateSize()[1];

            box.show();
            if (opts.position == 'bottom') {
                box.center('y');
                box.moveToY($(window).height() - 50 - guessedHeight);
            } else if (opts.position == 'top') {
                box.center('y');
                box.moveToY(10);
            } else {
                box.center();
            }
        }
        
        if (!!existingBox) {
            existingBox.hideAndUnload(makeBox);
        } else {
            makeBox();
        }
    }
}
    
function remoteModalOverlay(e, url) {
    
    e.stopImmediatePropagation();
    
    var existingBox = Boxy.get($("#box_content"));
    
    if (!! existingBox) {
        existingBox.show();
    } else {
        
        var boxContent = $("<div></div>").attr("id", "box_content");
        
        $("body").append(boxContent);

        boxContent.load(url, {}, function() {
            var box = new Boxy(boxContent, 
                { modal: true, show: false, 
                     beforeShow: function() { 
                         $("div.qtip").hide(); 
                     },
                     afterHide: function() {
                         $("div.qtip").show();
                     } 
                 });
            box.show();
            box.center();
        });
    }
}

// iframe

function externalErrorHandler(e) {
    // no-op
}

// comments

function postComment(e, comment, entity_resource, activity_id, opts) {
    
    console.log("postComment event: %o", e);
    
    var defaults = {
        external: false,
        post_to_fb: false,
        post_to_twitter: false,
        inline: false
    };

    opts = $.extend(defaults, opts);

    var cb = function(response) {
        $("#comment_body").val('');
        $("div.panel").hide();
        var elem = $(response).hide();
        var box = Boxy.get("#comments_boxy");
        var container = opts.inline ? 
                    $("div.comment_container[uid=" + activity_id + "] ul.comments:last") :
                    opts.external ?
                        $("#comments_boxy ul.comments") :
                        $("#comment_container ul.comments");
                    
        console.log("Container is: %o", container, opts);            
                    
        elem.prependTo(container);

        if (box) {
            box.checkSize(elem.outerHeight());
        }
        
        var cbStandalone = function() {
            var pane = $(this).parent(), diff;
            // manage position and scrolling
            if (opts.external) {
                diff = $(this).attr("offsetTop") - $("#display_comments").attr("offsetTop");
                container.scrollTo(diff, { duration: 300});
            } else {
                if (elem.position().top + elem.height() < pane.parent().height()) {
                    console.debug("presumably within original height");
                    if (elem.is(":any-below-sharebar")) {
                        diff = elem.offset().top - $(window).height() + elem.height() + 50;
                        $.scrollTo(diff, { duration: 300 });
                    }
                } else {
                    diff = pane.parent().offset().top + pane.parent().height() - $(window).height() + 50;
                    if (opts.external) {
                        console.debug("external");
                        container.scrollTo(container.height(), { duration: 300});
                    } else {
                        $.scrollTo(diff, { duration: 300 });
                    }
                }
                $(pane).jScrollPane({
                    // animateTo: true,
                    maintainPosition: false
                });
                pane[0].scrollPaneTo(pane.data('jScrollPaneMaxScroll'));
            }
        };
        
        var cbInline = function() {
        };
        
        if (opts.inline) {
            elem.parent().next().find('textarea').val('Write a comment').addClass('closed');
        } else {
            $("#comment_container").find('textarea').val('').addClass('closed');
        }
        
        elem.slideDown(300, (opts.inline ? cbInline : cbStandalone));
        
        var curr = $("span.comment_count:first").text();
        $("span.comment_count").text(++curr);
    };

    // show overlay with loading gif
    $(e.target).parent().parent().find("div.panel").show();

    $.post("/post", 
        { "body": comment,
          "entity_resource": entity_resource,
          "activity_id": activity_id,
          "comment_id": "",
          "post_to_fb": opts.post_to_fb,
          "post_to_twitter": opts.post_to_twitter,
          "inline": opts.inline
        }, cb);
}

function deleteComment(e, comment_id, external) {
    
    external = external || false;

    var event = e;

    var cb = function(response) {
        var curr = $("span.comment_count:first").text();
        $("li.comment[uid=" + comment_id + "]").
            slideUp({ duration: 300, easing: "linear", complete: function() {
                var pane = $(this).parent("ul.internal");
                console.log(pane);
                $(this).remove();
                if (! external) {
                     pane.jScrollPane({
                         animateTo: true,
                         maintainPosition: false
                     });
                }
        }});
        
        $("span.comment_count").text(--curr);
        var box = Boxy.get("#comments_boxy");

        if (box) {
            box.checkSize();
        }
        
    };

    var del = function() {
        $(event.target).parents("li").unbind("hover");
        $(event.target).text("Deleting...").addClass("notify");
        $.post("/delete", {
            "body": "",
            "entity_resource": "",
            "activity_id": "",
            "comment_id": comment_id,
            "post_to_fb": ""
        }, cb);
    };

    Boxy.confirm("Are you sure you want to delete this comment?", del, { opacity: 0.2, title: "Confirm" });

}

function openEditor(e) {
    console.log("openEditor called");
    $(this).val('').removeClass("closed").parent().next().show();
}
   
function removeFan(e) {
    $(this).prev().animate({ opacity: 0.7 }, 300);
    var uid = $(this).attr("uid");
    $.post('/profile/' + uid + '/follow/',
            { 'mini': true },
            function(data) {
                $("li.fan, div.avatar").trigger({
                    type: "removed",
                    targetUser: uid,
                    repl: $(data),
                    currentUser: e.currentUser
                });
                
            });
    return false;
}   
function addFan(e) {
    $(this).prev().animate({ opacity: 0.7 }, 300);
    var uid = $(this).attr("uid");
    $.post('/profile/' + uid + '/follow/',
            { 'mini': true },
            function(data) {
                $("li.fan, div.avatar").trigger({
                    type: "added",
                    targetUser: uid,
                    repl: $(data),
                    currentUser: e.currentUser
                });
            });
    return false;
}

function displayUserWidget() {
    $("ul.user_widget").each(function() {
        $(this).children().slice(0,8).show();
        $(this).children().slice(8).hide();
    });
}

function refreshUserWidget(user) {
    $("a.avatar_link.add").userRequired(user).click(addFan);
    $("a.avatar_link.remove").userRequired(user).click(removeFan);
    displayUserWidget();
}

ffr.show_entry = function() {
    modalOverlay($("#entry"), 0.1);
    $("#ack").click(function() {
        $("#userbar_options").trigger("t1");
        Boxy.get("#box_content").hide();
    });
}

var currency = {
    _all: $("span.currency"),
    update: function(offer_id) {
        var that = this;
        $.post("/game/update_currency", 
            { 'offer' : offer_id },
            function(resp) {
                resp = $(resp);
                $("span.currency").replaceWith(resp);
            });
    }
};

var hints = {
    _all: $.fn.qtip.interfaces,
    close: function() {
        _(this._all).invoke('hide');
    }
};

var opp_error = {
    store: {},
    setup: function(sel) {
        var that = this;
        elems = $(sel);
        elems.each(function() {
            that.create($(this));
        });
        return elems;
    },
    create: function(elem) {
        this.store[elem] = elem;
    },
    present: function(elem, message) {
        elem.css({
            'background-color': 'red'
        })
        .find("span.error_msg")
        .text(message)
        .show();
    },
    clear: function(elem) {
        elem.css( { 'background-color': '#8dbb16'})
        .find("span.error_msg")
        .hide();
    }
};

var offers = {
    container: $("ul.offers:first"),
    fetch: function(resource_path) {
        var that = this;
        $.post("/game/offers", 
            { 'entity' : resource_path },
            function(resp) {
                resp = $(resp);
                resp.hide();
                $("ul.offers:first").append(resp);
                resp.fadeIn(300);
            });
    },
    effectSpeed: function() {
        speed = this.container.length ? 
            this.container.length * 50 : 
            300;
        return speed;
    },
    hide: function() {
        speed = this.effectSpeed();
        this.container.slideUp(speed);
    },
    show: function() {
        speed = this.effectSpeed();
        this.container.slideDown(speed);
    }
};

$(document).ready(function() {
    
    $("form").submit(function(){
        $(this).find("input[type='image'],input[type='submit']").click(function(){
            return false;
        });
    });
    
    var openWidget = function() {
        $(this).addClass("open").next().slideDown(300);
    };
    
    var closeWidget = function() {
        var me = $(this);
        me.next().slideUp(300, function() {
            me.removeClass("open");
        });
    };
    
    opp_error.setup($("li.opportunity"));
    
    // $("a.fb_connect").click(function(e) {
    //    e.preventDefault();
    //    window.open('http://www.facebook.com/login.php?api_key=' + fb_key + '&display=popup&extern=1&fbconnect=1&req_perms=publish_stream&return_session=1&v=1.0&next=' +
    //        escape(fb_url) + '&fb_connect=1', '_blank', 'top=442,width=480,height=460,resizable=yes', true);
    //    });
    
    $("a.fb_connect").click(function(e) {
        e.preventDefault();
        remoteModalOverlay(e, "/account/register_overlay?continue_path=" + encodeURI(window.location.pathname));
    });
    
    $("li.offer p.call").toggle(
        function() {
            $(this).next().slideDown("300");
        },
        function() {
            $(this).next().slideUp("300");
        });
        
    var boxscore_pick = function(e, opts) {
        e.preventDefault();
        var
            elem = $(e.target),
            offer = elem.parent(),
            team_link = elem.closest("tr").find("a.team_link"),
            offer_value = elem.closest("div.recap_box").find("p.call span.value"),
            team_path = elem.attr("id"),
            checkmark = $("<img></img>").attr({
                      alt: 'checkmark', 
                      src: '/img/icons/checkmark.png' 
                    }),
            offer_id = offer.attr("uid"),
            box = elem.closest("div.recap_box"),
            desc = box.children("p.call");
        elem.addClass("selected");
        $.post("/game/game_pick",
            { 'offer': offer_id, 'team': team_path, 'block_perms': opts.block_perms },
            function(resp) {
                if ($(resp).has("#gaming_error")) {
                    $("body").append($(resp));
                } else {
                    $("td.offer a:not(.selected)", box).remove();
                    currency.update(offer_id);
                    elem.fadeOut(100, function() {
                        elem.after(checkmark);
                        repl = $("<div></div>").append(offer_value);
                        desc.html("You picked this for " + repl.html() + ".");
                        box.css({ 'background-color' : '#def3a5' });
                        checkmark.fadeIn(100);
                    });                    
                }
            });
        return false;
    };
        
    $("li.offer a.action").livequery("click", function(e) {
        checkFBPublish(e, function(e, opts) {   
            e.stopPropagation();
            var elem = $(e.target),
                offer = elem.closest("li"),
                team_path = elem.attr("id"),
                offer_id = offer.attr("uid"),
                msg = [];
           $.post("/game/game_pick", 
                { 'offer' : offer_id, 'team' : team_path, 'block_perms':opts.block_perms },
                function(resp) {
                    if ($(resp).has("#gaming_error")) {
                        $("body").append($(resp));
                    } else {
                        resp = $(resp).hide();
                        currency.update(offer_id);
                        offer.fadeOut(300, function() {
                            offer.after(resp);
                            resp.fadeIn(300);
                        });
                    }
                });
            return false;
        });
        return false;
    });
    
    $("td.offer a.action").userRequired(ffr.fb_uid).click(function(e) {
        checkFBPublish(e, boxscore_pick);
        return false;
    });
    
    $("li.offer input").click(function() {
        console.debug($(this));
        opp_error.clear($(this).closest("li.offer"));
    });
    
    $("li.offer a.close_box").click(function(e) {
        e.preventDefault();
        offer = $(this).closest("li");
        $(this).closest("li").fadeOut(300, function() {
            $.post("/game/dismiss", { 'offer' : offer.attr("uid") });
        });
    });
    
    $("ul.tabs a").click(function() {
        var div, t = $(this).attr("href").split("#")[1];
        $("ul.tabs a").removeClass("selected");
        $(this).addClass("selected");
        div = $("div.tabs #" + t);
        div.siblings().hide();
        div.show();
        return false;
    });
    
    $("a.get_more").livequery("click", function() {
        var opts = { closebox: true, cascade: true }, iframe = $("#trialpay_container iframe");
        modalOverlay(iframe, null, opts);
        return false;
    });
        
    $("h4.control:not(.teams, .fan_of)").toggle(openWidget, closeWidget);
    
    $("h4.control.teams, h4.control.fan_of").toggle(closeWidget, openWidget);
            
    $("td.external_page").ready(function()
        {
            var h = $(document).height() - $("td.fanfeedr_bar").height();
            $("td.external_page").height(h);
            $(window).resize(function() {
                var h1 = $(document).height() - $("td.fanfeedr_bar").height();
                $("td.external_page").height(h1);                
            });
        }
    );
    
    // $("iframe").load(function() {
    //     // console.log(this.contentWindow);
    // });
    
    $("li.topic p").toggle(
        function(e) {
            if (e.target == this) {
                $(this).find("span").hide();
                $(this).next().slideDown(400);
            } 
        },
        function(e) {
            if (e.target == this) {
                $(this).next().slideUp(400);
                $(this).find("span").show();
            }
        }
    );
    $("li.topic a").click(function() {
        if ($(this).is(".indicator")) {
            $(this).parent().trigger("click");
            return false;
        } else {
            location.href = $(this).attr("href");
        }
    });
    
    $("table.team").tablesorter();

    $("a.restore").click(function() {
        $(this).parents("table.team").trigger("sorton",[0,0]);
    });
    
        
    $("table.view_control.filter a").click(function() {
        $(this).parent().next().find("span").hide();
        $(this).parent().next().find("span." + util.reduce_text($(this).attr("title"))).show();
    });
        
    $('a[rel*=boxy]').boxy({closeText:"[X]"});
    
    $('a.fb_login').click(function(e) {
        console.log("fb_login");
        var cb_href = $(e.target).attr("href");
        FB.Connect.requireSession(function() {
            location.href = cb_href;
        }); 
        return false;
    });
        
    $("#search_form").keydown(function(event) {
        // console.log(event);
    });
    
    $("div#accordion").accordion({collapsible:true, autoHeight:false});
     
    replaceFan = function(e) {
        if ($(this).children("a.avatar").is("." + e.targetUser)) {
            var fan = $(e.repl).find("div.avatar").bind("added removed", replaceFan).clone(true);
            $(this).replaceWith(fan);
        }
    };
    
    $("div.avatar").bind("added removed", replaceFan);
    
    addedFan = function(e) {
        var target_s = "li." + e.targetUser;
        var uid = $(this).attr("uid") || e.currentUser;
        if (uid == e.currentUser) {
            if ($(this).has(target_s)) { 
                return;
            };
            var added = $(e.repl).clone(true).hide();
            $(this).append(added);
            if (! ($(this).hasClass('user_widget') && $(this).children().size() > 8)) {
                $(added).fadeIn(1000, displayUserWidget);
            }
        }
    };
    
    removedFan = function(e) {
        var uid = $(this).attr("uid") || e.currentUser;
        if (uid == e.currentUser && ($(this).hasClass("follows") || $(this).hasClass("fans"))) {
            // console.log($(this), $(this).children().filter("li." + e.targetUser));
            $(this).children().filter("li." + e.targetUser).fadeOut(1000, function() {
                $(this).remove();
                displayUserWidget();
            });
        }
    };
    
    $("ul.follows, ul.fans").bind("added", addedFan);
    
    $("ul.follows, ul.fans").bind("removed", removedFan);
    
    var expander = function(e) {
        var h = $(this).attr("scrollHeight");
        if (h > 56) {
            var adjusted = (e.type == 'expand') ?
                h : Math.min(56, h);
            $(this).animate({ height: adjusted, maxHeight: adjusted });
        }
    };

    var showToggles = function() {
        var h = $(this).attr("scrollHeight");
        if (h > 58) {
            $(this).nextAll("a.toggle").show();
        }
    };

    $("li.comment.inline textarea.edit").val('Write a comment');
    
    $("#comment_container textarea").val('');

    $("li.comment").find("a.delete_comment").livequery("click", function(e) {
            console.log(e);
            var comment_id = $(this).parents("li").attr("uid");
            e.preventDefault();
            deleteComment(e, comment_id);
        });

    $("li.comment").find("a.flag_comment").livequery("click", function(e) {
        var comment_id = $(this).parents("li").attr("uid");
        e.preventDefault();
        // TODO: determine reqts and fxnality here
        alert("Flagging comment " + comment_id + " for abuse");
    });
    
    var orig = $("textarea.edit.ffr:first").height();
    
    $("textarea.edit.comment").livequery("focus", openEditor).livequery("blur", function(e) {
        var s = $(e.target).val();
        console.log(s);
        if (s.length == 0 || s == 'Write a comment') {
            $(e.target).val('Write a comment')
            .addClass("closed").height(23)
            .parent().next().hide();
        }
    });

    $("textarea.edit.comment").autoResize({animate: true, extraSpace: 18});
        
    $("a.cancel_comment").livequery("click", function(e) {
        e.preventDefault();
        
        $("#comment_body").val('');
        $("#comment_body").animate({"height": orig}, 300);
    });

    $("a.post_comment").livequery("click", function(e) {

        var entity = ''; 
        var activity = ''; 
        var t = $(e.target);
        var uid = t.closest("div.comment_container").attr("uid");
        var textBox = t.parent().prev().find("textarea");
        
        // console.log("target: %o; inline: %s, uid: %s", t, t.is(".inline"), uid);
        
        if (t.is(".inline")) {
            activity = uid;
        } else {
            entity = uid;
        }
        
        var opts = {
            external: t.is(".external"),
            post_to_fb: $("#post_comment_to_fb").is(":checked"),
            post_to_twitter: $("#post_comment_to_twitter").is(":checked"),
            inline: t.is(".inline")
        };
        
        console.log("entity %s, activity %s", entity, activity);
        postComment(e, textBox.val(), entity, activity, opts);
        
        return false;
    }); 

    $("div.collapsible").livequery("expand", expander).livequery("collapse", expander);

    $("div.collapsible").livequery(showToggles);

    // $("div.comment_body").trigger("collapse");

    $("li.comment a.toggle").click(function(e) {
        e.preventDefault();
    });

    var expander_toggle_init = function() {

        $(this).toggle(
            function(e) {
                $(this).removeClass("more").addClass("less");
                $(this).prev().trigger("expand");
            },
            function(e) {
                $(this).removeClass("less").addClass("more");
                $(this).prev().trigger("collapse");
            }
        );

    };

    var expander_toggle_teardown = function() {
        $(this).unbind('toggle').unbind('click');
    };

    $("li.comment a.toggle").livequery(expander_toggle_init, expander_toggle_teardown);
    
    $("a.submitter").click(function() {
        $(this).parents("form").submit();
        return false;
    });
        
});

jQuery.fn.preventDoubleSubmit = function() {
  jQuery(this).submit(function() {
    if (this.beenSubmitted) {
        return false;
    }
    else {
        this.beenSubmitted = true;
    }
  });
};


