/**
 * 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,
    ESCAPE: 27,
    BACKSPACE: 8,
    DELETE: 46
};

var hasFocus = '';

// 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().trim_quotes();
}

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 in_array (needle, haystack, argStrict) {
    // http://kevin.vanzonneveld.net
    // +   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;
}

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_quotes = 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');
}

function zeroPad(num,count)
{
var numZeropad = num + '';
while(numZeropad.length < count) {
numZeropad = "0" + numZeropad;
}
return numZeropad;
}

// 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()
{
    hideFeedback();
    $(':input').attr('disabled', 'disabled');
}

function buildMessage(message)
{
    return '<li class="green-check">' + message + '</li>' + "\n";
}

function prepMessages(built_messages, heading)
{
    if(!$('#user-feedback').length)
    {
        $('#form').prepend('<div id="user-feedback" class="hide-element"><div id="messagebox"><div class="feedback-block green-block"><div class="heading"></div><ul id="messagetext" class="content"></ul></div></div></div>'); 
    }
    else if(!$('#messagebox').length)
    {
        $('#user-feedback').prepend('<div id="messagebox"><div class="feedback-block green-block"><div class="heading"></div><ul id="messagetext" class="content"></ul></div></div>');
    }

    $('#messagebox').hide();
    $('#messagetext').html(built_messages);

    message_heading = empty(heading) ? ('Message' + ($('li', '#messagetext').length > 1 ? 's' : '')) : heading; 

    $('.heading', '#messagebox').text(message_heading);
    $('#messagebox').show();
}

function buildError(message)
{
    return '<li class="red-cross">' + message + '</li>' + "\n";
}

// Primative function for displaying error messages on the page.
function prepErrors(built_errors)
{
    if(!$('#user-feedback').length)
    {
        $('#form').prepend('<div id="user-feedback" class="hide-element"><div id="errorbox"><div class="feedback-block red-block"><div class="heading"></div><ul id="errortext" class="content"></ul></div></div></div>'); 
    }
    else if(!$('#errorbox').length)
    {
        $('#user-feedback').append('<div id="errorbox"><div class="feedback-block red-block"><div class="heading"></div><ul id="errortext" class="content"></ul></div></div>');
    }
    $('#errorbox').hide();
    $('#errortext').html(built_errors);
    $('.heading', '#errorbox').text('Error' + ($('li', '#errortext').length > 1 ? 's' : ''));
    $('#errorbox').show();
}

function hideFeedback()
{
    $('#user-feedback').hide();
    $('#errorbox').hide();
    $('#messagebox').hide();
}

function showFeedback()
{
    $('#user-feedback').show();
}

// Initialise the page

function basePageInit()
{
    if(javascriptAvailabilityTest() == false) return false;

    // Preload CSS background images
    $.preloadCssImages();
    
    // Help link
    if($('#help_dialog').length && help_url)
    {
        $('#help_dialog').show();
        $('#help_dialog').click(function(e)
        {
            xlaAFMlaunch(help_url);
            return false;
        });
    }
    
    // BUTTONS
    if($('.fg-button').length)
    {
        $('.fg-button').hover(
        	function(){ $(this).removeClass('ui-state-default').addClass('ui-state-focus'); },
        	function(){ $(this).removeClass('ui-state-focus').addClass('ui-state-default'); }
        );	
    }
}

// THE LOADING WIDGET FUNTIONS

function hideLoadingWidget()
{
    // THE LOADING WIDGET
    if ($('#jscript_loader').length)
    {
        //$('#jscript_loader').fadeOut(50, function(){$('#jscript_loader').addClass('hidden');$('#main-content-table').fadeIn(50);});
        $('#jscript_loader').addClass('hidden');
        $('#main-content-table').removeClass('hide-element');;
    }
    
    return true;
}

function showLoadingWidget()
{
    // show the loading image.
    if ($('#jscript_loader').length)
    {
        //$('#main-content-table').fadeOut(50, function(){$('#jscript_loader').removeClass('hidden');$('#jscript_loader').fadeIn(50);});
        $('#main-content-table').addClass('hide-element');
        $('#jscript_loader').removeClass('hidden');
    }
    
    return true;
}

