document.write(
        '<style>@font-face { font-family: LeagueGothic; src: url(/forum/Themes/default/League%20Gothic.otf) format("opentype"); } ' +
        '       @font-face { font-family: Chunk; src: url(/forum/Themes/default/Chunk.otf) format("opentype"); }' +
        '       @font-face { font-family: Fnord; src: url(/forum/Themes/default/fnordx.ttf) format("truetype"); }' +
        '       @font-face { font-family: Sniglet; src: url(/forum/Themes/default/Sniglet.ttf) format("truetype"); }</style>');

$(document).ready(function () {
    var debug = localStorage.getItem('debug000');
    var message = $('textarea[name=message]');
        
    if (location.search.match(/topic=22171/)) {
        document.title = '..##@_TH 3  _ MGT.. H3 ((CoME5';
        $('#ajax_in_progress').css({
            display:'block',
            position:'absolute',
            width:'100%',
            height:'650px',
            top:'1000px',
            textIndent:'-5000px',
            background:'url(/images/crumble.gif) bottom right repeat-x',
            borderBottom:'9000px solid black'
        })
    }

    // add shortcut keys to post editor form
    var last_custom_tag = '';
    message.keypress(function (event) {
        message.dirty = true; // for autosave
        if (!event.ctrlKey) return;
        var key = String.fromCharCode(event.which).toLowerCase();
        var tag = {'i':'i', 'b':'b', 'q':'quote', 'l':'url'}[key];
        if (tag) {
            surroundText('['+tag+']', '[/'+tag+']', message[0]);
        } else if (key == 'k') {
            var tag = prompt('Enter tag (example "color=blue")', last_custom_tag);
            if (tag) {
                last_custom_tag = tag;
                var closing_tag = tag.split('=')[0];
                surroundText('['+tag+']', '[/'+closing_tag+']', message[0]);
            }
        }
    });    
    
    // THE BUTTON THAT TURNS EVERYBODY INTO A ROBOT
    if (localStorage.getItem('everybody_turned_into_a_robot')) {
        turn_everybody_into_a_robot();
        play_the_quest();
    } else {
        if (Math.random() < 0.1 || location.hash.indexOf('#robot') != -1) {
            display_robot_button();
        }
    }

    function turn_everybody_into_a_robot() {
        $('.avatarcontainer').each(function () {
            var profile_url = $(this).nextAll('a[href*=";u="]').eq(0).attr('href');
            var user_id = /u=(\d+)/.exec(profile_url)[1]
            var path = 'http://www.principiadiscordia.com/forum/robot-avatars/robot.php?id=' + user_id;
            $(this).html('<img src="' + path + '" style="width:140px;height:140px" />');
        });
    }; 

    function display_robot_button() {
        $('body').append('<div id="robotbutton"></div>');
        var robot_button = $('div#robotbutton');
        robot_button.css({
            background: "url(http://www.principiadiscordia.com/forum/robot-avatars/robot-button.png)",
            width: "180px", height: "180px", position: "absolute", right: "10px",
            display: "none", zIndex:"500",
        });
        robot_button.fadeIn(5000);
        robot_button.click(function () {
            turn_everybody_into_a_robot();
            localStorage.setItem('everybody_turned_into_a_robot', true);
            $(this).fadeOut(1000);
        });
    }

    function play_the_quest() {
//        if (!localStorage.getItem('trip_debug')) return;
        var topic_match = /index.php\?topic=(\d+)/.exec(location.href);
        if (!topic_match || location.href.indexOf('action') != -1) return; // if we're not in an actual thread, return
        var topic = topic_match[1];
        var used_topics = (sessionStorage.getItem('quest_used_topics') || '').split(',');
        var tasks = sessionStorage.getItem('quest_tasks') || 'mittens,lulz,argh!,fnord,fap';
        var start_time = sessionStorage.getItem('quest_start_time');
        //console.info('questing in topic ' + topic + ', tasks <' + tasks + '>, used topics <' + used_topics + '>');
        $(tasks.replace(/([^,]+)/g, 'img[alt="$1"]')).click(function () {
            //console.info('click trget');
            if (used_topics.indexOf(topic) != -1) { return; }
            var target = $(this).attr('alt');
            // tasks = tasks.split(',').filter(function(x){return x != target}).join(',');
            tasks = tasks.replace(RegExp('^' + target + '($|,)|,' + target), '');
            used_topics.push(topic);
            sessionStorage.setItem('quest_tasks', tasks);
            sessionStorage.setItem('quest_used_topics', used_topics.join(','));
            if (!start_time) sessionStorage.setItem('quest_start_time', start_time = (+new Date()));
            $(this).fadeOut(1000, function () {
                if (!tasks) { // YOU WIN !!
                    sessionStorage.removeItem('quest_tasks');
                    sessionStorage.removeItem('quest_used_topics');
                    sessionStorage.removeItem('quest_start_time');
                    localStorage.removeItem('everybody_turned_into_a_robot');
                    alert('SUCCESS!! EVERYBODY IS HUMAN AFTER ALL!\n\nENJOY YOUR VICTORY VIDEO');
                    location.href = 'http://vimeo.com/9937317';
                }});
        });
        $('body').append('<div id="quest_bar" style="display:none"></div>');
        setInterval(function () {
            if (start_time) { // The race has started!!
                var bar = $('#quest_bar');
                var time_left = 400  + Math.floor((start_time - (+new Date())) / 450);
                if (time_left <= 0) time_left = 0;
                bar.css({ position: 'fixed', top: '0px', left: '0px', height: '24px', width: (700 - time_left) + 'px',
                    borderLeft: time_left + 'px solid #0f0', textAlign: 'right', display: 'block', paddingRight: '8px',
                    background: '#060', color: '#4f4', font: 'bold 14px/24px Consolas,monospace', textTransform: 'uppercase'});
                if (time_left) {
                    bar.text(tasks.replace(/,/g, ' '));
                } else {
                    bar.text('TIME IS UP--TRY AGAIN');
                    sessionStorage.removeItem('quest_tasks');
                    sessionStorage.removeItem('quest_used_topics');
                    sessionStorage.removeItem('quest_start_time');
                    used_topics.push(topic);
                }
            }
        }, 500);
    }

  /* // youtube title crap
  
  if (location.hash.indexOf('#test') < 0) return;

  $('a[href^=http://www.youtube.com/watch?],a[href^=http://youtube.com/watch?]')
  .each(function (){
    var v = location.search.match(/v=(\w+)/)[1];
    var a = this;
    $.getJSON('http://gdata.youtube.com/feeds/api/videos/' + v + '?alt=json-in-script&callback=?',
    function (o){
      a.title = o.entry.title.$t;
    });
  });*/
  
    // autosave
    
    function date_format(d) {
        d = new Date(d);
        zp = function (s) { return ('00'+s).substr(-2); }
        return d.getFullYear()+'/'+zp(d.getMonth())+'/'+zp(d.getDate())+' '+zp(d.getHours())+':'+zp(d.getMinutes())+':'+zp(d.getSeconds())
    }
        
    if (debug && message.length) {
        // what kind of message are we posting?
        var draft_id = date_format(Date());
        if ($('input[name=to]').length) {
            draft_id += ' PM to ' + $('input[name=to]').val();
        } else if ($('input[name=topic]').val() == '0') {
            draft_id += ' New topic at board ' + /board=(\d+)/.exec(location.search)[1];
        } else {
            draft_id += ' Reply to topic ' +  + $('input[name=topic]').val();
        }
        // console.info('Autosave: '+draft_id);
        
        var subject = $('input[name=subject]');
        function save() {
            if (message.dirty) {
                // console.info('Autosaving ' + draft_id);
                Drafts.item(draft_id, message.val(), subject.val());
                message.dirty = false;
            }
        }
        // save every 30 seconds and on form submit        
        setInterval(save, 30 * 1000);
        message.parents('form').submit(save);
        
        var preview = $('input[name=preview]').eq(-1);
        if (preview.length) {
            var view_drafts = $('<input type="button" value="Drafts" />');
            preview.after(view_drafts);
            view_drafts.click(function () {
                var html = "<!DOCTYPE html><html><head><title>Drafts</title><style>*{margin:0;padding:0;text-indent:0;list-style:none}li{background:#ddd;padding-bottom:24px;}input,textarea{border:1px solid #000;background:#fff;display:block;width:620px;padding:4px;margin:8px auto;}textarea{height:300px;}p{font:bold 10px/24px sans-serif;color:#ddd;background:#000;text-align:center;cursor:pointer;}p:hover{color:#fff}</style></head><body><ul></ul></body></html>";
                var win = window.open("", "drafts", "toolbar=no,location=no,status=no,menubar=no,scrollbars=yes,width=680,height=500,resizable=yes");
                var doc = win.document;
                doc.write(html);
                doc.close();
                for (var i = 0, item; item = Drafts.item(i); i++) {
                    var el = $('<li><p /><input type="text" /><textarea></textarea></li>', doc);
                    el.find('p')
                        .text(item.id + ', last modified ' + date_format(item.time))
                        .attr('title', 'Click to load.')
                        .click(function () {
                            subject.val($(this).nextAll('input').val());
                            message.val($(this).nextAll('textarea').val());
                            win.close();
                        });
                    el.find('input').val(item.subject).attr('readonly','readonly');
                    el.find('textarea').val(item.msg).attr('readonly','readonly');
                    $('ul', doc).append(el);
                } 
            });
        }
    }
    
    // CENTRAL NOTICE
    
    /*if (localStorage.centralnotice != 'hide') {
        var cnotice = $('<div></div>')
            .css({
                width: '831px',
                height:'187px',
                background:'#fff url(/images/centralnotice-2.jpg)',
                cursor:'pointer',
                border:'4px solid #fff',
                borderWidth:'4px 16px'})
            .attr('title','http://www.principiadiscordia.com/forum/index.php?topic=17901.0')
            .click(function() { location = 'http://www.principiadiscordia.com/forum/index.php?topic=17901.0'; })
            .prependTo($('body'));
        var cclose = $('<div></div>')
            .css({
                width: '28px',
                height:'30px',
                margin:'0 0 0 800px'})
            .attr('title','close')
            .appendTo(cnotice)
            .click(function() { localStorage.centralnotice = 'hide'; cnotice.hide(); return false; });
    }*/

});

var Drafts = function () {
    // private
    var d;
    function read() {
        d = JSON.parse(localStorage.getItem('message_drafts') || '{"max_items":10,"items":[]}');
    }
    read();
    function write() {
        localStorage.setItem('message_drafts', JSON.stringify(d));
    }
    function check_length() {
        if (d.items.length <= d.max_items) return;            
        d.items.sort(function (a, b) { return b['time'] - a['time']; });
        d.items.splice(d.max_items);
    }
    // public
    return {
        item: function (id, msg, subject) {
            read();
            var t;
            if (typeof id == 'number') {
                t = d.items[id];
                if (!t) return;
            } else {
                for (var i = 0; (t = d.items[i])  && t['id'] != id; i++);
            }
            if (!msg) return t;
            if (!t) {
                t = {id: id};
                d.items.push(t);
            }
            t['time'] = Date();
            t['msg'] = msg;
            t['subject'] = subject;
            check_length();
            write();
        },
        length: function () { return d.items.length; }
    }
}();

