//TEMPLES, keu keu

submitting = false ;

badComms = new Array();
badComms[0] = 'launch';
badComms[1] = 'login';
badComms[2] = 'sudo';
badComms[3] = 'cp';
badComms[4] = 'rm';
badComms[5] = 'ps';
badComms[6] = 'exit' ;
//badComms[7] = 'cd' ;

window.commands = [];
var buffer = -1;

function in_array(needle, haystack, argStrict) {
    // http://kevin.vanzonneveld.net
    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: vlado houba
    // *     example 1: in_array('van', ['Kevin', 'van', 'Zonneveld']);
    // *     returns 1: true
    // *     example 2: in_array('vlado', {0: 'Kevin', vlado: 'van', 1: 'Zonneveld'});
    // *     returns 2: false
    // *     example 3: in_array(1, ['1', '2', '3']);
    // *     returns 3: true
    // *     example 3: in_array(1, ['1', '2', '3'], false);
    // *     returns 3: true
    // *     example 4: in_array(1, ['1', '2', '3'], true);
    // *     returns 4: false
 
    var key = '', strict = !!argStrict;
 
    if (strict) {
        for (key in haystack) {
            if (haystack[key] === needle) {
                return true;
            }
        }
    } else {
        for (key in haystack) {
            if (haystack[key] == needle) {
                return true;
            }
        }
    }
 
    return false;
}

function randomchar() {
    var chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghiklmnopqrstuvwxyz ";
    var randomchar = '' ;
    var rnum = Math.floor(Math.random() * chars.length);
    return chars.substring(rnum,rnum+1);
}


/* flicker screen intermittently */
function flicker() {
       clearTimeout(t);
       glitched = false ;
       opacity = Math.floor(6+Math.random()*10)/10 ;
       $('body').css('opacity',opacity);

       $('#content p[id!=term]').contents().each(function() { //glitch stuff, let's be friendly and not glitch the terminal
        text = $(this).text();
        length = text.length ;
        chance = 0.993;
        if(Math.random() > chance && glitched == false) {
             victim = Math.floor(Math.random()*length)+1 ;
             if(text.charAt(victim) != " ") {
                 start = text.substring(0,victim-1);
                 end = text.substring(victim,length);
                 var newstring = start + randomchar() + end ;
                 $(this).text(newstring);
                 glitched = true ;
            }
        }
      });

       if(flickerCount > 0) {
           timeout = Math.floor(Math.random()*5);
           t = setTimeout('flicker()', timeout);
           flickerCount--
       } else {
           resetFlicker();
       }
   }
   function resetFlicker() {
       flickerCount = Math.floor(Math.random()*10)+1 ;
       $('body').css('opacity','1');
       timeout = Math.floor(Math.random()*30000);
       t = setTimeout('flicker()', timeout);
   }
/* end flicker */

/* terminal and input handling stuff */

function bindTerminal() {
    $('input.term').val('');
    $('input.term').focus();
    //thx pnuk
    $("input.term").keyup(
        function(e) {
            if( e.keyCode == 38 ) {
                if( buffer <= 0 )
                    buffer = window.commands.length - 1;
                else
                    buffer--;
                    $(this).val( window.commands[ buffer ] );
            } else if( e.keyCode == 40 ) {
                if( buffer >= window.commands.length -1 ) {
                    buffer = 0;
                } else {
                    buffer++;
                }
                $(this).val( window.commands[ buffer ] );
            } else if( e.keyCode == 13 && $(this).val() != "" && !submitting) {
                getNewMessagesCount();
                parseInput($(this).val());
            }
        }
    );
    window.scrollBy(0,10000000);
}

function parseInput(termCommand) {
    window.commands.push( termCommand );
    
    //fetch stuff from parser
    
    $('#content').css('display','block');
    
    //warning! incoming HORRIBLE KLUDGE
    if(termCommand.indexOf('messages') != -1 || 
        termCommand.indexOf('message') != -1 || 
        termCommand.indexOf('read') != -1 || 
        termCommand.indexOf('mail') != -1 || 
        termCommand.indexOf('twitter') != -1 ||
        termCommand.indexOf('pine') != -1
        ) {
    
        $('#content').append('<p>[guest@temples ~]$<span class="term">' + termCommand + '</span></p>'); //print faux terminal
        readNewMessages(); //fetch messages
    
    } else if(termCommand.indexOf('rotate') != -1) {
        jQuery.each(jQuery.browser, function(i) {
            if($.browser.safari) {
                $("#c").attr('style','-webkit-transform:rotate(-90deg)');
            } else if($.browser.mozilla) {
                $("#c").attr('style', '-moz-transform:rotate(-90deg)');
            }
        });
    } else if(termCommand.indexOf('reflect') != -1) {
        jQuery.each(jQuery.browser, function(i) {
            if($.browser.safari) {
                $("#c").attr('style','-webkit-transform:rotate(180deg)');
            } else if($.browser.mozilla) {
                $("#c").attr('style', '-moz-transform:rotate(180deg)');
            }
        });
    }
        else { 
        $.get('parser.php', { command: termCommand }, function(output) { //send command to parser
            $('#content').append(output);
            //clear #content if command is 'clear'
            if(termCommand == 'clear') { 
                $('#logo').remove(); //ok, ok, let's remove the logo as well.
                $('#content').empty() ; 
            }

            end = termCommand.length ; //check for "bad" commands

            if(termCommand.indexOf(' ') > 0) end = termCommand.indexOf(' ');
            if(in_array(termCommand.substr(0,end), badComms)) {
                $('#term').remove();
            }  
            submitting = false ;
        });
    }
    bindTerminal();
}

/* end terminal */

/* twitter integration */
/* moved to server side .. NOT */
function getNewMessagesCount() {
    
    $('#term').hide();
     
    if($.cookie('last_updated')) { 
        since_id = $.cookie('last_updated'); 
    } else if ($.cookie('last_read')) { 
        since_id = $.cookie('last_read');
    }
    
    if(!$.cookie('last_read') && !$.cookie('last_updated')) { 
        twitter_url = "http://search.twitter.com/search.json?rpp=200&q=%23templesfi&callback=?" ; 
    } else {
        twitter_url = "http://search.twitter.com/search.json?rpp=200&q=%23templesfi&callback=?&since_id=" + since_id ;
    }
    
    $.getJSON(twitter_url, 
        function(tweets) {
            if(tweets.results.length > 0) {
               
               $.cookie('last_updated', tweets.results[0].id, { expires: 0, path: '/', domain: 'temples.fi', secure: false });
               if(!$.cookie('last_read')) { $.cookie('last_read', tweets.results[tweets.results.length-1].id-1, { expires: 0, path: '/', domain: 'temples.fi', secure: false }) ; }
               $('#content').append('<p>You have ' + tweets.results.length + ' new <strong>messages</strong>.</p>'); 
              $('#term').show(); 
            }
        });
}

function readNewMessages() {
    since_id = 0 ;
    //damned if i can be arsed to figure out what the f is broken with this thing. I'll get around to fixing it when it's time to overhaul the site, which hopefully is never.
    if(!$.cookie('last_read')) {
        // since_id = $.cookie('last_updated')-1;
    } else {
       // since_id = $.cookie('last_read');
    }
    
    $.getJSON("http://search.twitter.com/search.json?rpp=200&q=%23templesfi&callback=?&since_id=" + since_id, 
        function(tweets) {
            console.log(tweets);
            if(tweets.results.length > 0) {
                for (i = 0 ; i < tweets.results.length ; i++) {
                    writeMessage(tweets.results[i]);
                }
                $.cookie('last_read', tweets.results[0].id, { expires: 30, path: '/', domain: 'temples.fi', secure: false }) ;
                $.cookie('last_updated', tweets.results[0].id) ;
            } else {
                $('#content').append('No unread messages.');
            }
        });
}

function writeMessage(tweet) {
    
    message = tweet.text.replace(/\#templesfi/i, '');
    message = message.replace(/twitter/i, 'comms');
    
    html =  '<p><strong>' + tweet.id + '</strong><br />' + message + '<br />//<strong>' + tweet.from_user + '</strong>'  ;
    html += '<br />----------------------------------------------------------------</p>'
    $('#content').append(html);
}
/* end twitter */

/* init document */

$(document).ready(function() {
   // init for reloading page
   $('#term').hide();
   getNewMessagesCount();
   
   $(document).click(function() {
       $('input.term').focus();
   });
   
   $('#content').ajaxStart(function() { 
       submitting = true ;
       $('#term').hide(); 
   });
   
   $('#content').ajaxStop(function() { 
       submitting = false ;
       $('#term').show();
       bindTerminal(); 
   });
   
   bindTerminal();
   resetFlicker();
});
