Browser = {
    isIE: function() {
        return this._is("msie");
    },

    isIPhone: function() {
        return this._is("iphone");
    },

    isIPad: function() {
        return this._is("ipad");
    },

    isIPod: function() {
        return this._is("ipod");
    },

    isAndroid: function() {
        return this._is("android");
    },

    isBlackBerry: function() {
        return this._is("blackberry");
    },

    isIOS: function() {
        return this.isIPhone() || this.isIPad() || this.isIPod();
    },

    isMobile: function() {
        return this.isIOS() || this.isAndroid() || this.isBlackBerry();
    },

    version: function() {
        if (this._cachedVersion == undefined)
            try {
                if (this.isIE())
                    this._cachedVersion = parseFloat(this._getUserAgent().split("MSIE")[1]);
                else if (this.isAndroid())
                    this._cachedVersion = parseFloat(this._getUserAgent().split("Android")[1]);
                else if (this.isIOS()) {
                    var v = this._getUserAgent().split("OS")[1];
                    this._cachedVersion = parseFloat(v.replace("_", ".").replace(/_/g, ""));
                }
            } catch(ignored) {
            }
        return this._cachedVersion != undefined ? this._cachedVersion : 0;
    },

    isPlaceHolderSupported: function() {
        return !this.isAndroid() || this.version() >= 2.0;
    },

    _is: function(token) {
        return this._getUserAgent().toLowerCase().indexOf(token) >= 0;
    },

    _getUserAgent: function() {
        return this._forcedUserAgent || navigator.userAgent;
    },

    setDeviceType: function(forcedUserAgent) {
        if (this._forcedUserAgent != forcedUserAgent)
            this._cachedVersion = undefined;
        this._forcedUserAgent = forcedUserAgent;
    }
};

(function() {
    window.AppLoader = window.AppLoader || {};

    var s = window.localStorage || window.globalStorage;
    if (s)
        try {
            s["autoniq.test"] = "test";
            s["autoniq.test"] = undefined;
            AppLoader.storage = {
                set: function(n, v, d) {
                    s["autoniq." + n] = d;
                    s["autoniq.version." + n] = v;
                },
                get: function(n, v) {
                    if (v == s["autoniq.version." + n])
                        return s["autoniq." + n];
                }
            }
        }catch(ignored/*localStorage is not writable (ie iOS Private Browsing mode*/) {
        }
    else if (window.google && google.gears)
        try {
            var db = google.gears.factory.create('beta.database');
            db.open('autoniq');
            db.execute("create table if not exists resources(n text unique not null primary key, v text not null, d text not null)");
            db.close();

            AppLoader.storage = {
                set: function(n, v, d) {
                    db.open('autoniq');
                    db.execute("delete from resources where n = ?", [n]);
                    db.execute("insert into resources(n, v, d) values (?, ?, ?)", [n, v, d]);
                    db.close();
                },
                get: function(n, v) {
                    var d;
                    db.open('autoniq');
                    var r = db.execute('select d from resources where n = ? and v = ?', [n, v]);
                    if (r.isValidRow())
                        d = r.field(0);
                    r.close();
                    db.close();
                    return d;
                }
            };
        } catch(e) {
            alert(e);
        }

    AppLoader.getResource = function(url, cb) {
        var s = AppLoader.storage,
        m = AppLoader.manifest,
        v = m[url], d;

        if (s && (d = s.get(url, v)))
            return cb(url, d);

        var x = new XMLHttpRequest();
        x.onreadystatechange = function() {
            if (x.readyState == 4) {
                if (x.status == 200) {
                    if (cb(url, x.responseText) && s && v)
                        s.set(url, v, x.responseText);
                } else {
                    alert("error loading: " + url);
                    cb(url); // error
                }
            }
        };
        x.open("GET", url + '?' + +new Date(), true);
        x.send();
    };

    function loadResources(args) {
        var url;
        for (; ;) {
            if (!args.length)
                return;
            url = args.shift();
            if (Object.prototype.toString.call(url) !== "[object Function]")
                break;
            url();
        }
        AppLoader.getResource(url, function(url, data) {
            var result = false;
            if (/.js\b/i.test(url)) {
                try {
                    window.eval(data);
                    result = true;
                } catch(e) {
                    alert("JS resource load error: " + e + "\nURL: " + url);
                }
            } else if (/.css\b/i.test(url)) {
                var e = document.createElement("style");
                e.setAttribute("type", "text/css");
                if (e.styleSheet)   // hello IE
                    e.styleSheet.cssText = data;
                else
                    e.appendChild(document.createTextNode(data));
                var head = document.getElementsByTagName("head")[0];
                head.appendChild(document.createTextNode("\n"));
                head.appendChild(e);
                result = true;

            } else if (/.html\b/i.test(url)) {
                e = document.createElement("div");
                e.innerHTML = data;
                document.body.appendChild(e);
                result = true;
            } else
                alert("Unsupported resource type: " + url);

            loadResources(args);
            return true;
        });
    }

    function empty(e) {
        while (e.firstChild)
            e.removeChild(e.firstChild);
    }

    function createCookie(name, value, days) {
        var expires = "";
        if (days !== undefined) {
            var date = new Date();
            date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
            expires = "; expires=" + date.toGMTString();
        }
        document.cookie = name + "=" + value + expires + "; path=/";
    }

    function readCookie(name) {
        var nameEQ = name + "=";
        var 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);
            if (c.indexOf(nameEQ) === 0)
                return c.substring(nameEQ.length, c.length);
        }
        return undefined;
    }

    AppLoader.checkBrowserCompatibility = function(warningContainer, keepContainer) {
        var cookie = "TEST";
        var token = new Date().getMilliseconds();
        createCookie(cookie, token);

        if (token != readCookie(cookie)) {
            empty(warningContainer);
            var e = document.createElement("div");
            e.innerHTML = "Please enable browser cookies";
            warningContainer.appendChild(e);
            throw "Terminated";
        }
        createCookie(cookie, "", -1);

        if (Browser.isIE() && Browser.version() <= 6) {
            empty(warningContainer);
            e = document.createElement("div");
            e.innerHTML = "Warning: For security reasons Internet Explorer version 6 and below " +
            "is not supported.<br/><br/>Please upgrade to a current version of Internet Explorer, Firefox, Safari or Chrome";
            warningContainer.appendChild(e);
            throw "Terminated";
        }
        if (!keepContainer)
            document.body.removeChild(warningContainer);
    };

    AppLoader.load = function(warningContainerName, windowName, page, pageData) {
        var warningContainer = document.getElementById(warningContainerName);
        window.name = windowName;
        this.checkBrowserCompatibility(warningContainer, true);
        empty(warningContainer);
        var e = document.createElement("div");
        e.innerHTML = "Loading ...";
        warningContainer.appendChild(e);

        // Called from init() to cache the bootstrap.js after it's loaded with "script" tag.
        if (this.cacheBoot && this.storage) {
            this.getResource(this.cacheBoot, function(url, data) {
                return !!data;
            });
            delete this.cacheBoot;
        }

        var r = ["mobile/js/lib-min.js", "mobile/js/app-min.js"];
        if (!Browser.isIE() || Browser.version() > 7)
            r.push("mobile/css/app-min.css");
        r.push("mobile/markup-min.html");

        r.push(function() {
            document.body.removeChild(warningContainer);
            Tmatex.PM.init(Autoniq, page, pageData);
        });
        loadResources(r);
    };
})();




