﻿// GWConsole  //

var GWconsole, GWConsole_content, GWconsole_input;
var GWconsole_visible = false;
var GWConsoleCommands =
[
    { name: 'Auto Complete Form', command: 'ac', func: GWConsole_Command_AutoComplete },
    { name: 'Reset form', command: 'resetform', func: GWConsole_Command_ClearForm},
    { name: 'Change console colour', command: 'colour', func: GWConsole_Command_ChangeColour },
    { name: 'Exit Console', command: 'exit', func: GWConsole_Command_Close },
    { name: 'Show this help', command: 'help', func: GWConsole_OutputCommmands },
    { name: 'Clear Console', command: 'cls', func: GWConsole_Clear },
    { name: 'Run Validation', command: 'validate', func: GWConsole_Command_Validate },
    { name: 'Toggle Quick Shortcut', command: 'toggleshortcut', func: GWConsole_Command_ToggleShortcut },
    { name: '', command: 'cornify', func: GWConsole_SuperCorn, hidden:true }
];
var GWconsole_commandHistory = new Array();
var GWconsole_historyPosition = null;
var welcomeTxt = "GradWeb 2.0 Console - Copyright (c) 2009 GradWeb Ltd.";

function GWConsole_Setup() {
    $(document).keyup(GWConsole_CheckKeySequence);
    if (readCookie("GWCONSOLE_QUICKSHORTCUT") == 'true') 
        GWConsole_ToggleQuickShortcut(true);
};

var seq = [38, 38, 40, 40, 37, 39, 37, 39]; // u,u,d,d,l,r,l,r
var seqPos = 0; var seqTimeout = null;

function GWConsole_CheckQuickShortcut(event) {
    var kc = event.keyCode;
    if (kc == 223 && event.ctrlKey) 
    {
        GWConsole_Toggle();
    }
};

function GWConsole_CheckKeySequence(event) {
    var kc = event.keyCode;
    if (seq[seqPos] == kc) {
        if (seqPos == seq.length - 1) {
            seqPos = 0;
            clearTimeout(seqTimeout);
            GWConsole_Toggle();
        }
        else {
            if (seqTimeout) clearTimeout(seqTimeout);

            seqTimeout = setTimeout(GWConsole_SequenceTimeout, 750);
            seqPos++;
        }
    }
    else seqPos = 0;
};

function GWConsole_ToggleQuickShortcut(shortCutActive) {
    if (shortCutActive) {
        $(document).keydown(GWConsole_CheckQuickShortcut);
    }
    else 
    {
        $(document).unbind('keydown');
    }
};

function GWConsole_SequenceTimeout() {
    seqPos = 0;
    seqTimeout = null;
};

function GWConsole_Toggle() {
    if (!GWconsole_visible) {
        if (GWconsole === undefined) {
            var html = "<div id=\'GWconsole\'><div id='GWConsoleContainer'><div id='GWConsoleContent'></div><div> &gt; <input type='text' id='GWConsole_Input' /></div></div></div>";
            var docW = $(document).width();
            $("body").prepend(html);

            GWconsole = document.getElementById('GWconsole');
            GWconsole_input = document.getElementById('GWConsole_Input');
            GWConsole_content = document.getElementById('GWConsoleContent');

            var colour = readCookie("GWCONSOLE_COLOUR");
            if (colour !== null) GWConsole_Command_ChangeColour(colour);
        }

        GWConsole_UpdateWidth();
        $(window).resize(GWConsole_UpdateWidth);
        $(GWconsole_input).keyup(GWConsole_InputKeyUp);
        $(GWconsole).click(GWConsole_Clicked);

        GWconsole_visible = true;

        GWConsole_Clear();
        GWConsole_Output("Welcome to GradWeb Console! Please enter a command. (For a list of commands type 'help') ");
        
        $(GWconsole).slideDown('normal', function() {
            GWconsole_input.focus();
        });
    }
    else {
        $(GWconsole).slideUp();

        $(window).unbind("resize");
        $(GWconsole_input).unbind("keyup");
        $(GWconsole).unbind("click");
        
        GWconsole_visible = false;
        GWConsole_Setup();
    }
};

function GWConsole_OutputCommmands() {
    for (i = 0; i < GWConsoleCommands.length; i++) {
        var comm = GWConsoleCommands[i];
        if(comm.hidden !== true) GWConsole_Output(comm.command + ' - ' + comm.name);
    }
    GWConsole_ScrollBottom();
};

function GWConsole_InputKeyUp(e)
{
    switch (e.keyCode) {
        case 13:
            GWConsole_ProcessCommand();
            break;
        case 27:
            GWConsole_Toggle();
            break;
        case 38:
            GWConsole_PreviousCommand();
            e.preventDefault();
            break;    
        case 40:
            GWConsole_NextCommand();
            e.preventDefault();
            break;
    }
};

function GWConsole_ProcessCommand() {
    
    var re = new RegExp(/([a-z]+)(?: ([a-z\-]+))?/i);
    var result = re.exec(GWconsole_input.value);
    GWConsole_AddCommandToHistory(GWconsole_input.value);
    GWconsole_historyPosition = null;
    
    GWconsole_input.value = '';
    if (result === null) return;
    
    var command = result[1];
    var param = result[2];

    var curCommand = null;
    jQuery.each(GWConsoleCommands, function() {
        if (command == this.command) {
            curCommand = this;
        }
    });
    
    if (curCommand == null) 
        GWConsole_OutputAndScroll("Command '" + command + "' not found. Type 'help' for a list of commands");
    else 
        curCommand.func(param);
};

function GWConsole_AddCommandToHistory(cmd)
{
    var historyCount = GWconsole_commandHistory.length;
    if (historyCount == 0 || (historyCount > 0 && GWconsole_commandHistory[historyCount - 1] != cmd))
    {
        GWconsole_commandHistory.push(cmd);
    }
};

function GWConsole_PreviousCommand()
{
    if (GWconsole_commandHistory.length > 0)
    {
        GWconsole_historyPosition = (GWconsole_historyPosition == null) ? GWconsole_commandHistory.length : GWconsole_historyPosition;
        GWconsole_historyPosition = (GWconsole_historyPosition == 0) ? 0 : GWconsole_historyPosition - 1;
        GWconsole_input.value = GWconsole_commandHistory[GWconsole_historyPosition];
    }
};

function GWConsole_NextCommand()
{
    if (GWconsole_historyPosition != null && GWconsole_commandHistory.length > 0)
    {
        GWconsole_historyPosition++;
        if (GWconsole_historyPosition == GWconsole_commandHistory.length)
        {
            GWconsole_historyPosition = null;
            GWconsole_input.value = '';
        }
        else
        {
            GWconsole_input.value = GWconsole_commandHistory[GWconsole_historyPosition];
        }
    }
};

function GWConsole_UpdateWidth() {
    var docW = $(document).width();    
    $(GWconsole).width(docW);
};

function GWConsole_Output(msg) {
    $("#GWConsoleContent").append('<p>' + msg + '</p>');
};

function GWConsole_OutputAndScroll(msg)
{
    GWConsole_Output(msg);
    GWConsole_ScrollBottom();
};

function GWConsole_Clicked(e) {
    GWConsole_ScrollBottom();
};

function GWConsole_ScrollBottom() {
    $(GWconsole).attr({ scrollTop: $(GWconsole).attr("scrollHeight") });
    GWconsole_input.focus();
};

function GWConsole_Clear() {
    $("#GWConsoleContent").html("");
    $("#GWConsoleContent").append('<p><strong>' + welcomeTxt + '</strong></p>');
};


// Console Commands
function GWConsole_Command_ChangeColour(colour) {

    if (colour === undefined) {
        GWConsole_Output("You need to choose a colour!");
        GWConsole_Output("Type 'colour [colourChoice]' (options are green and pink)");
        GWConsole_ScrollBottom();
        return;
    }

    var code;
    switch (colour) {

        case 'pink':
            code = '#FF38DE';
            break;

        case 'green':
        default:
            code = 'lime';
            colour = 'green';
            break;
    }

    $(GWconsole).css('color', code);
    $(GWconsole_input).css('color', code);

    createCookie('GWCONSOLE_COLOUR', colour);
};

function GWConsole_Command_ToggleShortcut(option) {

    var shortcutEnabled = readCookie("GWCONSOLE_QUICKSHORTCUT");

    if (shortcutEnabled == 'true') {
        GWConsole_OutputAndScroll('Quick short has been disabled.');
        eraseCookie("GWCONSOLE_QUICKSHORTCUT");
        GWConsole_ToggleQuickShortcut(false);
    }
    else {
        GWConsole_OutputAndScroll('Quick shortcut enabled. To show/hide console press CTRL + ` (key to the left of 1).');
        createCookie("GWCONSOLE_QUICKSHORTCUT", "true");
        GWConsole_ToggleQuickShortcut(true);
    }   
}

function GWConsole_Command_Validate(option) {

    GWConsole_Clear();
    GWConsole_Output('Running all client side validations on form');

    var validator = new FormValidator('#frmMain');
    validator.Run();

    if (validator.HasErrors()) {
        var errors = validator.GetErrors();

        jQuery.each(errors, function(i, e) {
            GWConsole_Output(e.message);
        });

        GWConsole_OutputAndScroll('Validation Complete. ' + errors.length + ' error(s) were found');
    }
    else {
        GWConsole_OutputAndScroll('Yay! No errors found on form.');
    }


};

function GWConsole_Command_AutoComplete()
{
    GWConsole_Clear();
    GWConsole_Output("GradWeb AutoComplete");

    var inputCount = $("form#frmMain input[disabled!=disabled][type!=hidden][type!=submit][type!=button]").each(AutoComplete_Input).length;
    GWConsole_Output("AutoFilled " + inputCount + " input fields");

    var selectCount = $("form#frmMain select[disabled!=disabled]").each(AutoComplete_Select).length;
    GWConsole_Output("AutoFilled " + selectCount + " select fields");

    var textareaCount = $("form#frmMain textarea[disabled!=disabled]").each(AutoComplete_Textarea).length;
    GWConsole_Output("AutoFilled " + textareaCount + " textareas");

    GWConsole_Output("AutoComplete Complete - Type exit to close the console");
    GWConsole_ScrollBottom();
};

function GWConsole_Command_Close() {
    GWConsole_Toggle();
};

// AutoComplete Functions
function AutoComplete_Input() {

    var input = this;

    switch (input.type) {
        case 'text':
            var value;
            if ($(input).hasClass('hasDatepicker'))
                value = '17/03/1989';
            else
                value = AutoComplete_GenerateWords(5);

            input.value = value;

            break;

        case 'checkbox':
        case 'radio':
            if (input.parentNode.className != 'UDFDeleteCheckbox') input.checked = true;
            break;
    }
};

function AutoComplete_Select() {

    var select = this;
    var selectedIndex = Math.ceil(Math.random() * (select.length - 1));
    select.selectedIndex = selectedIndex;
};

function AutoComplete_Textarea() {
    var textarea = this;
    var re = new RegExp(/count\[([0-9]+)\]/);
    var result = re.exec(textarea.className);
    var numWords;

    if (result === null)
        numWords = 10;
    else
        numWords = parseInt(result[1], 10);


    textarea.value = AutoComplete_GenerateWords(numWords);
    textarea.focus();
    textarea.blur();
};

var words = ['apple', 'ball', 'car', 'dog', 'dinosaur', 'lollypop', 'water', 'feel', 'socks', 'face', 'glass', 'heart', 'trousers', 'job', 'zebra', 'nose', 'monkey', 'nice', 'olive', 'presto', 'queen', 'fun', 'solid', 'time'];
function AutoComplete_GenerateWords(numWords) {
    var str = '';

    for (i = 0; i < numWords; i++) {
        var num = Math.floor(Math.random() * (words.length-1));
        str += words[num] + ' ';
    }
    return str;
};

function GWConsole_SuperCorn()
{
    GWConsole_OutputAndScroll("<pre>"+sc+"</pre>");
}


// Cookie functions (from http://www.quirksmode.org/js/cookies.html)
function createCookie(name, value) {
    createCookieWithDays(name, value, 365)
};

function createCookieWithDays(name, value, days)
{
    if (days) {
        var date = new Date();
        date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
        var expires = "; expires=" + date.toGMTString();
    }
    else var expires = "";
    document.cookie = name + "=" + value + expires + "; path=/";
}

function readCookie(name) {
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for (var i = 0; i < ca.length; i++) {
        var 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 eraseCookie(name) {
    createCookieWithDays(name, "", -1);
}



function GWConsole_Command_ClearForm() {

    $("form#frmMain input").each(Clear_Input);
    $("form#frmMain select").each(Clear_Select);
    $("form#frmMain textarea").each(Clear_Textarea);
    GWConsole_Output("Form Reset - Type exit to close the console");
    GWConsole_ScrollBottom();
};

function Clear_Input() {
    var input = this;
    switch (input.type) {
        case 'text':
            input.value = '';
            break;
            
        case 'checkbox':
        case 'radio':
            input.checked = false;
            break;
    }
};

function Clear_Textarea() {
    this.value = '';
};

function Clear_Select() {
    this.selectedIndex = 0;
};

var sc ="      \\<br>       \\<br>        \\\\<br>         \\\\<br>          >\\/7<br>      _.-(6'  \\<br>     (=___._/` \\<br>          )  \\ |<br>         /   / |<br>        /    > /<br>       j    < _\\<br>   _.-' :      ``.<br>   \\ r=._\\        `.<br>  <`\\\\_  \\         .`-.<br>   \\ r-7  `-. ._  ' .  `\\<br>    \\`,      `-.`7  7)   )<br>     \\/         \\|  \\\\'  / `-._<br>                ||    .\\'<br>                 \\\\  (<br>                  >\\  ><br>              ,.-' >.\\'<br>             <.'_.\\'\\'<br>               <\\'<br>";
