if (typeof k == "undefined" || !k) {
    var k = {};
}

(function() {
    var imgPreloaderEl = null;

    k.util = {
        isOnHashChange : function() {
            if ("onhashchange" in window) {
                return true;
            } else {
                return false;
            }
        },

        getHash : function() {
            if (k.a.isBrowserIe() &&  (k.a.getBrowserVer() * 1) == 6) {
                var hash = __getHashFromHref();

                if (false === hash) {
                    hash = window.location.hash;
                }

                return hash;
            } else if (k.a.isBrowserOpera()) {
                var hash = __getHashFromHref();

                if (false === hash) {
                    hash = window.location.hash;
                }

                return hash;
            } else {
                return window.location.hash;
            }
        },

        setHash : function(hash) {
            window.location.hash = hash;
        },

        setupPageProp : function(pageInfo) {
            document.title = pageInfo.ria_page_name;
        },

        string2Json : function(jsonString) {
            var first = jsonString.charAt(0);

            if (k.util.isStringJson(jsonString)) {
                var out = false;

                jsonString = 'out = ' + jsonString;
                eval(jsonString);

                return out;
            } else {
                throw new Error(-10, "Incorrect json format!");
            }
        },

        count : function(obj) {
            //моджно оптимизировать используя __count__
            var i = 0;

            k.a.each(obj, function(key, val) {
                i++;
            });

            return i;
        },

        //если будет использоваться на продакшене - переписать на флешь!
        playSound : function(path) {
            var player = document.getElementById('player');

            if (null === player) {
                var playerEl = document.createElement('embed');
                playerEl.hidden = true;
                playerEl.autostart = true;
                playerEl.loop = false;
                playerEl.id = 'player';

                var div = document.createElement('div');
                div.style.visibility = 'hidden';
                div.appendChild(playerEl);

                document.body.appendChild(div);
                player = document.getElementById('player');
            }

            player.src = path;
        },

        parseName2Arr : function(name) {
            name = name.replace(/]/g, '');

            var nameArr = name.split('[')

            return nameArr;
        },

        putValueToOut : function(out, nameArr, value) {
            var cur = out;
            var i = 1;

            k.a.each(nameArr, function(key, name) {
                if ('' == name) {
                    var total = k.util.count(cur);
                    name = total;
                }

                if (typeof(cur[name]) == 'undefined') {
                    cur[name] = {};
                }

                if (i == nameArr.length) {
                    cur[name] = value;
                }

                cur = cur[name];

                i++;
            });

            return out;
        },

        inObject : function(value, obj) {
            if (typeof(obj) != 'object') {
                return false;
            }

            var out = false;

            k.a.each(obj, function(objKey, objVal) {
                if (objVal == value) {
                    out = objKey;
                    return false;
                }
            });

            return out;
        },

        /*
         * проверяет - совпадают ли объекты.
         * работает рекурсивно.
         * Если объекты разные - true
         * Если объекты одинаковые - false
         *
         **/
        isDiff : function(obj1, obj2) {
            var out = false;

            k.a.each(obj1, function(key, value) {
                if (typeof(obj2[key]) == 'undefined') {
                    out = true;
                    return false;
                } else if (typeof(value) != typeof(obj2[key])) {
                    out = true;
                    return false;
                } else {
                    if (null === value || typeof(value) != 'object') {
                        if (value != obj2[key]) {
                            out = true;
                            return false;
                        }
                    } else {
                        out = k.util.isDiff(value, obj2[key]);
                    }
                }
            });

            return out;
        },

        objKeys : function(obj) {
            var out = [];

            k.a.each(obj, function(key, val) {
                out.push(key);
            });

            return out;
        },

        objKeysIdx : function(obj) {
            var out = {};

            k.a.each(obj, function(key, val) {
                out[key] = '';
            });

            return out;
        },

        /*
         * возвращает высоту рабочей области - без прокрутки
         *
         **/
        windowHeight : function() {
            var de = document.documentElement;

            if (self.innerHeight) {
                return self.innerHeight;
            } else if (de && de.clientHeight) {
                return de.clientHeight;
            } else {
                return document.body.clientHeight;
            }
        },

        /*
         * возвращает ширину рабочей области - без прокрутки
         *
         **/
        windowWidth : function() {
            var de = document.documentElement;

            if (self.innerWidth) {
                return self.innerWidth;
            } else if (de && de.clientWidth) {
                return de.clientWidth;
            } else {
                return document.body.clientWidth;
            }
        },

        /*
         * вовращает высоту body вместе со скролингом
         *
         **/
        documentHeight : function() {
            return (document.body.scrollHeight > document.body.offsetHeight) ? document.body.scrollHeight : document.body.offsetHeight;
        },

        /*
         * возвращает ширину body вместе со скроленгом
         *
         **/
        documentWidth : function() {
            return (document.body.scrollWidth > document.body.offsetWidth) ? document.body.scrollWidth : document.body.offsetWidth;
        },

        scrollX : function () {
            return window.pageXOffset ? window.pageXOffset : document.documentElement.scrollLeft ? document.documentElement.scrollLeft : document.body.scrollLeft;
        },

        scrollY : function() {
            return window.pageYOffset ? window.pageYOffset : document.documentElement.scrollTop ? document.documentElement.scrollTop : document.body.scrollTop;
        },

        getWinCenterX : function(blockWidth) {
            var left = 0,
                winWidth  = k.util.windowWidth();

            if (winWidth > blockWidth) {
                left = Math.round((winWidth - blockWidth) / 2);
            }

            left += k.util.scrollX();

            return left;
        },

        getWinCenterY : function(blockHeight) {
            var top = 0,
                winHeight = k.util.windowHeight();

            if (winHeight > blockHeight) {
                top = Math.round((winHeight - blockHeight) / 2);
            }

            top += k.util.scrollY();

            return top;
        },
        /*
         * останавливает всплытие для события
         *
         **/
        stopBubble : function(e) {
            if (e && e.stopPropagation) {
                e.stopPropagation();
            } else {
                window.event.cancelBubble = true;
            }
        },

        isStringJson : function(jsonString) {
            var first = jsonString.charAt(0);
            var last = jsonString.charAt(jsonString.length - 1);
            var numReg = /^\d+$/;

            if (jsonString == 'null' || jsonString == 'true' || jsonString == 'false') {
                return true;
            } else if ((first == '[' && last == ']') || (first == '{' && last == '}')) {
                return true;
            } else if (numReg.test(jsonString)) {
                return true;
            } else {
                return false;
            }
        },

        stripTags : function(str) {
            str = str.replace(/<\/?[^>]+>/gi, "");

            return str;
        },

        trim : function(str) {
            return str.replace(/(^\s+)|(\s+$)/g, "");
        },

        preloadImages : function (images) {
            if (null === imgPreloaderEl) {
                imgPreloaderEl = document.createElement('div');
                imgPreloaderEl.style.position = 'absolute';
                imgPreloaderEl.style.top = '0px';
                imgPreloaderEl.style.left = '0px';
                imgPreloaderEl.style.height = '1px';
                imgPreloaderEl.style.overflow = 'hidden';
                imgPreloaderEl.style.visibility = 'hidden';
                document.body.appendChild(imgPreloaderEl);
            }

            k.a.each(images, function(i, value) {
                imgPreloaderEl.innerHTML += '<img src="' + value + '" />';
            });
        }
    };

    /*
     * Для говно-браузеров - хешь режем из window.location.href
     *
     **/
    function __getHashFromHref()
    {
        var pos = window.location.href.indexOf('#');

        if (pos == -1) {
            return false;
        } else {
            return window.location.href.substr(pos);
        }
    }
}) ();
