﻿/// <reference path="jQuery-1.3.2.js" />
/// <reference path="jquery.tweet.js" />
/// <reference path="jquery-jtemplates_uncompressed.js" />

//This keeps track of our window interval event
var wjInfo = {
    session: {
        menuTimeout: null,
        blogLoading: false
    },
    initHashChange: function () {
        //Handles setting up the interval for checking has changes
        wjInfo.session.menuTimeout = window.setInterval("wjInfo.checkHashChange(true)", 500);
    },
    killHashChange: function () {
        //Kills the interval for checking has changes
        //We use this to turn off the hash change checks while we're mid animation - so that our current actions aren't overriden
        //by a new hash change event
        if (wjInfo.session.menuTimeout) {
            window.clearInterval(wjInfo.session.menuTimeout);
        }

        wjInfo.session.menuTimeout = null;
    },
    checkHashChange: function (firstLoad) {
        //Checks to see if the hash has changes for our page (#anchor) tags
        //This is to handle history/fwd/back navigation to keep the browser buttons working even though we're using AJAX
        if (window.location.hash) {
            var primaryAnchor = wjInfo.getAnchor(0), secondaryAnchor = wjInfo.getAnchor(1);

            if (primaryAnchor !== $("#navigation li.selectedmenu div.text a").attr("rel")) {
                $("#navigation a[rel='" + primaryAnchor + "']").click();
            }

            if (secondaryAnchor !== $("#navigation2 li.selectedmenu div.text a").attr("rel")) {
                $("#navigation2 a[rel='" + secondaryAnchor + "']").click();
            }
        } else if (firstLoad === true) {
            $("#navigation a[rel='!blog']").click();
        }
    },
    clearContent: function () {
        $("#content").html("");
    },
    loadAbout: function () {
        //Handles loading the about content
        wjInfo.clearContent();

        $.ajax({
            type: "GET",
            url: "/content/about.htm",
            dataType: "HTML",
            success: function (html) {
                $("#content").html(html);
                $("#content").fadeIn(500, function () {
                    wjInfo.initHashChange();
                });
            },
            error: function (html, error, status) {
                wjInfo.initHashChange();
            }
        });
    },
    loadBlog: function () {
        //Handles loading the blog content
        wjInfo.session.blogLoading = true;
        wjInfo.clearContent();

        $.ajax({
            type: "POST",
            contentType: "application/json; charset=utf-8",
            url: "/ws/services.asmx/GetRecentBlogs",
            data: "{}",
            dataType: "json",
            success: function (result) {
                $("#content").setTemplateURL("/templates/blogtemplate.htm?id=" + new Date().toString(), null, { filter_data: false }).processTemplate(result);

                //set a timeout to processTemplate() has time to finish - why doesn't it have a callback? UGH!
                window.setTimeout(function () {
                    $("#content").find("div:lt(2)").show();
                    $("#content").fadeIn(500);
                    $("#contentmenu").fadeIn(500, function () {
                        wjInfo.session.blogLoading = false;
                        wjInfo.initHashChange();
                    });
                }, 1200);
            },
            error: function (result, error, status) {
                console.log(error);
                console.log(status);
                wjInfo.session.blogLoading = false;
                wjInfo.initHashChange();
            }
        });

        $("#navigation2 li").show().removeClass("selectedmenu").find("div.text").each(function (menuIndex) {
            if (menuIndex === 0) {
                $(this).parent().addClass("selectedmenu");
            }

            $(this).click(function () {
                $("#navigation2 .selectedmenu").removeClass("selectedmenu");
                $(this).parent().addClass("selectedmenu");

                $("#content div.blog:visible").fadeOut(500, function () {
                    $("#content div.blog").each(function (blogIndex) {
                        if (blogIndex === (menuIndex * 2) || blogIndex === (menuIndex * 2) + 1) {
                            $(this).fadeIn(500);
                        }
                    });
                });
            });

        })
        .hover(function () {
            $(this).parent().addClass("hovermenu");
        },
        function () {
            $(this).parent().removeClass("hovermenu");
        })
        .find("a").each(function () {
            $(this).attr("href", "#!blog-" + $(this).attr("rel"));
        });

        if (wjInfo.getAnchor(0) === null) {
            window.location.hash = "!blog-1";
        }
    },
    loadPortfolio: function () {
        //Handles loading the portfolio contnet
        wjInfo.clearContent();

        $.ajax({
            type: "GET",
            url: "/content/portfolio.htm",
            dataType: "HTML",
            success: function (html) {
                $("#content")
                .html(html)
                .find("div.portfolio > div").hide().parent().parent()
                .find("div.portfolio:gt(0)").hide().parent()
                .fadeIn(500)
                .find("img")
                .click(function () {
                    $("#content").find("img.selectedmenu").removeClass("selectedmenu");
                    $(this).addClass("selectedmenu");

                    var imgID = $(this).attr("id"), detailID = imgID + "Detail";

                    $("#portfoliodetail").html("").append($("#content").find("#" + detailID).clone().fadeIn(500));
                })
                .hover(
                    function () {
                        $(this).addClass("hovermenu");
                    },
                    function () {
                        $(this).removeClass("hovermenu");
                    }
                );

                wjInfo.initPortfolioDetail(function () {
                    $("#content").find("img").eq(0).click();
                });

                $("#contentmenu").fadeIn(500, function () {
                    wjInfo.initHashChange();
                });
            },
            error: function (html) {
                console.log(html);
            }
        });

        $("#navigation2 li:gt(2)").hide();

        $("#navigation2 li").removeClass("selectedmenu").find("div.text")
        .each(function (menuIndex) {
            if (menuIndex === 0) {
                $(this).parent().addClass("selectedmenu");
            }

            $(this).click(function () {
                $("#navigation2 .selectedmenu").removeClass("selectedmenu");
                $(this).parent().addClass("selectedmenu");

                $("#content div.portfolio:visible").fadeOut(500, function () {
                    $("#content div.portfolio").each(function (blogIndex) {
                        if (blogIndex === menuIndex) {
                            $(this).fadeIn(500).find("img").eq(0).click();
                        }
                    });
                });
            });

        })
        .hover(function () {
            $(this).parent().addClass("hovermenu");
        },
        function () {
            $(this).parent().removeClass("hovermenu");
        })
        .find("a").each(function () {
            $(this).attr("href", "#!portfolio-" + $(this).attr("rel"));
        });

        if (wjInfo.getAnchor(0) === null) {
            window.location.hash = "!portfolio-1";
        }
    },
    loadSocial: function () {
        //Handles loading the social content
        wjInfo.clearContent();

        $.ajax({
            type: "GET",
            url: "/content/social.htm",
            dataType: "HTML",
            success: function (html) {
                $("#content")
                    .html(html)
                    .find("#tweet")
                    .tweet({
                        username: "WesleyJohnson",
                        count: 5,
                        loading_text: "",
                        callback: function () {
                            $("#content div.blog a").css("color", "#22b92b");
                            $("#content").fadeIn(500, function () {
                                wjInfo.initHashChange();
                            });
                        }
                    });
            },
            error: function (html) {
                console.log(html);
                wjInfo.initHashChange();
            }
        });
    },
    loadContact: function () {
        //Handles loading the contact content
        wjInfo.clearContent();

        $.ajax({
            type: "GET",
            url: "/content/contact.htm",
            dataType: "HTML",
            success: function (html) {
                $("#content").html(html);
                $("#content").fadeIn(500, function () {
                    wjInfo.initHashChange();
                });
            },
            error: function (html, error, status) {
                wjInfo.initHashChange();
            }
        });
    },
    initPortfolioDetail: function (callback) {
        //Inits the portfolio detail section by pushing the navigation up to the top of the page
        $("#contentleft").animate({ paddingTop: "50px" }, 500, function () {
            callback();
        });
    },
    disposeContentMenu: function () {
        $("#contentmenu").css("display", "none");
    },
    disposePortfolioDetail: function () {
        //Kills the portfolio detail section by fadding it out, shifting the navigation back down and then removing itself
        var $contentLeft = $("#contentleft"), $portfolioDetail = $("#portfoliodetail");

        if ($portfolioDetail.text() !== "") {
            $portfolioDetail.find("div").eq(0).fadeOut(500, function () {
                $contentLeft.animate({ paddingTop: "200px" }, 500);
            }).remove();
        }
    },
    getAnchor: function (which) {
        //Checks for the presense of hash in the URL and returns it
        var search = window.location.toString().toLowerCase(), fullAnchor;
        if (search.match("#")) {
            fullAnchor = search.split("#")[1];

            if (fullAnchor.match("-")) {
                return fullAnchor.split("-")[which];
            } else {
                if (which === 0) {
                    return fullAnchor;
                } else {
                    return null;
                }
            }
        } else {
            return null;
        }
    }
};

//Initial jQuery functions that are run when we first load the page
//We're doing things like setting up the AJAX loading img, setting up click handlers and loading intial content;
$(function () {
    //Init the AJAX loading image stuff
    $("#loader img").ajaxStart(function () {
        $(this).fadeIn(100);
    }).ajaxStop(function () {
        $(this).fadeOut(100);
    });

    //Init all our click, hover actions for main navigation stuff
    $("#navigation div.text a").click(function () {
        var $containerLi = $(this).parent().parent();

        if ($containerLi.hasClass("selectedmenu") === false && wjInfo.session.menuTimeout !== null) {
            wjInfo.killHashChange();

            $("#navigation .selectedmenu div").animate({
                width: "200px",
                backgroundColor: "none"
            }, 500).parent().removeClass("selectedmenu");

            $containerLi.find("div").animate({
                width: "430px",
                backgroundColor: "#000"
            }, 300).parent().addClass("selectedmenu");

            switch ($(this).attr("rel")) {
                case "!blog":
                    if (!wjInfo.session.blogLoading) {
                        wjInfo.disposePortfolioDetail();
                        wjInfo.disposeContentMenu();
                        $("#content").fadeOut(500, function () {
                            wjInfo.loadBlog();
                        });
                    }
                    break;

                case "!about":
                    wjInfo.disposePortfolioDetail();
                    wjInfo.disposeContentMenu();
                    $("#content").fadeOut(500, function () {
                        wjInfo.loadAbout();
                    });
                    break;

                case "!portfolio":
                    wjInfo.disposeContentMenu();
                    $("#content").fadeOut(500, function () {
                        wjInfo.loadPortfolio();
                    });
                    break;

                case "!social":
                    wjInfo.disposePortfolioDetail();
                    wjInfo.disposeContentMenu();
                    $("#content").fadeOut(500, function () {
                        wjInfo.loadSocial();
                    });
                    break;

                case "!contact":
                    wjInfo.disposePortfolioDetail();
                    wjInfo.disposeContentMenu();
                    $("#content").fadeOut(500, function () {
                        wjInfo.loadContact();
                    });
                    break;
            }
        }
    }).hover(
        function () {
            $(this).parent().parent().addClass("hovermenu");
        },
        function () {
            $(this).parent().parent().removeClass("hovermenu");
        }
    );


    //Init our interval checks to see if the hash has change
    wjInfo.initHashChange(true);
});

