/**
 * 1st Domains common scripts
 * Created by Chris Noel, Net24 Ltd.
 */

// TOP LEVEL VARIABLES

var unexpected_error_message = 'The system was unable to complete your request at this time please try again later!';

//  Is the browser supporting Javascript?
var w3c = (document.createElement && document.getElementsByTagName);

// Common key codes
var KEY = {
    TAB: 9,
    RETURN: 13,
    COMMA: 188,
    SPACEBAR: 32
};

// UTILITY FUNCTIONS ---------------------------------------------------------------

function javascriptAvailabilityTest()
{
    if(w3c)
    {
        if ($('#no_jscript').length)
        {
            $('#no_jscript').remove();
        }
        return true;
    }
    return false;
}

/**
 * Utility method for doing basic checking on a value harvested from a form input
 */
function parseFormInputValue(input_value)
{
    if(!w3c){return false;}
    if (typeof input_value == 'undefined'){return false;}
    return input_value.trim();
}

function empty( mixed_var ) {
    // http://kevin.vanzonneveld.net
    // +   original by: Philippe Baumann
    // +      input by: Onno Marsman
    // +   bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +      input by: LH
    // +   improved by: Onno Marsman
    // +   improved by: Francesco
    // *     example 1: empty(null);
    // *     returns 1: true
    // *     example 2: empty(undefined);
    // *     returns 2: true
    // *     example 3: empty([]);
    // *     returns 3: true
    // *     example 4: empty({});
    // *     returns 4: true

    var key;

    if (mixed_var === ""
        || mixed_var === 0
        || mixed_var === "0"
        || mixed_var === null
        || mixed_var === false
        || mixed_var === undefined
    ){
        return true;
    }
    if (typeof mixed_var == 'object') {
        for (key in mixed_var) {
            if (typeof mixed_var[key] !== 'function' ) {
              return false;
            }
        }
        return true;
    }
    return false;
}

function is_array (mixed_var) {
    // Returns true if variable is an array
    //
    // version: 909.322
    // discuss at: http://phpjs.org/functions/is_array
    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: Legaev Andrey
    // +   bugfixed by: Cord
    // +   bugfixed by: Manish
    // +   improved by: Onno Marsman
    // +   improved by: Brett Zamir (http://brett-zamir.me)
    // +   bugfixed by: Brett Zamir (http://brett-zamir.me)
    // %        note 1: In php.js, javascript objects are like php associative arrays, thus JavaScript objects will also
    // %        note 1: return true  in this function (except for objects which inherit properties, being thus used as objects),
    // %        note 1: unless you do ini_set('phpjs.objectsAsArrays', true), in which case only genuine JavaScript arrays
    // %        note 1: will return true
    // *     example 1: is_array(['Kevin', 'van', 'Zonneveld']);
    // *     returns 1: true
    // *     example 2: is_array('Kevin van Zonneveld');
    // *     returns 2: false
    // *     example 3: is_array({0: 'Kevin', 1: 'van', 2: 'Zonneveld'});
    // *     returns 3: true
    // *     example 4: is_array(function tmp_a(){this.name = 'Kevin'});
    // *     returns 4: false
    var key = '';
    var getFuncName = function (fn) {
        var name = (/\W*function\s+([\w\$]+)\s*\(/).exec(fn);
        if (!name) {
            return '(Anonymous)';
        }
        return name[1];
    };

    if (!mixed_var) {
        return false;
    }

    // BEGIN REDUNDANT
    this.php_js = this.php_js || {};
    this.php_js.ini = this.php_js.ini || {};
    // END REDUNDANT

    if (typeof mixed_var === 'object') {

        if (this.php_js.ini['phpjs.objectsAsArrays'] &&  // Strict checking for being a JavaScript array (only check this way if call ini_set('phpjs.objectsAsArrays', 0) to disallow objects as arrays)
            (
            (this.php_js.ini['phpjs.objectsAsArrays'].local_value.toLowerCase &&
                    this.php_js.ini['phpjs.objectsAsArrays'].local_value.toLowerCase() === 'off') ||
                parseInt(this.php_js.ini['phpjs.objectsAsArrays'].local_value, 10) === 0)
            ) {
            return mixed_var.hasOwnProperty('length') && // Not non-enumerable because of being on parent class
                            !mixed_var.propertyIsEnumerable('length') && // Since is own property, if not enumerable, it must be a built-in function
                                getFuncName(mixed_var.constructor) !== 'String'; // exclude String()
        }

        if (mixed_var.hasOwnProperty) {
            for (key in mixed_var) {
                // Checks whether the object has the specified property
                // if not, we figure it's not an object in the sense of a php-associative-array.
                if (false === mixed_var.hasOwnProperty(key)) {
                    return false;
                }
            }
        }

        // Read discussion at: http://kevin.vanzonneveld.net/techblog/article/javascript_equivalent_for_phps_is_array/
        return true;
    }

    return false;
}

function is_numeric (mixed_var) {
    // Returns true if value is a number or a numeric string
    //
    // version: 911.718
    // discuss at: http://phpjs.org/functions/is_numeric    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: David
    // +   improved by: taith
    // +   bugfixed by: Tim de Koning
    // +   bugfixed by: WebDevHobo (http://webdevhobo.blogspot.com/)    // +   bugfixed by: Brett Zamir (http://brett-zamir.me)
    // *     example 1: is_numeric(186.31);
    // *     returns 1: true
    // *     example 2: is_numeric('Kevin van Zonneveld');
    // *     returns 2: false    // *     example 3: is_numeric('+186.31e2');
    // *     returns 3: true
    // *     example 4: is_numeric('');
    // *     returns 4: false
    // *     example 4: is_numeric([]);    // *     returns 4: false
    return (typeof(mixed_var) === 'number' || typeof(mixed_var) === 'string') && mixed_var !== '' && !isNaN(mixed_var);
}

// Trim methods
String.prototype.trim = function()
{
    return this.replace(/^\s+|\s+$/g,"");
};

String.prototype.ltrim = function()
{
    return this.replace(/^\s+/,"");
};

String.prototype.rtrim = function()
{
    return this.replace(/\s+$/,"");
};

String.prototype.stripquotes = function()
{
    return this.replace(/[\"\']+/g,"");
};

String.prototype.trim_dots = function()
{
    return this.replace(/^\.|\.$/g,"");
};

String.prototype.chunk = function(chunk_size)
{
    var chunk_start = 0;
    var chunk_end = chunk_size;
    var chunks = new Array();

    while(chunk_end <= this.length)
    {
        chunks.push(this.substr(chunk_start, chunk_size));
        chunk_start = chunk_end;

        // Stop the while loop
        if (chunk_end == this.length)
        {
            chunk_end++;
        }
        else
        {
            chunk_end += chunk_size;
            if (chunk_end > this.length)
            {
                chunk_end = this.length;
            }
        }

    }
    return chunks;
};

// HELP FOUND HERE http://simonwillison.net/2006/Jan/20/escape/
function regexEscape(text)
{
    var special_chars = ['[', ']', '\\', '^', '$', '.', '|', '?', '*', '+', '(', ')'];
    var replace_regex = new RegExp('(\\' + special_chars.join('|\\') + ')', 'g');
    return text.replace(replace_regex, '\\$1');
}

// Legacy functions revised
var timerID = 0;

function xlaAFMlaunch(help_url)
{
    if (document.all)
    {
        windowheight = screen.availHeight;
        rightwidth=240;
        leftwidth=screen.availWidth-rightwidth-11;
        AFMwindow=window.open(help_url,'xlaAFM','width='+rightwidth+',height='+(windowheight-51)+',screenX='+leftwidth+',screenY=0,top=0,left=' +leftwidth+',toolbar=0,location=0,status=1,menubar=0,resizable=1');
        AFMwindow.focus();
        timerID = setInterval("CheckHelp();", 300);
        window.moveTo(0, 0);
        window.resizeTo(screen.availWidth - rightwidth - 11, screen.availHeight);
    }
    else
    {
        AFMwindow=window.open(help_url,'','width=240,height=480,toolbar=0,location=0,status=1,menubar=0,resizable=1');
    }
}

function CheckHelp()
{
    if (!(AFMwindow && AFMwindow.open && !AFMwindow.closed))
    {
        window.moveTo(0,0);
        window.resizeTo(screen.availWidth, screen.availHeight);
        clearInterval(timerID);
    }
}

// User feedback
function preparePageForAction()
{
    if(!w3c){return false;}
    $('#please_wait_table').hide();
    $('#messagebox').hide();
    $('#errorbox').hide();
    $(':input').attr('disabled', 'disabled');
}

function displayMessages(messages)
{
    // insert the new message
    $('#messagetext').html(messages);
    $('#messagebox').show();
}

function buildMessage(message)
{
    return '<li>' + message + '</li>' + "\n";
}

function buildError(message)
{
    return '<li>' + message + '</li>' + "\n";
}

// Primative function for displaying error messages on the page.
function displayErrors(errors)
{
    $('#errortext').html(errors);
    $('#errorbox').show();
}

function hideErrors()
{
    $('#errorbox').hide();
}

function initPleaseWaitMessageTable()
{
    if(!w3c){return false;}
    if ($('#please_wait_table').length){return false;}
    var messagetable = '<table id="please_wait_table" border="0" cellpadding="5" cellspacing="0" width="100%">';
    messagetable += '<tbody><tr bgcolor="#ffffff"><td class="red-header" bgcolor="#eeeeee" id="please_wait"></td></tr>';
    messagetable +=  '</tbody></table>';
    $('#domain_name_area').after(messagetable);
    $('#please_wait_table').hide();
}

function displayPleaseWaitMessage()
{
    if(!w3c){return false;}
    var message = "<span id='please_wait' class='red-header'><div style='float:left;'><img src='/images/ajax/ajax-loader.gif' /></div><div style='float:left;margin:1px 0px 0px 2px;'>Please Wait...</div></span><div style='clear:both;'/>";
    // insert the new message
    $('#please_wait').html(message);
    $('#please_wait_table').show();
}