/**
 * Pelmorex object. This objects provides generic functions that can be re-used
 * and creates a namespace to prevent conflicts with other JavaScript
 * libraries.
 *
 * @fileoverview
 * This is the source file for the generic Pelmorex object.
 *
 * @author Jim Ing (jing@pelmorex.com)
 *
 * @static
 *
 * @property {boolean}  debug               Enable (true) or disable (false) Firebug console logging
 * @property {object}   console             Enable (true) or disable (false) logging levels
 * @property {string}   lang                Language code: [en | fr] = [English | French]
 * @property {string}   dateFormat          Date format code: [locale | utc | {blank}] = [locale string | UTC/GMT | yyyy/mm/dd hh:nn:ss AM/PM]
 *
 * @property {object}   _jsr                Stores a JSR object
 * @property {boolean}  _qsArgs             Stores query string arguments
 * @property {boolean}  _pngFix             Enable (true) or disable (false) PNG fix for IE
 */
var Pmx =
{
/*
    debug                   : true,
    console                 :
    {
        debug               : true,
        log                 : true,
        info                : true,
        warn                : true,
        error               : true
    },
*/
    debug                   : false,
    console                 :
    {
        debug               : false,
        log                 : false,
        info                : false,
        warn                : false,
        error               : false
    },

    lang                    : 'en',
    //lang                    : 'fr',
    dateFormat              : 'locale',

    _jsr                    : null,
    _qsArgs                 : [],

    _pngFix                 : false,

    /**
     * @description
     * Converts decimal to hex.
     */
    decToHex : function( num )
    {
        return num.toString( 16 );
    },

    /**
     * @description
     * Returns a formatted date string.
     * <pre>
     * +---------+---------------------------------------------------------------------+
     * |  Code   |                               Format                                |
     * +---------+---------------------------------------------------------------------+
     * | locale  | User's locale (defined in Regional Settings under Control Panel)    |
     * |         | e.g.,                                                               |
     * |         |     English (Canada)         - December 19, 2007 11:12:00 AM        |
     * |         |     English (United Kingdom) - 19 December 2007 11:12:00            |
     * |         |     French (Canada)          - 19 decembre 2007 11:12:00            |
     * |         |     German (Germany)         - Mittwoch, 19. Dezember 2007 11:12:00 |
     * +---------+---------------------------------------------------------------------+
     * | utc     | 2007/12/19 04:12:00 PM (GMT)                                        |
     * +---------+---------------------------------------------------------------------+
     * | {blank} | 2007/12/19 11:12:00 AM                                              |
     * +---------+---------------------------------------------------------------------+
     * </pre>
     *
     * @param {object} date_obj
     *
     * @return {string} A formatted date.
     *
     * @example
     * Pmx.dateFormat = 'locale';
     * Pmx.formatDate();
     */
    formatDate : function( date_obj )
    {
        var date_fmt = '';

        if( Pmx.dateFormat == 'locale' )
        {
            return date_obj.toLocaleString();
        }
        else if( Pmx.dateFormat == 'utc' )
        {
            if( date_obj )
            {
                var yyyy_utc = date_obj.getUTCFullYear();
                var mm_utc = Pmx.zeroPad( ( date_obj.getUTCMonth() + 1 ), 2 );
                var dd_utc = Pmx.zeroPad( date_obj.getUTCDate(), 2 );

                // format hours in 12-hour time
                var ampm_utc;
                var hh_utc = date_obj.getUTCHours();
                if( hh_utc === 0 )
                {
                    hh_utc = 12;
                    ampm_utc = 'AM';
                }
                else if( hh_utc > 0 && hh_utc < 12 )
                {
                    ampm_utc = 'AM';
                }
                else if( hh_utc == 12 )
                {
                    ampm_utc = 'PM';
                }
                else
                {
                    hh_utc = hh_utc - 12;
                    ampm_utc = 'PM';
                }
                hh_utc = Pmx.zeroPad( hh_utc, 2 );
                var nn_utc = Pmx.zeroPad( date_obj.getUTCMinutes(), 2 );

                date_fmt = yyyy_utc + '/' + mm_utc + '/' + dd_utc + ' ' + hh_utc + ':' + nn_utc + ' ' + ampm_utc + ' (GMT)';
            }

            return date_fmt;
        }
        else
        {
            if( date_obj )
            {
                var yyyy = date_obj.getFullYear();
                var mm = Pmx.zeroPad( ( date_obj.getMonth() + 1 ), 2 );
                var dd = Pmx.zeroPad( date_obj.getDate(), 2 );

                // format hours in 12-hour time
                var ampm;
                var hh = date_obj.getHours();
                if( hh === 0 )
                {
                    hh = 12;
                    ampm = 'AM';
                }
                else if( hh > 0 && hh < 12 )
                {
                    ampm = 'AM';
                }
                else if( hh == 12 )
                {
                    ampm = 'PM';
                }
                else
                {
                    hh = hh - 12;
                    ampm = 'PM';
                }
                hh = Pmx.zeroPad( hh, 2 );
                var nn = Pmx.zeroPad( date_obj.getMinutes(), 2 );

                // get timezone offset in hours
                var tz = date_obj.getTimezoneOffset() / 60;
                if( tz < 0 )
                {
                    tz = '+' + Math.abs( tz );
                }
                else
                {
                    tz = '-' + Math.abs( tz );
                }

                //date_fmt = yyyy + '/' + mm + '/' + dd + ' ' + hh + ':' + nn + ' ' + ampm + ' (GMT' + tz + ')';
                date_fmt = yyyy + '/' + mm + '/' + dd + ' ' + hh + ':' + nn + ' ' + ampm;
            }

            return date_fmt;
        }
    },

    /**
     * @description
     * Converts hex to decimal.
     */
    hexToDec : function( num )
    {
        return parseInt( num, 16 );
    },

    init : function()
    {
        console.debug( 'Initialized!' );
    },

    /**
     * @description
     * Initialize whether the client's browser requires a PNG fix for IE 5.5/6.0 or not.
     */
    initPngFix : function()
    {
        if( window.navigator.appVersion.indexOf( 'MSIE 6' ) != -1 || window.navigator.appVersion.indexOf( 'MSIE 5.5' ) != -1 )
        {
            Pmx._pngFix = true;
        }
    },

    /**
     * @description
     * Initializes the query string property with the name/value pairs. To
     * access the query string arguments from a URL like this:
     * index.html?lat=43.54916825665955&lon=-79.74538385868074&zoom=13&mapStyle=s
     * just reference the named argument in the _qsArgs property.
     *
     * @example
     * Pmx.Map.latitude = Pmx._qsArgs.lat;
     * Pmx.Map.longitude = Pmx._qsArgs.lon;
     * Pmx.Map.zoomLevel = Pmx._qsArgs.zoom;
     * Pmx.Map.mapStyle = Pmx._qsArgs.mapStyle;
     */
    initQueryString : function()
    {
        var query = window.location.search.substring( 1 );
        var parms = query.split( '&' );
        for( var i = 0; i < parms.length; i++ )
        {
            var pos = parms[ i ].indexOf( '=' );
            if( pos > 0 )
            {
                var key = parms[ i ].substring( 0, pos );
                var val = parms[ i ].substring( pos + 1 );
                Pmx._qsArgs[ key ] = val;
                //console.debug( key + ' = ' + val );
            }
        }
    },

    /**
     * @description
     * Convert a Pelmorex date string to a UTC date object.
     *
     * <pre>
     * Format: dd mm yy hh nn
     *          |  |  |  |  +--- minutes
     *          |  |  |  +------ hours
     *          |  |  +--------- year (offset from 1995)
     *          |  +------------ month
     *          +--------------- day
     * </pre>
     *
     * @param {string} date_str
     *
     * @return {object} A UTC date object.
     */
    parsePmxDate : function( date_str )
    {
        var date_obj;

        if( date_str.length == 10 )
        {
            var dd = parseInt( date_str.substr( 0, 2 ), 10 );
            var mm = parseInt( date_str.substr( 2, 2 ), 10 );
            var yy = parseInt( date_str.substr( 4, 2 ), 10 );
            var hh = parseInt( date_str.substr( 6, 2 ), 10 );
            var nn = parseInt( date_str.substr( 8, 2 ), 10 );
            var ss = 0;

            // PMX year is offset from 1995
            var yyyy = 1995 + yy;

            // convert string format to UTC date object
            date_obj = new Date( Date.UTC( yyyy, ( mm - 1 ), dd, hh, nn, ss ) );
        }

        return date_obj;
    },

    /**
     * @description
     * Converts an RGB string to hex format.
     * e.g., rgb( 0, 0, 0 ) to #000000
     *
     * @param {object} elem
     */
    rgb2hex : function( str )
    {
        str = str.replace(/rgb\(|\)/g, "").split(",");
        str[0] = parseInt(str[0], 10).toString(16).toLowerCase();
        str[1] = parseInt(str[1], 10).toString(16).toLowerCase();
        str[2] = parseInt(str[2], 10).toString(16).toLowerCase();
        str[0] = (str[0].length == 1) ? '0' + str[0] : str[0];
        str[1] = (str[1].length == 1) ? '0' + str[1] : str[1];
        str[2] = (str[2].length == 1) ? '0' + str[2] : str[2];

        return ('#' + str.join(""));
    },

    /**
     * @description
     * Toggle the debug property.
     *
     * @param {object} elem
     */
    toggleDebug : function( elem )
    {
        if( elem )
        {
            if( elem.checked )
            {
                Pmx.debug = true;
            }
            else
            {
                Pmx.debug = false;
            }
        }
    },

    /**
     * @description
     * Toggle the console log type property.
     *
     * @param {object} elem
     * @param {string} code
     */
    toggleLogType : function( elem, code )
    {
        if( elem && code )
        {
            if( elem.checked )
            {
                Pmx.console[ code ] = true;
            }
            else
            {
                Pmx.console[ code ] = false;
            }
        }
    },

    /**
     * @description
     * Zero-pad a positive integer.
     *
     * @param {integer} number
     * @param {integer} length
     *
     * @return {string} A zero-padded string
     */
    zeroPad : function( number, length )
    {
        number = String( number );
        var zeros = [];
        for( var i = 0; i < length; ++i )
        {
            zeros.push( '0' );
        }
        return zeros.join( '' ).substring( 0, length - number.length ) + number;
    }
};
