﻿/// <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 menuTimeout = 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 $containerDiv = $(this).parent();
        var $containerLi = $(this).parent().parent();

        if ($containerLi.hasClass("selectedmenu") == false && menuTimeout != null) {
            killHashChange();

            $("#navigation .selectedmenu div").animate({
                width: "10px",
                textalign: "center"
            }, 500).parent().removeClass("selectedmenu");

            $containerLi.find("div").animate({
                width: "200px",
                textalign: "left"
            }, 300).parent().addClass("selectedmenu");

            switch ($(this).attr("rel")) {
                case "blog":
                    disposePortfolioDetail();
                    disposeContentMenu();
                    $("#content").fadeOut(500, function() { loadBlog(); });
                    break;

                case "about":
                    disposePortfolioDetail();
                    disposeContentMenu();
                    $("#content").fadeOut(500, function() { loadAbout(); });
                    break;

                case "portfolio":
                    disposeContentMenu();
                    $("#content").fadeOut(500, function() { loadPortfolio(); });
                    break;

                case "social":
                    disposePortfolioDetail();
                    disposeContentMenu();
                    $("#content").fadeOut(500, function() { loadSocial(); });
                    break;

                case "contact":
                    disposePortfolioDetail();
                    disposeContentMenu();
                    $("#content").fadeOut(500, function() { 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
    initHashChange(true);
});


//Handles setting up the interval for checking has changes
function initHashChange() {
    menuTimeout = window.setInterval("checkHashChange(true)", 500);
}

//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
function killHashChange() {
    if (menuTimeout)
        window.clearInterval(menuTimeout);

    menuTimeout = null;
}

//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
function checkHashChange(firstLoad) {
    if (window.location.hash) {
        var primaryAnchor = getAnchor(0);
        var secondaryAnchor = 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();
    }
}

//Handles loading the blog content
function loadBlog() {
    $("#content").html("");

    $.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!
            setTimeout(function() {
                $("#content").find("div:lt(2)").show();
                $("#content").fadeIn(500);
                $("#contentmenu").fadeIn(500, function() { initHashChange(); });
            }, 500);
        },
        error: function(result, error, status) {
            console.log(error);
            console.log(status);
            initHashChange();
        }
    });

    $("#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.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 (getAnchor(0) == null)
        window.location.hash = "blog-1";
}

//Handles loading the about content
function loadAbout() {
    $("#content").html("");

    $.ajax({
        type: "GET",
        url: "/content/about.htm",
        dataType: "HTML",
        success: function(html) {
            $("#content").html(html);
            $("#content").fadeIn(500, function() { initHashChange(); });
        },
        error: function(html, error, status) {
            initHashChange();
        }
    });
}

//Handles loading the portfolio contnet
function loadPortfolio() {
    $("#content").html("");

    $.ajax({
        type: "GET",
        url: "/content/portfolio.htm",
        dataType: "HTML",
        success: function(html) {
            $("#content")
            .html(html)
            .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");
                var detailID = imgID + "Detail";

                $("#portfoliodetail").html("").append($("#content").find("#" + detailID).clone().fadeIn(500));
            }).hover(
                function() {
                    $(this).addClass("hovermenu");
                },
                function() {
                    $(this).removeClass("hovermenu");
                }
            );

            initPortfolioDetail(function() {
                $("#content").find("img").eq(0).click();
            });

            $("#contentmenu").fadeIn(500, function() { initHashChange(); });
        },
        error: function(html) {
            console.log(html);
        }
    });

    $("#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 (getAnchor(0) == null)
        window.location.hash = "portfolio-1";
}

//Handles loading the social content
function loadSocial() {
    $("#content").html("");

    $.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() { initHashChange(); });
                }
            });
        },
        error: function(html) {
            console.log(html);
            initHashChange();
        }
    });
}

//Handles loading the contact content
function loadContact() {
    $("#content").html("");

    $.ajax({
        type: "GET",
        url: "/content/contact.htm",
        dataType: "HTML",
        success: function(html) {
            $("#content").html(html);
            $("#content").fadeIn(500, function() { initHashChange(); });
        },
        error: function(html, error, status) {
            initHashChange();
        }
    });
}

//Inits the portfolio detail section by pushing the navigation up to the top of the page
function initPortfolioDetail(callback) {
    $("#contentleft").animate({ paddingTop: "50px" }, 500, function() {
        callback();
    });
}

function disposeContentMenu() {
    $("#contentmenu").css("display","none");
}

//Kills the portfolio detail section by fadding it out, shifting the navigation back down and then removing itself
function disposePortfolioDetail() {
    var $contentLeft = $("#contentleft");
    var $portfolioDetail = $("#portfoliodetail");

    if ($portfolioDetail.text() != "") {
        $portfolioDetail.find("div").eq(0).fadeOut(500, function() {
            $contentLeft.animate({ paddingTop: "200px" }, 500);
        }).remove();
    }
}

//Checks for the presense of hash in the URL and returns it
function getAnchor(which) {
    var search = window.location.toString().toLowerCase();
    if (search.match("#")) {
        var fullAnchor = search.split("#")[1];
        if (fullAnchor.match("-")) {
            return fullAnchor.split("-")[which];
        } else {
            if (which == 0) {
                return fullAnchor;
            } else {
                return null;
            }
        }
    } else {
        return null;
    }
}