/*!
 * Tuho-engine (C) 2010-2011 Ville Lahdenvuo
 * See http://tuhoojabotti.com/ for more information
!*/

/*********************\
\**** GLOBALS ********/

//Modernizr.csstransforms = false;
//Modernizr.csstransitions = false;

var curPage = location.pathname.split("/")[1],
    missing = [],
    sloganT;

/*********************\
\**** HELPERS ********/

function ShowWarning(warning, level) {
    var err = $(".warning:contains('" + warning + "')");
    if (err.length) {
        // Error/warning is already found, so let's not repeat it.
        if ($(".amount", err).length) {
            $(".amount", err).fadeOut(100, function () {
                $(this).text(parseInt($(".amount", err).text(), 10) + 1).fadeIn(100);
            });
        } else {
            $('<span> (<span class="amount"> 2</span>x)</span>').appendTo(err).children(".amount").fadeIn(200);
        }
    } else {
        // It's a new error/warning
        if (level === "error") {
            $('<div class="warning" style="display: none;"><strong>ERROR: </strong>' + warning + '</div>')
                .click(function () {
                    $(this).slideUp(300, function () {
                        $(this).remove(); 
                    });
                })
                .appendTo("#warning")
                .slideDown(500);
        } else {
            $('<div class="warning" style="display: none;"><strong>WARNING: </strong>' + warning + '</div>')
                .click(function () {
                    $(this).slideUp(300, function () {
                        $(this).remove();
                    });
                })
                .appendTo("#warning")
                .slideDown(500);
        }
    }
}

function OpenAccordion(article) {
    var sibl = article.siblings();
    $("header h1 a", article).animate(
        {"font-size": "28px"}, 200,
        function () {
            $(".content", article).slideDown(150, function () {
                if (typeof history.replaceState === 'function') {
                    window.history.replaceState({title: curPage}, "", curPage + "/#" + article.attr("id"));
                } else { // So sad...
                    location.hash = article.attr("id");
                }
            });
        }
    );
    $("header h1 a", sibl).animate({"font-size": "20px"}, 200);
    $(".content", sibl).slideUp(150);
}

function UpdateHover(title, instant) {
    if (!title) {
        return;
    }
	var p = $(title).position(),
	    l = $(title).innerWidth();
    if (Modernizr.csstransitions || instant) {
        $("#hover").css({"width": l - 6, "left": p.left});
        $(title).css({
            "color" : "#FFF",
            "bottom": "5px",
            "text-shadow": "0px 0px 8px white"
        }).siblings("a").css({
            "color" : "#FFCF79",
            "bottom": "0px",
            "text-shadow": "none"
        });
    } else { // So sad...
        $("#hover").stop(true).animate({"width": l - 6, "left": p.left}, 200);
        $(title).animate({
            "color" : "rgb(255,255,255)",
            "bottom": "5px"
        }, 200).css({
            "text-shadow": "0px 0px 8px white"
        }).siblings("a").stop(true).animate({
            "color" : "rgb(255,207,121)",
            "bottom": "0px"
        }, 200).css({
            "text-shadow": "none"
        });

    }
}

function UpdateSlogan() {
    if (Modernizr.csstransitions) {
        $("body > header h2").css({
            "bottom" : "20px",
            "opacity": "0.2",
            "-webkit-transform": "scale(0.2,0.2)",
            "-khtml-transform" : "scale(0.2,0.2)",
            "-moz-transform"   : "scale(0.2,0.2)",
            "-ms-transform"    : "scale(0.2,0.2)",
            "-o-transform"     : "scale(0.2,0.2)",
            "transform"        : "scale(0.2,0.2)"
        });
        setTimeout(function () {
            $("body > header h2").load("/api/slogan", function (data, status) {
                if (status !== "success") {
                    ShowWarning("Error while loading slogan!");
                }
                $("body > header h2").css({
                    "bottom" : "0px",
                    "opacity": "1",
                    "-webkit-transform": "scale(1,1)",
                    "-khtml-transform" : "scale(1,1)",
                    "-moz-transform"   : "scale(1,1)",
                    "-ms-transform"    : "scale(1,1)",
                    "-o-transform"     : "scale(1,1)",
                    "transform"        : "scale(1,1)"
                });
            });
        }, 800);
    } else { // So sad...
        $("body > header h2").fadeOut(800, function () {
            $(this).load("/api/slogan", function (data, status) {
                if (status !== "success") {
                    ShowWarning("Error while loading slogan!");
                } else {
                    $(this).fadeIn(800);
                }
            });
        });
    }
}

function LoadPage(page, skip) {
    $("#page").fadeOut(200, function () {
        var section = this;
        $.getJSON("api/page/" + page, function (data, textStatus, xhr) {
            if (textStatus === "success") {
                $("h1:first", section).html('&bull; ' + data.title + ' &bull;');
                $("#content", section).html(data.content);
                $("head title").text(data.title + " – Destroying Pictures");
                $("article").each(function () {
                    var article = $(this),
                        title   = $("header > hgroup > h1 > a", article);
                    title.click(function (e) {
                        e.preventDefault();
                        setTimeout(function () {
                            OpenAccordion(article);
                        }, 1);
                    });
                });
                $(section).fadeIn(100);
                if (!skip) { // Change the url!
                    window.history.pushState({title: page}, "", page + "/");
                }
                curPage = page;
                UpdateHover($('nav a[href*="' + curPage + '"]'));
                OpenAccordion($("article:first"));
            } else {
                ShowWarning("Failed to load the page, try again later.");
            }
        });
    });
}

function LoadTweets(s) {
    jQuery.getJSON("http://search.twitter.com/search.json?lang=en&q=" + escape(s) + "&callback=?", function(d) {
        if (d.results.length){
            console.log(d);
            console.log(d.results[Math.floor(d.results.length * Math.random())].text);
        }
    });
}

/*********************\
\**** INITIALIZE *****/

$(document).ready(function () {

    // HASH AND HOVER EFFECT
    if (!location.hash) {
        OpenAccordion($("article:first"));
    }
    UpdateHover($('nav a[href="' + curPage + '/"]'), true); // Instantly throw the hover effect in place

    $("nav").mouseleave(function () {
        setTimeout(function () {
            UpdateHover($('nav a[href="' + curPage + '/"]'));
        },
        300);
    }).trigger('mouseleave');

    // MODERN EYECANDY    -    NAVIGATION
    if (Modernizr.csstransitions) {
        $("nav a").css({
            "-webkit-transition": "all 0.2s ease-in",
            "-khtml-transition" : "all 0.2s ease-in",
            "-moz-transition"   : "all 0.2s ease-in",
            "-ms-transition"    : "all 0.2s ease-in",
            "-o-transition"     : "all 0.2s ease-in",
            "transition"        : "all 0.2s ease-in"
        });
        $("#hover").css({
            "-webkit-transition": "all 0.3s ease",
            "-khtml-transition" : "all 0.3s ease",
            "-moz-transition"   : "all 0.3s ease",
            "-ms-transition"    : "all 0.3s ease",
            "-o-transition"     : "all 0.3s ease",
            "transition"        : "all 0.3s ease"
        });
        $("body > header h2").css({
            "-webkit-transition": "all 0.8s ease",
            "-khtml-transition" : "all 0.8s ease",
            "-moz-transition"   : "all 0.8s ease",
            "-ms-transition"    : "all 0.8s ease",
            "-o-transition"     : "all 0.8s ease",
            "transition"        : "all 0.8s ease"
        });
    } else {
        missing.push("CSS3 Transitions");
    }
    $("#hover").css({
        "height"        : "23px",
        "display"       : "block"
    });
    if (Modernizr.history) {
        $(window).bind("popstate", function (e) {
            e = e.originalEvent;
            if (e.state) {
                LoadPage(e.state.title, true);
            } else {
                window.history.replaceState({title: curPage}, "", curPage);
            }
        });
        $("nav a").click(function (e) {
            e.preventDefault();
            LoadPage(this.href.split("/")[3]);
        });
    } else {
        missing.push("HTML5 History API");
    }
    $("nav a").hoverIntent({
        "over"  : function () {
            UpdateHover(this);
        },
        "out": function () {},
        "interval": 50
    });
    if (!Modernizr.borderradius) {
        missing.push("CSS 3 Border Radius (The corners ought to be round!)");
    }

    // ACCORDIONS
    $("article").each(function () {
        var article = $(this),
            title   = $("header > hgroup > h1 > a", article);
        title.click(function (e) {
            e.preventDefault();
            setTimeout(function () {
                OpenAccordion(article);
            }, 1);
        });
    });

    // SLOGANS / QUOTES
    $("body > header h2").click(function () {
        UpdateSlogan();
    });
    sloganT = setInterval(UpdateSlogan, 12000);
    // Stop polling for slogans if the tab/window is hidden!
    $(document).bind("webkitvisibilitychange", function () {
        if (document.webkitHidden) {
            window.clearTimeout(sloganT);
        } else { // Tab/Window is visible again!
            UpdateSlogan();
            sloganT = setInterval(UpdateSlogan, 12000);
        }
    });
    // COMPATIBILITY WARNINGS
    if (missing.length > 1) {
        ShowWarning("You are missing " + missing.slice(0, -1).join(", ") + " and " + missing.pop() + ". Update your browser in order to enhance your experience.");
    } else if(missing.length == 1) {
        ShowWarning("You are missing " + missing.pop() + ". Update your browser in order to enhance your experience.");
    }
});

