/* Standalone version of the onReady code from jQuery 1.2.2  */

function onReady(f) {
	// Attach the listeners
	onReady.bindReady();

	// If the DOM is already ready
	if (onReady.isReady) {
		// Execute the function immediately
		f.call(window);
		// Otherwise, remember the function for later
	}else{
		// Add the function to the wait list
		onReady.readyList.push(function() { return f.call(window);});
		return this;
	}
}

onReady.isReady = false;
onReady.readyList = [];
onReady.ready = function() { // Handle when the DOM is ready
	// Make sure that the DOM is not already loaded
	if (!onReady.isReady) {
		// Remember that the DOM is ready
		onReady.isReady = true;

		// If there are functions bound, to execute
		if (onReady.readyList) {
			// Execute all of them
			for (var i = 0 ; i<onReady.readyList.length ; i++) {
				onReady.readyList[i].call(window);
			}

			// Reset the list of functions
			onReady.readyList = null;
		}
	}
};

onReady.readyBound = false;

onReady.bindReady = function(){
	if (onReady.readyBound) {
		return;
	}
	onReady.readyBound = true;

	// Mozilla, Opera (see further below for it) and webkit nightlies currently support this event
	if (document.addEventListener && !BO.opera) {
		// Use the handy event callback
		document.addEventListener("DOMContentLoaded", onReady.ready, false);
	}

	// If IE is used and is not in a frame
	// Continually check to see if the document is ready
	if (BO.ie && window === top) {
		(function(){
			if (onReady.isReady) {
				return;
			}
			try {
				// If IE is used, use the trick by Diego Perini
				// http://javascript.nwbox.com/IEContentLoaded/
				document.documentElement.doScroll("left");
			} catch(e) {
				setTimeout(arguments.callee, 0);
				return;
			}
			// and execute any waiting functions
			onReady.ready();
		})();
	}

	if (BO.opera) {
		document.addEventListener("DOMContentLoaded", function() {
			if (onReady.isReady) {
				return;
			}
			for (var i = 0; i < document.styleSheets.length; i++) {
				if (document.styleSheets[i].disabled) {
					setTimeout(arguments.callee, 0);
					return;
				}
			}
			// and execute any waiting functions
			onReady.ready();
		}, false);
	}
	if (BO.safari) {
		var numStyles;
		(function(){
			if (onReady.isReady) {
				return;
			}
			if (document.readyState !== "loaded" && document.readyState !== "complete") {
				setTimeout(arguments.callee, 0);
				return;
			}
			if (numStyles === undefined) {
				numStyles = document.getElementsByTagName('style').length;
				var links = document.getElementsByTagName('link');
				for (var i=0 ; i<links.length ; i++) {
					if (/stylesheet/i.test(links[i].rel)) {
						numStyles++;
					}
				}
			}

			if (document.styleSheets.length !== numStyles) {
				setTimeout(arguments.callee, 0);
				return;
			}
			// and execute any waiting functions
			onReady.ready();
		})();
	}

	// A fallback to window.onload, that will always work
	if (window.addEventListener) {
		window.addEventListener('load', onReady.ready, false);
	} else if (window.attachEvent) {
		window.attachEvent("onload", onReady.ready);
	} else {
		var oldonload = window.onload;
		window.onload = function() {
			if (oldonload) {
				oldonload.call(window);
			}
			onReady.ready();
		};
	}
};

var BO = new function() {
	this.ie        = false /*@cc_on || true @*/;
	this.ie4       = this.ie && !document.getElementById;
	this.ie5       = this.ie && !document.namespaces && !this.ie4;
	this.ie7       = false /*@cc_on || (@_jscript_version == '5.7' && !!window.XMLHttpRequest && !document.querySelector) @*/;
	this.ie8       = navigator.userAgent.indexOf('Trident/4.0') !== -1;
	this.ie6       = this.ie && !!document.implementation && !!document.implementation.hasFeature && !this.ie7 && !this.ie8;
	this.ie55      = this.ie && !!document.namespaces && !this.ie6 && !this.ie7 && !this.ie8;
	this.ie7vista  = this.ie7 && /Windows NT 6\.0/.test(navigator.appVersion);
	this.ns4       = !this.ie && !!document.layers && !!window.confirm && !document.createElement;
	this.opera     = !!self.opera;
	this.gecko     = !!document.getBoxObjectFor;
	this.khtml     = !!navigator.vendor === 'KDE';
	this.konq      = this.khtml || document.childNodes && !document.all && !navigator.taintEnabled;
	this.safari    = !!document.childNodes && !document.all && !navigator.taintEnabled && !navigator.accentColorName;
	this.safari4   = this.safari && !!window.postMessage;
	this.safari30  = this.safari && !!window.devicePixelRatio;
	this.safari12  = this.safari && !parseInt(0,10).toFixed && !window.XMLHttpRequest;
	this.safari20  = this.safari && !!parseInt(0,10).toFixed && !this.safari12 && !this.safari30;
	this.safari11  = this.safari && !this.safari12 && !this.safari20 && !this.safari30;
	this.chrome    = navigator.userAgent.indexOf('Chrome') !== -1;
	this.X11       = navigator.appVersion.indexOf('X11') !== -1;
    this.iphone    = navigator.userAgent.toLowerCase().indexOf('iphone') !== -1;
    this.android   = navigator.userAgent.toLowerCase().indexOf('android') !== -1;
};

// Rewriting index frame hash to go directly to specific post(s)

var redirecter;

onReady(function() {
   redirecter = new HashRedirecter();
});

function HashRedirecter() {
    this.domFrame = document.getElementById('mainFrame');

    // Extract src from frame src
    this.srcOriginal = this.domFrame.src;
    var aMatches = this.srcOriginal.match(/iloapp\.([^\/]+)\/blog\/([^\?\#]+)/);

    if(aMatches) {
        this.domain = aMatches[1];
        this.blogLocation = aMatches[2];
    } else {
        return;
    }

    if (this.isMobile()) {

        // Show mobile version without frame
        window.location = 'http://iloapp.' + this.domain + '/blog/' + this.blogLocation + '?Mobile';
        return;

    } else {

        // Update frame for the first time
        this.UpdateFrame();
    
        // Begin interval
        var This = this;
        setInterval(function() {
            This.UpdateFrame();
        }, 500);

    }
}

HashRedirecter.prototype = {
    hashCurrent: '',

    UpdateFrame: function() {

    if(this.hashCurrent != location.hash) {

        var txtBlogSrc = 'http://iloapp.' + this.domain + '/blog/' + this.blogLocation + '?';

        if(aMatches = location.hash.match(/^#home(\.(\d+))?$/)) {

            // Requesting home page
            if(aMatches[2] != null && aMatches[2] !== '') {
                //Include page number
                this.domFrame.src = txtBlogSrc + 'Home&page=' + parseInt(aMatches[1]);
            } else {
                this.domFrame.src = txtBlogSrc + 'Home';
            }

        } else {

            var aMatches = location.hash.match(/^#(post|comments|category|user)?(\d+)(?:\.(\d+))?/);
            if(aMatches) {
                var field = aMatches[1], id = aMatches[2], page = aMatches[3];
                var src;

                // Set frame src
                if(field == 'comments') {
                    src = txtBlogSrc + 'NewComment&post=' + id;
                } else if(field == 'post' || field == 'category' || field == 'user') {
                    src = txtBlogSrc + 'Home&' + field + '=' + id;
                }

                // Add page if included
                if(page != null) {
                    src += '&page=' + page;
                }

                // Set url with fragment/identifier
                this.domFrame.src = src + '#niceURL';
            }
         }

         this.hashCurrent = location.hash;

    } else {

        // Check if cookie contains a message
        var aMatches = document.cookie.match(/\bbmsg(\d+)=([^;]+)/);
        if(aMatches) {
            var blogId = aMatches[1];
            var message = aMatches[2];

            // Delete the cookie
            var expires = new Date(0);
            document.cookie = 'bmsg' + blogId + '=_;path=/;domain=.' +
                    this.domain + ';expires=' + expires.toGMTString();
            document.cookie = 'bmsg' + blogId + '=_;path=/;expires=' +
                    expires.toGMTString();

            // Set hash according to message
            if(!navigator.userAgent.match(/safari/i)) {
                location.replace('#' + message);
                this.hashCurrent = '#' + message;
            }
         }
      }
   },

   isMobile: function () {
       return ((BO.iphone || BO.android || document.cookie.match(/is_mobile=true/)) &&
               !document.cookie.match(/is_mobile=false/));
   }
}
