/*global document, window, top, $ */

$(document).ready(function () {
    // Extract domain name and blog location
    var hash = window.location.hash,
        frameUrl = window.location.toString(),
        domain,
        blogLocation,
        matches,
        message,
        baseUrl;

    matches = frameUrl.match(/iloapp\.([^\/]+?)\/blog\/([^\?\/\#]+)/);

    if (matches) {
        domain = matches[1];
        blogLocation = matches[2];
        baseUrl = 'http://' + blogLocation + '.' + domain + '/';
        matches = frameUrl.match(/Home(?:&(post|category|user|page)=(\d+)(?:&page=(\d+))?)?/);

        if (top === window) {
            // Not inside frame so redirect
            if (matches && matches[1] !== undefined) {
                window.location = baseUrl + '#' + matches[1] + matches[2];
            }
        } else if (matches) {
            if (window.postMessage) {
                // Post message to top frame to indicate url
                if (matches[1] !== undefined) {
                    if (matches[1] === 'page') {
                        message = 'home.' + matches[2];
                    } else {
                        message = matches[1] + matches[2];
                        if (matches[3] !== undefined) {
                            message += '.' + matches[3];
                        }
                    }
                    top.postMessage(message, baseUrl);
                } else {
                    top.postMessage('home', baseUrl);
                }
            }
        } else {
            matches = frameUrl.match(/NewComment&post=(\d+)/);
            if (matches && window.postMessage) {
                top.postMessage('comments' + matches[1], baseUrl);
            }
        }
    }
});

function WriteFlash(txtObject) {
    document.write(txtObject);
}

