/*global window, navigator, document, onReady*/

var UrlRewriter = function () {
    var userAgent = navigator.userAgent.toLowerCase(),
        isMobile = userAgent.indexOf('mobile') !== -1 ||
            userAgent.indexOf('iphone') !== -1 ||
            userAgent.indexOf('blackberry') !== -1 ||
            (document.cookie.match(/is_mobile=true/) &&
            !document.cookie.match(/is_mobile=false/)),
        isIE = navigator.userAgent.toLowerCase().match(/(msie) ([\w.]+)/),
        getUrlInfo = function (src) {
            var matches = src.match(/([^\.\/]+)\.((?:[^\/]+\.)+[^\/]+)/),
                urlInfo;

            if (matches) {
                urlInfo = {
                    location: matches[1],
                    domain: matches[2]
                };
            } else {
                matches = src.match(/([^\/]+)\/([^\/]+)/);
                if (matches) {
                    urlInfo = {
                        domain: matches[1],
                        location: matches[2]
                    };
                }
            }

            return urlInfo;
        },
        instance;

    instance = (function () {
        var urlRewriter = this,
            frame = document.getElementById('mainFrame'),
            hashCurrent = window.location.hash,
            domain,
            galleryLocation,
            frameSrc;

        return {
            init: function () {
                var urlInfo = getUrlInfo(window.location.toString());

                if (urlInfo) {
                    galleryLocation = urlInfo.location;
                    domain = urlInfo.domain;
                    frameSrc = 'http://iloapp.' + domain + '/gallery/' + galleryLocation + '?';

                    if (isMobile) {
                        // Show mobile version without frame
                        window.location = 'http://iloapp.' + domain + '/gallery/' + galleryLocation + '?Mobile';
                    } else {
                        if (hashCurrent === '') {
                            this.updateHash('home');
                        } else {
                            this.updateFrame();
                        }

                        if (window.history) {
                            onReady.addEventHandler(window, 'popstate', function (e) {
                                if (hashCurrent !== window.location.hash) {
                                    this.updateFrame(window.location.hash);
                                }
                            }, this);
                        } else  if ('onhashchange' in window) {
                            onReady.addEventHandler(window, 'hashchange', function (e) {
                                if (hashCurrent !== window.location.hash) {
                                    this.updateFrame(window.location.hash);
                                }
                            }, this);
                        }

                        if (window.postMessage) {
                            onReady.addEventHandler(window, 'message', function (e) {
                                this.updateHash(e.data);
                            }, this);
                        }
                    }
                }
            },

            /*
             * Change frame src according to hash.
             */
            updateFrame: function (hash) {
                if (!hash) {
                    hashCurrent = window.location.hash;
                } else {
                    hashCurrent = hash;
                }

                var src = this.hashToSrc(hashCurrent);
                if (frame.src !== src) {
                    frame.src = src;
                }
            },

            updateHash: function (message) {
                var hash = '#' + message;

                // Set hash according to message
                if (hashCurrent !== hash) {
                    hashCurrent = hash;
                    if (window.history && window.history.replaceState) {
                        window.history.replaceState({message: message}, '', hash);
                    } else {
                        window.location.hash = '#' + message;
                    }
                }
            },

            hashToSrc: function (hash) {
                var matches = hash.match(/^#home(\.(\d+))?$/),
                    src = frameSrc,
                    albumId,
                    imageId;

                if (matches) {
                    if (matches[2] !== undefined) {
                        src += 'Home&page=' + parseInt(matches[2], 10);
                    } else {
                        src += 'Home';
                    }
                } else {
                    matches = hash.match(/^#(\d+)(?:\.(\d+))?/);
                    if (matches) {
                        // Get album and image ids from hash
                        albumId = matches[1];
                        imageId = matches[2];

                        src += 'Album&album=' + albumId;

                        // Check if option image id was given
                        if (imageId !== null) {
                            src += '&image=' + imageId;
                        }
                    }
                }

                return src;
            }
        };
    }());

    instance.init();
    UrlRewriter = function () {
        return instance;
    };

    return UrlRewriter();
};

onReady(function () {
    var urlRewriter = new UrlRewriter();
});

