(function ($)
{
    var defaultWidth = 510, //pixels
    transition = 450; //millisecond

    $.extend({
        get_index: function ()
        {

            var index = 2;
            if ($.browser.msie && parseInt($.browser.version) < 9)
                index = 1;

            return index;
        },
        // http://djpate.com/2009/10/07/animated-scroll-to-anchorid-function-with-jquery/

        goToByScroll: function (elm)
        {
            $('html,body').animate({ scrollTop: $('a[name="' + elm.attr('href').substr(1) + '"]').offset().top }, 'fast');
        },

        doneLoading: function (objs)
        {
            $.initCycle();

            $("#contentTemp").each(function () { this.innerHTML = ""; });
            $.updatePageLinks();

            $('#overlay:visible').fadeOut('fast');
            $(document).trigger('pageReady');

            var timeout = 0;
            objs.contentTmp.find("script").each(function ()
            {
                setTimeout(this.text, timeout);
                timeout++;
            });

            if (objs.scripts != null && objs.scripts.length > 0)
            {
                setTimeout(objs.scripts, timeout);
            }

        },
        beginLoading: function ()
        {
            $('#overlay:not(:visible)').fadeIn('fast');
            $('html, body').animate({ scrollTop: 0 }, 'fast');
        },
        updatePageLinks: function ()
        {
            $.dochecking = true;
            $('a.bookmark').unbind('click');
            $('a.bookmark').click(function (e)
            {
                e.preventDefault();
                $.goToByScroll($(this));
                return false;
            });
            var links = $('a:not(.bookmark, [type="external"])');
            links.unbind("click");
            links.click(function (event)
            {
                $.dochecking = false;
                var currentTime = new Date(), me = $(this), menuStaging = $('#menuStaging'), menu = $('#menuHolder'), scripts = null, contentTmp = $("#contentTemp"), content = $('#content'), title = "";
                if (me.attr('href').indexOf("://") == -1 && me.attr('href').indexOf("mailto:") == -1)
                {
                    event.preventDefault();
                    if (me.attr('href') != "/")
                    {
                        window.location.href = "/#" + me.attr('href');
                    } else
                    {
                        window.location.href = "/#";
                    }
                    $.hash = window.location.hash;
                    $.getPage(function (menuHtml)
                    {
                        if (me.attr("type") != "external" && me.attr("type") != "link")
                        {
                            menuStaging.html(menuHtml);
                            var scrollWidth = defaultWidth, parent = menuStaging.parent(), animatingMenu = menu, isReversed = false;
                            if (me.attr("type") == "back")
                            {
                                margin = 0;

                                menuStaging.html(menu.html());
                                menu.html(menuHtml);

                                menu = menuStaging;
                                menuStaging = animatingMenu;
                                isReversed = true;
                                $('#menu').scrollLeft(scrollWidth);
                                scrollWidth = 0;
                            }

                            $('#menu').animate({ scrollLeft: scrollWidth }, transition, function ()
                            {
                                if (isReversed)
                                {
                                    menuStaging.html(menuStaging.html());
                                    menu.html("");
                                    menu.attr('style', '');
                                    menuStaging.attr('style', '');
                                }
                                else
                                {
                                    menu.html(menuStaging.html());
                                    menuStaging.html("");
                                    menuStaging.attr('style', '');
                                    menu.attr('style', '');
                                }
                                $.doneLoading({ contentTmp: contentTmp, scripts: scripts });
                                $('#menu').scrollLeft(0);
                            });
                        }
                    });
                }
            });
        },
        cleanArray: function (actual)
        {
            var newArray = new Array();
            for (var i = 0; i < actual.length; i++)
            {
                if (actual[i])
                {
                    newArray.push(actual[i]);
                }
            }
            return newArray;
        },
        setMeta: function (data)
        {
            document.title = $.cleanArray(data.split(/(<title>|<\/title>)/ig))[$.get_index()];

        },
        getPage: function (animateMenu)
        {
            $.beginLoading();
            $.hash = window.location.hash;
            var hash = $.hash;
            if ($.hash == "")
            {
                hash = "#/";
            }
            var currentTime = new Date(), menuStaging = $('#menuStaging'), menu = $('#menuHolder'), scripts = null, contentTmp = $("#contentTemp"), content = $('#content'), title = "";

            $.ajax({ url: hash.substring(1),
                data: { date: currentTime.getMilliseconds() },
                dataType: "html",
                success: function (data, textStatus, jqXHR)
                {

                    var html = data.replace(/<div id=\"contentTemp\" style=\"display: none; width: 0; height: 0;\"><\/div>/g, "").split(/(<body>|<\/body>)/ig)[$.get_index()], scripts = "";
                    if ($.browser.msie && parseInt($.browser.version) < 9)
                        scripts = html.split(/<script (.|\n)*?>|<\/script>/ig)[$.get_index()];
                    contentTmp[0].innerHTML = html;

                    $.setMeta(data);

                    contentTmp = $("#contentTemp");

                    contentTmp.find('#overlay').show();

                    content.html(contentTmp.find('#content').html());
                    if (animateMenu && typeof (animateMenu) == 'function')
                    {
                        animateMenu(contentTmp.find('#menuHolder').html());
                    } else
                    {
                        menu.html(contentTmp.find('#menuHolder').html());

                        $.doneLoading({ contentTmp: contentTmp, scripts: scripts });
                    }
                },
                error: function (data)
                {
                    $.doneLoading({ contentTmp: contentTmp, scripts: scripts });
                    if (console && console.log)
                    {
                        console.log(data);
                    }
                }
            });
        },
        ischeckingback: false,
        dochecking: true,
        hash: "",
        checkifback: function ()
        {
            if (!$.ischeckingback)
            {
                $.ischeckingback = true;
                $.hash = window.location.hash;

                setInterval(function ()
                {
                    if (window.location.hash != $.hash && $.dochecking)
                    {
                        $.hash = window.location.hash;
                        $.getPage();
                    }
                }, 100);
            }
        }
    });
    $(document).ready(function ()
    {
        if (window.location.pathname != "/")
            window.location.href = "/#" + window.location.pathname;


        $.checkifback();
        $.getPage();

        $.updatePageLinks();

    });
})(jQuery);
