;(function ($, window, document, undefined) {
    'use strict';

    window.Ignite = window.Ignite || {};
    window.Ignite.Core = {};

    $.extend(window.Ignite.Core, {

        /**
         * Get the path to errors.
         *
         * @param obj
         * @param key
         * @returns {T}
         */
        getPath: function(obj, key) {
            return key.split('.').reduce(function(o, x) {
                return (typeof o === 'undefined' || o === null) ? o : o[x];
            }, obj);
        },

        /**
         * Check if a key is set on an object.
         *
         * @param obj
         * @param key
         * @returns {boolean}
         */
        isset: function(obj, key) {
            return key.split('.').every(function(x) {
                if (typeof obj !== 'object' || obj === null || !(x in obj)) {
                    return false;
                }
                obj = obj[x];
                return true;
            });
        },

        /**
         * Get the errors from the response.
         *
         * @param variable
         * @param path
         * @param defaultMessage
         * @returns {string}
         */
        getResponseErrors: function(variable, path, defaultMessage) {
            var messages = 'No error info provided.';

            if (typeof(defaultMessage) !== 'undefined') {
                messages = defaultMessage;
            }

            if (this.isset(variable, path)) {
                messages = this.getPath(variable, path).join("\n");
                if (messages !== '') {
                    messages += "\n";
                }
            }

            return messages;
        },

        flash: function(message, state, timeout) {
            var $alert = $('<div class="alert"></div>');
            var $close = $('<button data-dismiss=".alert" class="close">&times;</button>');
            var $text  = $('<p class="alert-message"></p>');
            var remove = function() {
                $alert.fadeOut(function() {
                    $(this).remove();
                });
            };

            $alert.addClass('alert-' + (state || 'info'));
            $alert.addClass('alert-floating');
            $close.on('click', remove);
            $text.html(message);
            $alert.append($close);
            $alert.append($text);
            $('body').append($alert);

            if (0 !== timeout) {
                setTimeout(remove, timeout || 3000);
            }
        },

        /**
         * Add commas to number format.
         *
         * @param nStr
         * @returns {string}
         */
        addCommas: function(nStr) {
            nStr += '';
            var x = nStr.split('.');
            var x1 = x[0];
            var x2 = x.length > 1 ? '.' + x[1] : '';
            var rgx = /(\d+)(\d{3})/;
            while (rgx.test(x1)) {
                x1 = x1.replace(rgx, '$1' + ',' + '$2');
            }
            return x1 + x2;
        },

        /**
         * Set a browser cookie.
         *
         * @param cname
         * @param cvalue
         * @param exdays
         */
        setCookie: function(cname, cvalue, exdays) {
            var d = new Date();
            d.setTime(d.getTime() + (exdays*24*60*60*1000));
            var expires = 'expires=' + d.toUTCString();
            document.cookie = cname + '=' + cvalue + ';' + expires + ';path=/';
        },

        /**
         * Get a browser cookie.
         *
         * @param cname
         * @returns {string}
         */
        getCookie: function(cname) {
            var name = cname + '=';
            var decodedCookie = decodeURIComponent(document.cookie);
            var ca = decodedCookie.split(';');

            for(var i = 0; i < ca.length; i++) {
                var c = ca[i];
                while (c.charAt(0) === ' ') {
                    c = c.substring(1);
                }
                if (c.indexOf(name) === 0) {
                    return c.substring(name.length, c.length);
                }
            }

            return '';
        },

        codifyField: function(source, target) {
            var $source = $(source);
            var $target = $(target);

            if (! $target.attr('disabled') && ! $target.attr('readonly')) {
              $source.on('keyup', function() {
                $target.val(
                  $.trim($source.val())
                    .toLowerCase()
                    .replace(/[^a-z0-9]+|\s+/gmi, '_')
                    .replace(/[\-]+$/g, '')
                );
              });
            }
        }
    });

})(jQuery, window, document);
