
var OTOS = window.OTOS || {};
OTOS.Util = function () {

    return {

        /**
         * Adds a function to window's onload-event.
         *
         * @param   {function}  myfunc  The function to add to window's onload -event
         */
        addOnload: function (myfunc) {

            if (window.addEventListener) { // w3c
                window.addEventListener('load', myfunc, false);
            } else if(window.attachEvent) { // ie
                window.attachEvent('onload', myfunc);
            } // else if

        },


        /**
         * Removes leading whitespaces
         *
         * @param   {string}    str     The string to be handled
         */
        lTrim: function (str) {

            if (str && str.length > 0) {
                var re  = /\s*((\S+\s*)*)/;
                str   = str.replace(re, "$1");
            } // if

            return str;

        },


        /**
         * Removes trailing whitespaces
         *
         * @param   {string}    str     The string to be handled
         */
        rTrim: function (str) {

            if (str && str.length > 0) {
                var re = /((\s*\S+)*)\s*/;
                str.replace(re, "$1");
            } // if

            return str;

        },


        /**
         * Removes leading and trailing whitespaces
         *
         * @param   {string}    str     The string to be handled
         */
        trim: function (str) {
            return OTOS.Util.lTrim(OTOS.Util.rTrim(str));
        },


        /**
         * Updates the dropdownlist with the hours. If the hour-period is chosen
         * from the periods-dropdown, we'll enable the hour-dropdown and disable
         * otherwise.
         */
        updateHours: function () {

            var period = $F('lstPeriods');

            if (period == 'HOUR') {

                $('lstTimes').disabled = false;

                var myDate  = new Date();
                var hours   = OTOS.Util.checkTime(myDate.getHours());

                OTOS.FormElement.selectOptionByValue($('lstTimes'), hours);
                OTOS.ElementConfig.HOUR = hours;

            } else {
                $('lstTimes').disabled = true;
            } // else

        },


        /**
         * Adds a leading zero to the number if the number's lenght < 2 chars (the number is smaller
         * than 10).
         *
         * @param   {integer)   i   The number to process.
         * @return  The number with a leading zero (if num < 10)
         * @type    {string}
         */
        checkTime: function (i) {
            return ((i < 10) ? '0' + i : i);
        },


        /**
         * Changes the selected language by setting the language code into a cookie
         * variable. After changing, refreshes the browser.
         *
         * @param   {string}    code    The language code (fi, en etc)
         */
        changeLanguage: function (code) {
            OTOS.Util.createCookie('otos_lang', code, 0);
            window.location.reload();
        },


        /**
         * Creates a cookie
         *
         * @param   {string}    name    The name of the cookie variable
         * @param   {string}    value   The value for the cookie
         * @param   {string}    days    The number of days the cookie to exist
         */
        createCookie: function (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 = "";
            } // else

            document.cookie = name + "=" + value + expires + "; path=/";

        },


        /**
         * Returns the cookie variable's value
         *
         * @param   {string}    name    The name of the cookie
         * @return  The value of the cookie
         * @type    {string}
         */
        readCookie: function (name) {

            var nameEQ  = name + "=",
                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);
                } // while

                if (c.indexOf(nameEQ) == 0) {
                    return c.substring(nameEQ.length, c.length);
                } // if

            } // for

            return null;

        },


        /**
         * Removes a cookie
         *
         * @param   {string}    name    The name of the cookie
         */
        eraseCookie: function (name) {
            OTOS.Util.createCookie(name, "", -1);
        },


        /**
         * Checks if a value exists in an array
         *
         * @param   {mixed}     needle      The value that we're searching
         * @param   {array}     haystack    The array to be searched
         * @return  True, if the value exists and false otherwise
         * @type    {boolean}
         */
        in_array: function (needle, haystack) {

            for (var i = 0; i < haystack.length; i++) {
                if (haystack[i] == needle) {
                    return true;
                } // if
            } // for

            return false;

        },


        /**
         * Displays the progress bar
         */
        showProgressBar: function () {

            if ($('progressBar') == undefined) {

                var pb = Builder.node('div', {
                        id: 'progressBar',
                        style: 'display: none'
                    }, [
                        'Ladataan...',
                        Builder.node('img', { src: 'images/bigrotation2.gif' })
                    ]);

                document.getElementsByTagName('body')[0].appendChild(pb);

                new Effect.Opacity(pb, {
                        from: 0.0,
                        to: 0.8,
                        duration: 0.2,
                        transition: Effect.Transitions.linear,
                        beforeStart: function (obj) { Element.show(obj.element); }
                    });

            } // if

        },


        /**
         * Hides the progress bar
         */
        hideProgressBar: function () {

            var count = Ajax.activeRequestCount;

            if (count == 0) {

                var pb = $('progressBar');
                new Effect.Opacity(pb, {
                        from: 0.8,
                        to: 0.0,
                        duration: 0.2,
                        transition: Effect.Transitions.linear,
                        afterFinish: function (obj) {
//                             Element.hide(obj.element);
                            Element.remove(pb);
                        }
                    });

            } // if

        },


        /**
         * Get's the size of the object, ie. the number of properties
         *
         * @param   {object}    obj     The object
         * @return  The size of the object
         * @type    {int}
         */
        getObjectSize: function (obj) {

            var counter = 0;

            for (var i in obj) {
                counter++;
            } // for

            return counter;

        },


        /**
         * Opens a new browser window
         *
         * @param   {string}    url     The url of the page that is loaded to the new window
         * @param   {string}    name    The name for the new window
         * @param   {int}       width   The width of the new window
         * @param   {int}       height  The height of the new window
         */
        openWindow: function (url, name, width, height) {
            var settings = "toolbar=no, location=no, directories=no, status=no, menubar=no, scrollbars=yes, resizable=yes, width=" + width + ", height=" + height;
            var myNewWindow = window.open(url, name, settings);
        },


        /**
         * Hides and displays the content area of the navigation box. This happens when a certain
         * element has been clicked.
         *
         * @param   {element}   el  The element that has been clicked
         */
        toggleNavBox: function (el) {
            Element.toggle(document.getElementsByClassName('navContent', OTOS.Dom.getFirstAncestorByClassName(el, 'navBox'))[0]);
            el.firstChild.nodeValue = (el.firstChild.nodeValue == '\u25BC') ? '\u25C0' : '\u25BC';
        },


        /**
         * Checks, whether a string is an empty string, ie. it contains nothing
         * or only whitespaces
         *
         * @return  True, if the string is empty and false otherwise
         * @type    {boolean}
         */
        isEmpty: function (str) {
            return (OTOS.Util.trim(str) == '') ? true : false;
        },


        /**
         * Checks whether the user is authenticated or not and calls the
         * callback function after the check.
         *
         * @param   {function}  callback    The function to be called after the check.
         *                                  The callback function must take the request-object
         *                                  as a parameter. The request-object's responseText-
         *                                  property contains a string formatted as follow:
         *                                  isAdmin (boolean)###isUser (boolean)
         */
        checkAuthentication: function (callback) {
            var myAjax  = new Ajax.Request(
                'xmlHttpFunctions.php', {
                    method: 'post',
                    postBody: 'checkAuthentication=1',
                    onSuccess: function (request) { callback(request); },
                    asynchronous: true
                });
        },


        /**
         * Gets all the server data from the database and then calls the ElementConfig's init-function.
         * The init-function takes the request-object and a callback function as its parameters.
         *
         * @param   {function}  callback    The callback function to be called int the init-function
         */
        getServerData: function (callback) {
            var myAjax = new Ajax.Request(
                'xmlHttpFunctions.php', {
                    method: 'post',
                    postBody: 'getServerData=1',
                    onSuccess: function (request) { OTOS.ElementConfig.init(request, callback); },
                    asynchronous: true
                });
        },


        /**
         * Checks whether the user has a permission for a certain component (browser, report_types).
         *
         * @param   {string}    event       The component which permission we're checking
         * @param   {function}  callback    The function that handles the response of
         *                                  the request. The request-object's responseText-property
         *                                  contains a string formatted as follows:
         *                                  hasPermission (boolean)###isUser (boolean)###isAdmin (boolean)
         */
        checkPermission: function (component, callback) {
            var myAjax  = new Ajax.Request(
                    'xmlHttpFunctions.php', {
                        method: 'post',
                        postBody: 'checkPermission=' + component,
                        onSuccess: function (request) { callback(request); },
                        asynchronous: true
                    });
        },


        /**
         * Creates an array with numbers from begin to end
         *
         * @param   {int}   begin   The start of the range
         * @param   {int}   end     The end of the range
         * @return  An array containing the numbers from begin to end
         * @type    {array}
         */
        range: function (begin, end) {

            var range = [];

            for (var i = begin; i <= end; i++) {
                range.push(i);
            } // for

            return range;

        },


        /**
         * Parses the date and time information out of an url of an image and returns an object
         * with the date information.
         *
         * @param   {string}    url     The url of the image, for example
         *                              http://domainname/otos/getSnapshot.php?
         *                              server=10.10.10.253&image=/otos/analyzing_images/
         *                              recorder/0014D18A2F45-0/20061127/thumbnails/130149.jpg
         * @return  An object containing the date and time information. The object has properties year,
         *          month, day, hour, minute and second.
         * @type    {object}
         */
        getDateObjectFromImageUrl: function (url) {

             // if the url is null, return an object with only the current year

            if (url == null) {

                var myDate  = new Date();
                var obj     = { year: myDate.getFullYear(), month: '', day: '', hour: '', minute: '' };

            } else {

                // split the url from the slashes, reverse the array, remove the file suffix
                // and parse the date and time information

                var urlParts    = url.split('/').reverse(),
                    dateStr     = urlParts[2],
                    timeStr     = urlParts[0].replace(/\.jpg/gi, ''),
                    year        = dateStr.substr(0, 4),
                    month       = dateStr.substr(4, 2),
                    day         = dateStr.substr(6, 2),
                    hour        = timeStr.substr(0, 2);
                    minute      = timeStr.substr(2, 2);
                    second      = timeStr.substr(4, 2);

                var obj = { year: year, month: month, day: day, hour: hour, minute: minute, second: second };

            } // else

            return obj;

        },


        /**
         * Generates a date string from an url of an image corresponding the current
         * period
         *
         * @param   {string}    url     The url of the image, for example
         *                              http://domainname/otos/getSnapshot.php?
         *                              server=10.10.10.253&image=/otos/analyzing_images/
         *                              recorder/0014D18A2F45-0/20061127/thumbnails/130149.jpg
         * @param   {string}    period  The current period, must be 'year', 'month', 'day', 'hour' or
         *                              'minute'
         * @return  A string with the date information, ie. '21/11/2006 13:12:58'
         */
        getDateStringFromImageUrl: function (url, period) {

            var str = '';

            if (OTOS.Util.isEmpty(url)) {
                str = 'Ei kuvia';

            } else {

                var dateObj = OTOS.Util.getDateObjectFromImageUrl(url);

                if (OTOS.Util.in_array(period, ['year', 'month', 'day', 'hour', 'minute'])) { str = dateObj.month + '/' + dateObj.year; }
                if (OTOS.Util.in_array(period, ['month', 'day', 'hour', 'minute'])) { str = dateObj.day + '/' + str; }
                if (OTOS.Util.in_array(period, ['day', 'hour', 'minute'])) { str += ' ' + dateObj.hour }
                if (OTOS.Util.in_array(period, ['hour', 'minute'])) { str += ':' + dateObj.minute }
                if (OTOS.Util.in_array(period, ['minute'])) { str += ':' + dateObj.second }

            } // else

            return str;

        }

    };

}();
