
if (typeof Gangta == 'undefined' || !Gangta) {
    var Gangta = {
        version: '0.1'
    };
}

/**
 * User Interface Controls
 */
Gangta.UI = Gangta.UI || {
    
    /**
     * 
     */
    Dialog: {
        NONE: 0,
        OK_CANCEL: 1,
        YES_NO: 2,
        ACCEPT_CANCEL: 3,
        CLOSE: 4,
        create: function() {
            
        },
        show: function(options) {
            /*
            
            options['content'] = 'Hello World';
            options['show_for'] = 3; // Show for 3 seconds then hide
            options['load'] = '/members/online';
            options['onclose'] = function() { alert('It closed!'); };
            options['onload'] = function() {  }; // Can be used for the ajax onLoad
            options['type'] = Dialog.OK_CANCEL; // Different dialog types.  Default is NONE
            
            */
        },
        hide: function() {
            
        }
    },
    
    /**
     * Form class
     */
    Form: {
        /**
         * Create a textarea element
         */
        Textarea: Class.create({
            initialize: function(options) {
                this.options = options;
                
                // create element
                
                // use options to set attributes
            },
            /**
             * Calculate and return the number of new lines.  Used when expanding the height to show all text without scroll
             */
            getNewLines: function() {
                
            },
            setHeight: function(height) {
                
            },
            onChange: function() {
                // if options['scrolling'] == 'no'
                  // calculate number of lines
                  // set new height if necessary
                // end if
                
                // if options['charlimit'] > 0
                  // check whether num of chars exceeds limit
                // end if
            }
        })
    },
    /**
     * Functions to be used on elements
     */
    elementExtends: {
        /**
         * Disable text highlighting
         *
         * Example Usage:
         *
         * $('myDiv').disableHighlighting();
         */
        disableHighlighting: function(element) {
            element = $(element);
            element.onselectstart = function(){ return false; }; // ie
            element.onmousedown = function(){ return false; }; // moz
            return element;
        },
        /**
         * Enable text highlighting (See disableHighlighting for an example)
         */
        enableHighlighting: function(element) {
            element = $(element);
            element.onselectstart = function(){ return true; }; // ie
            element.onmousedown = function(){ return true; }; // moz
            return element;
        },
        /**
         * Adds boxOver tooltip syntax to the title attribute
         */
        addTooltip: function(element, header_text, body_text) {
            element = $(element);
            element.setAttribute('title', 'header=[' + header_text + '] body=[' + body_text + ']');
            return element;
        }
    }
};

// Add new $(element).   methods
Element.addMethods(Gangta.UI.elementExtends);

// Will make it easier to call Dialog.show()
var Dialog = Dialog || Gangta.UI.Dialog;




/**
 * Handles all page stuff
 */

Gangta.Page = Gangta.Page || {
    loadJS: function(url) {
        
        var script = document.createElement('script');
        script.src = url;
        script.type = 'text/javascript';
        document.body.appendChild(script);
    },
    loadCSS: function(url) {
        //TODO: document.write('<script type="text/javascript" src="' + url + '"><\/script>');
    },
    redirect: function(url) {
        if (url == 'self') {
            url = get_file_name();
        }
        if (url.indexOf('http://') == -1) {
            url = web_root + url;
        }
        self.location = url;
        return;
    }
};

Gangta.Controller = Class.create({
    initialize: function() {

        // Start page updater (stats, messages, news, etc)
        
        // Load notifier (check for idleness/activeness)
        new Notifier(300000);

    	document.observe('state:idle', this.notifierOnIdle.bind(this))
                .observe('state:active', this.notifierOnActive.bind(this));
    },
    /**
     * Abstract, can be overwritten in child classes
     */
    notifierOnIdle: function() {},
    notifierOnActive: function() {}
});


/* toggle news button */
function toggle_news_button(pe) {
    if ($('news-button').hasClassName('flash')) {
        $('news-button').removeClassName('flash');
    } else {
        $('news-button').addClassName('flash');
    }
}
/* toggle message button */
function toggle_message_button(pe) {
    if ($('message-button').hasClassName('flash')) {
        $('message-button').removeClassName('flash');
    } else {
        $('message-button').addClassName('flash');
    }
}
/* toggle posts button */
function toggle_posts_button(pe) {
    if ($('posts-button').hasClassName('flash')) {
        $('posts-button').removeClassName('flash');
    } else {
        $('posts-button').addClassName('flash');
    }
}

/* Navigation */
function nav_on(elem) {  elem.setAttribute('defColour', elem.style.backgroundColor); elem.style.backgroundColor = '#666666'; return; }
function nav_off(elem) { elem.style.backgroundColor = elem.getAttribute('defColour'); return; }

var checkflag = false;
function check(field) {
    if (checkflag == false) {
        for (var i=0,len=field.length;i<len;++i) {
            field[i].checked = true;
        }
        checkflag = true;
        return 'Uncheck All';
    } else {
        for (var i=0,len=field.length;i<len;++i) {
            field[i].checked = false;
        }
        checkflag = false;
        return 'Check All';
    }
}

/**
 * Get the user to confirm their choice before executing
 */
function confirmChoice() { return (confirm('Are you sure?')) ? true : false; }

function checkBox(value) { if (value == 0) { alert('Choose from the list'); return false; } else { return true; } }

/**
 * Mainly for robbery but could make a general one that will work for anything
 */
function showhide(value, value_array) {
    for (var i=0,len=value_array.length;i<len;i++) {
        var element;
        obj = $('id'+value_array[i]);
        obj.style.display = 'none';
    }
    if (value != '0') {
        obj = $('id'+value);
        obj.style.display = 'block';
    }
}

function commas(number) {
    number = ''+number; // Force it to become a string
    if (number.length > 3) {
        var mod = number.length%3;
        var output = (mod > 0 ? (number.substring(0, mod)) : '');
        
        for (var i=0,len=Math.floor(number.length/3);i < len;i++) {
            if ((mod == 0) && (i == 0)) {
                output += number.substring(mod+3*i, mod+3*i+3);
            } else {
                output += ','+number.substring(mod+3*i, mod+3*i+3);
            }
        }
        return(output);
    } else {
        return number;
    }
}

function stripslashes(str) {
    str = str.replace(/\\'/g,'\'');
    str = str.replace(/\\"/g,'"');
    str = str.replace(/\\\\/g,'\\');
    str = str.replace(/\\0/g,'\0');
    return str;
}

function StartTimer() {
    setTimeout("UpdateTimer()", 1024);
    resetmin = 5;resetsec = 0;
    if (min < 0) {
        min = resetmin;
        sec = resetsec;
    }
    if (sec < 10) {
        temp = '0';
    } else {
        temp = '';
    }
    $('idTimer').innerHTML = '<span id="idMin" style="font-weight: normal;font-size: 11px">'+min+'</span> min(s) <span id="idSec" style="font-weight: bold;font-size: 11px">'+temp+sec+'</span> sec';
}

var t_red = 255; var t_green = 255; var t_blue = 255;
function UpdateTimer() {
    setTimeout('UpdateTimer()', 1024);

    sec--;
    if (min == 0 && sec == 0) {
        min = resetmin;
        sec = resetsec;
        $('idTimer').style.color = 'rgb(255,255,255)';
        t_red = 255; t_green = 255; t_blue = 255;
    }
    if (sec < 0) {
        sec = 59;
        min--;
    }
    $('idMin').innerHTML = min;

    var temp;
    if (sec < 10) {
        temp = '0';
    } else {
        temp = '';
    }
    temp = temp+sec;
    $('idSec').innerHTML = temp;
    
    if (min == 0 && sec <= 10)
    {
        if (sec < 5)
        {
            t_red -= 5;
        }
        t_green -= (sec > 4) ? 25 : 7;
        t_blue -= (sec > 4) ? 25 : 7;
        $('idTimer').style.color = 'rgb('+t_red+','+t_green+','+t_blue+')';
    }
}


/**
 * ajax functions
 */
// perform request
function gMSG_request(file, url) {
    new Ajax.Request(file+'?'+url,
      {
        method: 'get',
        onSuccess: function(transport){ MSG_onComplete(transport) },
        onFailure: function(){ MSG_onFailure() },
        onLoading: function(){ MSG_onLoading() }
      });
    return;
}
function gta_ajax(url, request_method) {
    new Ajax.Request(url,
      {
        method: request_method,
        onSuccess: function(transport){ MSG_onComplete(transport) },
        onFailure: function(){ MSG_onFailure() },
        onLoading: function(){ MSG_onLoading() }
      });
    return;
}
function gta_get_ajax(url) { gta_ajax(url, 'get'); }
// Show message, update token
function MSG_show(msg) {
    if (msg['token'] != "") {
        for (var i = 0,len = document.forms.length;i < len;++i) {
            if (isset(document.forms[i].token)) {
                document.forms[i].token.value = msg['token'];
            }
        }
    }
    var text = (msg['msg'] != "") ? msg['msg'] : msg;

    $('gMsg').innerHTML = text;
    $('gMsg').style.display = 'block';
    setTimeout("$('gMsg').fade();", 3000);
    return;
}

function MSG_onComplete(transport) {
    if (typeof transport != 'undefined') {
        var response = get_response(transport.responseText);
        MSG_show(response);
    }
}
// Decode ajax response
function get_response(msg) {
    if (msg.indexOf("#sep#") == -1) {
        return msg;
    }
    var response = new Array();
    var msg_split = msg.split("#sep#");
    for (var i = 0,len = msg_split.length;i < len;++i) {
        var item_split = msg_split[i].split(":val:");
        if (item_split[1] != "") {
            response[item_split[0]] = item_split[1];
        }
    }
    return response;
}

function MSG_onFailure() {
    alert('Something went wrong.  Try again, if the problem persists contact a member of staff.');
}
function MSG_onLoading() {
    $('gMsg').innerHTML = '';
    $('gMsg').style.display = 'block';
    var div = document.createElement('div');
    div.className = 'page_msg_container';
    //div.style.background = '#353535 url(images/icons/loading.gif) no-repeat 3px 3px';
    div.style.backgroundColor = '#353535';
    div.style.backgroundImage = 'url(images/icons/loading.gif)';
    div.style.backgroundRepeat = 'no-repeat';
    div.style.backgroundPosition = '3px 3px';

    var div2 = document.createElement('div');
    div2.className = 'page_msg_inner1';

    var div3 = document.createElement('div');
    div3.className = 'page_msg_inner2';

    var span = document.createElement('span');
    span.className = 'var';
    span.innerHTML = 'Loading...';

    var div_clear = document.createElement('div');
    div_clear.clear = 'both';
    
    div3.appendChild(span);
    div3.appendChild(div_clear);
    div2.appendChild(div3);
    div.appendChild(div2);
    
    $('gMsg').appendChild(div);
}


/**
 * displays js array
 */
function print_r(theObj){
  if(theObj.constructor == Array ||
     theObj.constructor == Object){
    document.write("<ul>")
    for(var p in theObj){
      if(theObj[p].constructor == Array||
         theObj[p].constructor == Object){
document.write("<li>["+p+"] => "+typeof(theObj)+"</li>");
        document.write("<ul>")
        print_r(theObj[p]);
        document.write("</ul>")
      } else {
document.write("<li>["+p+"] => "+theObj[p]+"</li>");
      }
    }
    document.write("</ul>")
  }
}


/**
 * Get the filename for the document
 */
function get_file_name() {
    var file_name = document.location.href;
    var end = (file_name.indexOf('?') == -1) ? file_name.length : file_name.indexOf('?');
    return file_name.substring(file_name.lastIndexOf('/')+1, end);
}

/**
 * Redirect to a url
 */
function rd(url) {
    if (url == 'self') {
        url = get_file_name();
    }
    if (url.indexOf('http://') == -1) {
        url = web_root + url;
    }
    self.location = url;
    return true;
}

/**
 * Count how many characters there are in a textarea form element
 */
function textarea_counter(field, countfield, maxlimit) {
    // This fixes a problem with new line stuff with firefox and I.E
    var field_len = field.value.length - (field.value.length - field.value.replace("\r\n", '').length);

    if (field_len > maxlimit) {
        field.value = field.value.substring(0, maxlimit);
    } else {
        countfield.value = maxlimit - field_len;
    }
}

/* Prototype addons */
String.prototype.trim = function() { return this.replace(/^\s+|\s+$/, ''); };

function isset(varname) { return (typeof(window[varname]) != 'undefined' && typeof(eval(varname) != 'undefined')); }


function urldecode( str ) {
    // http://kevin.vanzonneveld.net
    // +   original by: Philip Peterson
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +      input by: AJ
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: Brett Zamir
    // %          note: info on what encoding functions to use from: http://xkr.us/articles/javascript/encode-compare/
    // *     example 1: urldecode('Kevin+van+Zonneveld%21');
    // *     returns 1: 'Kevin van Zonneveld!'
    // *     example 2: urldecode('http%3A%2F%2Fkevin.vanzonneveld.net%2F');
    // *     returns 2: 'http://kevin.vanzonneveld.net/'
    // *     example 3: urldecode('http%3A%2F%2Fwww.google.nl%2Fsearch%3Fq%3Dphp.js%26ie%3Dutf-8%26oe%3Dutf-8%26aq%3Dt%26rls%3Dcom.ubuntu%3Aen-US%3Aunofficial%26client%3Dfirefox-a');
    // *     returns 3: 'http://www.google.nl/search?q=php.js&ie=utf-8&oe=utf-8&aq=t&rls=com.ubuntu:en-US:unofficial&client=firefox-a'
    
    var histogram = {};
    var ret = str.toString();
    
    var replacer = function(search, replace, str) {
        var tmp_arr = [];
        tmp_arr = str.split(search);
        return tmp_arr.join(replace);
    };
    
    // The histogram is identical to the one in urlencode.
    histogram["'"]   = '%27';
    histogram['(']   = '%28';
    histogram[')']   = '%29';
    histogram['*']   = '%2A';
    histogram['~']   = '%7E';
    histogram['!']   = '%21';
    histogram['%20'] = '+';
 
    for (replace in histogram) {
        search = histogram[replace]; // Switch order when decoding
        ret = replacer(search, replace, ret) // Custom replace. No regexing   
    }
    
    // End with decodeURIComponent, which most resembles PHP's encoding functions
    ret = decodeURIComponent(ret);
 
    return ret;
}

function in_array (needle, haystack, argStrict) {
    // Checks if the given value exists in the array  
    // 
    // version: 1006.1915
    // discuss at: http://phpjs.org/functions/in_array    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: vlado houba
    // +   input by: Billy
    // +   bugfixed by: Brett Zamir (http://brett-zamir.me)
    // *     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;
}