//bind implementation (IE 8 etc.)
if (!Function.prototype.bind) {
    Function.prototype.bind = function (oThis) {
        if (typeof this !== "function") {
            // closest thing possible to the ECMAScript 5 internal IsCallable function
            throw new TypeError("Function.prototype.bind - what is trying to be bound is not callable");
        }

        var aArgs = Array.prototype.slice.call(arguments, 1),
            fToBind = this,
            fNOP = function () {
            },
            fBound = function () {
                return fToBind.apply(this instanceof fNOP && oThis
                        ? this
                        : oThis,
                    aArgs.concat(Array.prototype.slice.call(arguments)));
            };

        fNOP.prototype = this.prototype;
        fBound.prototype = new fNOP();

        return fBound;
    };
}
//************************BIND

/** iKantam module
 * @author Alex Poliushkin
 */
(function (global) {

    global.iKantam = (function () {


        /*private variables and methods*/
        var hasOwn = Object.prototype.hasOwnProperty,
            _indexOf = function (haystack, needle) {

                var i = 0,
                    max = haystack.length;
                for (; i < max; i++) {
                    if (haystack[i] === needle) {
                        return i;
                    }
                }
                return -1;
            },
            htmlEscapes = {
                '&': '&amp;',
                '<': '&lt;',
                '>': '&gt;',
                '"': '&quot;',
                "'": '&#x27;',
                '/': '&#x2F;'
            },
            htmlEscaper = /[&<>"'\/]/g,
            _oToStr = Object.prototype.toString,
            _slice = Array.prototype.slice,
            _isObject = function (o) {
                return _oToStr.call(o) === "[object Object]"
            },
            _isFunction = function (f) {
                return _oToStr.call(f) === "[object Function]"
            },
            _storage = (function () {

                var data = {},
                    alowed = {
                        number: 1,
                        string: 1,
                        boolean: 1
                    },

                    prefix = (Math.random() + '_').slice(2);

                return {
                    set: function (name, value) {
                        /* if(this.isDefined(name)) {
                         return false;
                         } */

                        if (!hasOwn.call(alowed, typeof value)) {
                            return false;
                        }

                        data[prefix + name] = value;
                        return true;
                    },

                    isDefined: function (name) {
                        return hasOwn.call(data, prefix + name);
                    },

                    get: function (name, default_) {

                        if (this.isDefined(name)) {
                            return data[prefix + name];
                        }

                        return default_ || null;
                    },

                    unset: function (name) {
                        if (this.isDefined(name)) {
                            return delete data[prefix + name];
                        }
                        return false;
                    }
                };

            }()), //_storage
            _modules = {},

            cloner = {

                _clone: function _clone(obj) {
                    if (obj instanceof Array) {
                        var out = [];
                        for (var i = 0, len = obj.length; i < len; i++) {
                            var value = obj[i];
                            out[i] = (value !== null && typeof value === "object") ? _clone(value) : value;
                        }
                    } else {
                        var out = {};
                        for (var key in obj) {
                            if (obj.hasOwnProperty(key)) {
                                var value = obj[key];
                                out[key] = (value !== null && typeof value === "object") ? _clone(value) : value;
                            }
                        }
                    }
                    return out;
                },

                clone: function (it) {
                    return this._clone({
                        it: it
                    }).it;
                }
            },

            _queue = [],
            _whenQueue = [],
            _callWhenCallback = function (modules, callback) {
                var args,
                    modulesArr = [];

                if (modules.length === 1) {
                    modulesArr.push(_getModule(modules.shift()));
                } else {
                    args = _getModules.apply(this, modules);
                    var i;
                    for (i in args) {
                        if (hasOwn.call(args, i)) {
                            modulesArr.push(args[i]);
                        }
                    }
                }
                callback.apply(this, modulesArr);
            },
            _touchWhenQueue = function (list) {
                var i = list.length;
                for (; i--;) {
                    if (!hasOwn.call(_modules, list[i])) {
                        return false;
                    }
                }
                return true;
            },
            _afterModuleAdd = function (name, o) {
                var whenQueueSize = _whenQueue.length,
                    i = 0,
                    callback,
                    whenArgs;

                for (i = 0; i < whenQueueSize; i++) {
                    if (typeof _whenQueue[i] !== 'undefined' && _touchWhenQueue(_whenQueue[i].when)) {
                        whenArgs = _whenQueue[i].when;
                        callback = _whenQueue[i].callback;
                        _whenQueue.splice(i, 1);
                        i -= 1;
                        _callWhenCallback(whenArgs, callback);
                    }
                }

                return true;
            };

        function _getModules(list) {
            var args = Array.prototype.slice.call(arguments),
                mod = {},
                i = 0,
                max = args.length;
            if (!args.length || list === '*') {
                return _modules;
            } else {
                for (; i < max; i += 1) {
                    if (hasOwn.call(_modules, args[i])) {
                        mod[args[i]] = _modules[args[i]];
                    }
                }
            }
            return mod;
        }

        function _getModule(name) {

            if (hasOwn.call(_modules, name)) {
                return _modules[name];
            }

            return null;
        }

//iKantam object
        return {
            info: {
                fileName: 'iKantam.module.core.js',
                modulesDir: 'modules',
                version: '1.3.4'
            },

            /**
             * Protect namespacing. Create new objects or use existing.
             * ...
             * iKantam.namespace('my.new.object');
             * ...
             * @return object
             */

            namespace: function (ns_string) {
                var parts = ns_string.split('.'),
                    parent = this,
                    i;

                if (parts[0] === parent) {
                    parts = parts.slice(1);
                }

                for (i = 0; i < parts.length; i++) {
                    if (typeof parent[parts[i]] === 'undefined') {
                        parent[parts[i]] = {};
                    }

                    parent = parent[parts[i]];
                }

                return parent;
            },

            /**
             * Save and protect from rewrite.
             * Only simple data can be saved.
             *
             */
            storage: {

                set: _storage.set.bind(_storage),

                get: _storage.get.bind(_storage),

                unset: _storage.unset.bind(_storage),

                isSet: _storage.isDefined.bind(_storage)
            },


            addModule: function (name, implementation, self_binding) {

                self_binding = self_binding || false;
                var i,
                    max = _queue.length;
                if (!hasOwn.call(_modules, name)) {

                    if (typeof implementation === 'function') {
                        if (self_binding) {
                            _modules[name] = implementation;
                        } else {
                            _modules[name] = implementation.bind(this);
                        }

                        //check if this function in call queue
                        for (i = 0; i < max; i += 1) {
                            if (_queue[i].func === name) {
                                if (self_binding) {
                                    implementation.apply(implementation, _queue[i].args);
                                } else {
                                    implementation.apply(this, _queue[i].args);
                                }

                                //_queue.splice(i, 1);
                                _queue[i] = {};
                            }
                        }
                        _afterModuleAdd(name, this);
                        return true;
                    }
                    _modules[name] = implementation;
                    _afterModuleAdd(name, this);
                    return true;
                }

                throw new Error('Module with name "' + name + '" already exist');
            },

            when: function (when, callback) {
                var args = Array.prototype.slice.call(arguments),
                    callback = args.pop();
                if (_touchWhenQueue(args)) {
                    _callWhenCallback(args, callback.bind(this));
                } else {
                    _whenQueue.push({when: args, callback: callback});
                }
                return this;
            },

            getModules: _getModules,

            getModule: _getModule,

            clone: cloner.clone.bind(cloner),

            checkProperty: function (object, property) {
                return hasOwn.call(object, property);
            },

            /* Queue */

            putToCallQueue: function (name, args) {
                if (typeof name === 'string') {

                    var f = this.getModule(name);
                    if (typeof f === 'function') {
                        f.apply(this, args);
                        return true;
                    }
                    _queue.push({func: name, args: args});
                    return true;
                }

                return false;
            },

            objectSize: function (object) {
                var size = 0;
                for (var i in object) {
                    if (object.hasOwnProperty(i)) {
                        size++;
                    }
                }
                return size;
            },

            firstMatched: function (arr, callback, context) {
                var el;
                context = context || this;
                for (var i = 0, l = arr.length; i < l; i++) {
                    el = arr[i];
                    if (callback.call(context, el, i, arr)) {
                        return el;
                    }
                }
                return undefined;
            },

            extend: function (child, parent, other) {
                if (parent) {
                    var F = function () {
                    };
                    F.prototype = parent.prototype;
                    child.prototype = new F();
                    child.prototype.constructor = child;
                    child.prototype.proto = function () {
                        return parent.prototype;
                    }

                } else {
                    child.prototype.proto = function () {
                    }
                }
            },

            stringHash: function (str) {
                var hash = 0, i, char;
                if (str.length == 0) return hash;
                for (i = 0, l = str.length; i < l; i++) {
                    char = str.charCodeAt(i);
                    hash = ((hash << 5) - hash) + char;
                    hash |= 0; // Convert to 32bit integer
                }
                return hash;
            },
            preg_quote: function (str) {
                return (str + '').replace(/([\\\.\+\*\?\[\^\]\$\(\)\{\}\=\!\<\>\|\:])/g, "\\$1");
            },

            redirect: function (url, data) {
                if (typeof data !== 'object' || this.objectSize(data) < 1) {
                    window.location.href = url;
                } else {
                    if (!jQuery) {
                        throw new Error('jQuery required');
                    }
                    var $form = jQuery('<form method="POST" action="' + url + '">');
                    jQuery.each(data, function (key, value) {
                        $form.append(jQuery('<input type="hidden" name="' + key + '" value="' + value + '">'));
                    });
                    $form.appendTo('body').submit();
                }
            },

            url: function (path) {
                if (typeof path !== "string") {
                    throw new TypeError("path must be a string value");
                }
                if (path[0] === '/') {
                    path = path.slice(1);
                }
                var baseUrl = this.BASE_URL || (window.location.protocol + '//' + window.location.host);
                if (baseUrl[baseUrl.length - 1] !== '/') {
                    baseUrl += '/';
                }
                return baseUrl + path;
            },

            getByPath: function (obj, path) {
                for (var i = 0, path = path.split('.'), len = path.length; i < len; i++) {
                    if (typeof obj === 'undefined') {
                        return obj;
                    }
                    obj = obj[path[i]];
                }

                return obj;
            },

            isEqual: function (a, b, strict) {
                strict = (strict === false) ? strict : true;
                if (strict ? (a === b) : (a == b)) return true;

                if (!( a instanceof Object ) || !( b instanceof Object )) return false;

                if (a.constructor !== b.constructor) return false;

                for (var p in a) {
                    if (!a.hasOwnProperty(p)) continue;
                    // other properties were tested using x.constructor === y.constructor

                    if (!b.hasOwnProperty(p)) return false;
                    // allows to compare x[ p ] and y[ p ] when set to undefined

                    if (strict ? (a[p] === b[p]) : (a[p] == b[p])) continue;
                    // if they have the same strict value or identity then they are equal

                    if (typeof( a[p] ) !== "object") return false;
                    // Numbers, Strings, Functions, Booleans must be strictly equal

                    if (!iKantam.isEqual(a[p], b[p], strict)) return false;
                    // Objects and Arrays must be tested recursively
                }

                for (p in b) {
                    if (b.hasOwnProperty(p) && !a.hasOwnProperty(p)) return false;
                    // allows x[ p ] to be set to undefined
                }
                return true;
            },

            pickProperties: function (obj, list) {
                var result = [];
                list.forEach(function (propertyName) {
                    result.push(obj[propertyName]);
                });

                return result;
            },

            checkWaitProperties: function (obj, propertyList, chk) {
                return function (name, oldV, newV) {
                    var check = chk || function (v) {
                            return typeof v !== 'undefined';
                        };

                    try {
                        propertyList.forEach(function (propertyName) {
                            var value = (propertyName === name) ? newV : obj[propertyName];
                            if (!check(value)) {
                                throw new Error();
                            }
                        });
                    } catch (e) {
                        return false;
                    }

                    return true;
                }
            },

            whenProperties: function (obj, propertyList, handler, chk) {
                var isSet = this.checkWaitProperties(obj, propertyList, chk),
                    self = this;
                // in order to use it with "watch" it must return passed value
                return function (name, oldV, newV) {
                    if (isSet(name, oldV, newV)) {
                        var parameters = self.pickProperties(obj, propertyList);
                        if (typeof name !== 'undefined') {
                            parameters[propertyList.indexOf(name)] = newV;
                        }
                        handler.apply(obj, parameters);
                    }
                    return newV;
                }
            },

            whenSet: function (obj, propertyList, handler, chk) {
                var check = this.whenProperties(obj, propertyList, handler, chk),
                    self = this;
                propertyList.forEach(function (propertyName) {
                    self.watch(obj, propertyName, check);
                });
            },

            compose: function (funcs) {

                if (Object.prototype.toString.call(funcs) !== '[object Array]') {
                    funcs = Array.prototype.slice.call(arguments);
                }

                funcs.forEach(function (item) {
                    if (Object.prototype.toString.call(item) !== '[object Function]') {
                        throw new TypeError('compose: Only functions might be composed');
                    }
                });

                funcs.reverse();

                return funcs.reduce(function (g, f) {
                    return function (x) {
                        return g(f(x));
                    };
                }, function (x) {
                    return x;
                });
            },

            watch: (function () {
                var compose = this.compose,
                    self = this;

                return function (obj, prop, handler) {
                    var oldval = obj[prop], newval = oldval,
                        getter = function () {
                            return newval;
                        },
                        setter = function (val) {
                            oldval = newval;
                            return newval = handler.call(obj, prop, oldval, val);
                        },
                        descriptor = Object.getOwnPropertyDescriptor(obj, prop);

                    getter = (descriptor && descriptor.get) ? compose([descriptor.get, getter]) : getter;
                    setter = (descriptor && descriptor.set) ? compose([descriptor.set, setter]) : setter;

                    if (delete obj[prop]) {
                        if (Object.defineProperty) {
                            Object.defineProperty(obj, prop, {
                                get: getter,
                                set: setter
                            });
                        }
                        else if (Object.prototype.__defineGetter__ && Object.prototype.__defineSetter__) { // legacy
                            Object.prototype.__defineGetter__.call(obj, prop, getter);
                            Object.prototype.__defineSetter__.call(obj, prop, setter);
                        }
                    }
                };
            })(),

            transformKeys: function (map) {

                var transformers = Array.prototype.slice.call(arguments);

                return function (obj) {
                    var processed = {},
                        i,
                        result = {},
                        map,
                        byCallback = function (obj, callback) {
                            var name;

                            for (name in obj) {
                                if (!processed[name] && hasOwn.call(obj, name)) {
                                    result[callback.call(obj, name)] = obj[name];
                                    processed[name] = true;
                                }
                            }
                        },
                        byMap = function (obj, map) {
                            var name,
                                newName;

                            for (name in map) {
                                if (!processed[name] && hasOwn.call(map, name)) {
                                    newName = _isFunction(map[name]) ? newName.call(map, name) : map[name];
                                    result[newName] = obj[name];
                                    processed[name] = true;
                                }
                            }
                        };

                    for (i in transformers) {
                        if (hasOwn.call(transformers, i)) {
                            map = transformers[i];
                            if (_isFunction(map)) {
                                byCallback(obj, map)
                            } else if (_isObject(map)) {
                                byMap(obj, map);
                            }
                        }
                    }

                    for (i in obj) {
                        if (!processed[i] && hasOwn.call(obj, i)) {
                            result[i] = obj[i];
                        }
                    }

                    return result;
                };
            },

            /**
             * PHP like "parse_str" function
             */
            parseStr: function (str, result) {

                var strArr = String(str)
                        .replace(/^&/, '')
                        .replace(/&$/, '')
                        .split('&'),
                    sal = strArr.length,
                    i, j, ct, p, lastObj, obj, lastIter, undef, chr, tmp, key, value,
                    postLeftBracketPos, keys, keysLen,
                    fixStr = function (str) {
                        return decodeURIComponent(str.replace(/\+/g, '%20'))
                    };

                result = result || {};

                for (i = 0; i < sal; i++) {
                    tmp = strArr[i].split('=');
                    key = fixStr(tmp[0]);
                    value = (tmp.length < 2) ? '' : fixStr(tmp[1]);

                    while (key.charAt(0) === ' ') {
                        key = key.slice(1)
                    }
                    if (key.indexOf('\x00') > -1) {
                        key = key.slice(0, key.indexOf('\x00'))
                    }
                    if (key && key.charAt(0) !== '[') {
                        keys = [];
                        postLeftBracketPos = 0;
                        for (j = 0; j < key.length; j++) {
                            if (key.charAt(j) === '[' && !postLeftBracketPos) {
                                postLeftBracketPos = j + 1
                            } else if (key.charAt(j) === ']') {
                                if (postLeftBracketPos) {
                                    if (!keys.length) {
                                        keys.push(key.slice(0, postLeftBracketPos - 1))
                                    }
                                    keys.push(key.substr(postLeftBracketPos, j - postLeftBracketPos));
                                    postLeftBracketPos = 0;
                                    if (key.charAt(j + 1) !== '[') {
                                        break
                                    }
                                }
                            }
                        }
                        if (!keys.length) {
                            keys = [key]
                        }
                        for (j = 0; j < keys[0].length; j++) {
                            chr = keys[0].charAt(j);
                            if (chr === ' ' || chr === '.' || chr === '[') {
                                keys[0] = keys[0].substr(0, j) + '_' + keys[0].substr(j + 1)
                            }
                            if (chr === '[') {
                                break
                            }
                        }

                        obj = result;
                        for (j = 0, keysLen = keys.length; j < keysLen; j++) {
                            key = keys[j].replace(/^['"]/, '')
                                .replace(/['"]$/, '');
                            lastIter = j !== keys.length - 1;
                            lastObj = obj;
                            if ((key !== '' && key !== ' ') || j === 0) {
                                if (obj[key] === undef) {
                                    obj[key] = {}
                                }
                                obj = obj[key]
                            } else {
                                // To insert new dimension
                                ct = -1;
                                for (p in obj) {
                                    if (obj.hasOwnProperty(p)) {
                                        if (+p > ct && p.match(/^\d+$/g)) {
                                            ct = +p
                                        }
                                    }
                                }
                                key = ct + 1
                            }
                        }
                        lastObj[key] = value
                    }
                }

                return result;
            },

            escape: function (string) {
                return ('' + string).replace(htmlEscaper, function (match) {
                    return htmlEscapes[match];
                });
            }
        };


    }());

    iKantam.addModule('array', (function () {

        var _oToStr = Object.prototype.toString,
            _slice = Array.prototype.slice,
            _isArray = function (object) {

                return _oToStr.call(object) === '[object Array]';
            },

            _indexOf = function (haystack, needle) {

                var i = 0,
                    max = haystack.length;
                for (; i < max; i++) {
                    if (haystack[i] === needle) {
                        return i;
                    }
                }
                return -1;
            },
            _inArray = function (haystack, needle) {
                return _indexOf(haystack, needle) !== -1;
            };

        return {
            isArray: _isArray,
            inArray: _inArray,
            indexOf: _indexOf
        };
    }()));

})(this);
