/* Init */
$(document).ready(function()
{
    if ($.cookie('autoplay') === null)
    {
        $.cookie('autoplay', "on", {path: '/'});
    }

    setup_pageinit();
    setup_sidebar();
    resize_adjust_work();
    $(window).resize(resize_adjust_work);

    setup_tooltips("#header");

    $("#work-menu").data("current", $("#work-menu").children().first());
    $("#work-menu-up").click(function(e)
    {
        var target = $("#work-menu").data("current").prev();
        if ($(target).length > 0)
        {
            $("#work-menu").scrollTo(target, 200);
            $("#work-menu").data("current", target);
            if ($(target).prev().length == 0)
            {
                deactivate_stateimg(e.currentTarget);
            }
            if (!$("#work-menu-down").hasClass("state-image"))
            {
                activate_stateimg("#work-menu-down");
            }
        }
    });
    $("#work-menu-down").click(function(e)
    {
        var target = $("#work-menu").data("current").next();
        if ($(target).length > 0)
        {
            $("#work-menu").scrollTo(target, 200);
            $("#work-menu").data("current", target);
            if ($(target).next().length == 0)
            {
                deactivate_stateimg(e.currentTarget);
            }
            if (!$("#work-menu-up").hasClass("state-image"))
            {
                activate_stateimg("#work-menu-up");
            }
        }
    });
    $(".work-menu-current").first().each(function()
    {
        var target = $(this).parents(".work-menu-item");
        $("#work-menu").scrollTo(target, 0);
        $("#work-menu").data("current", target);
    });
    if ($("#work-menu").data("current").prev().length == 0)
    {
        deactivate_stateimg("#work-menu-up");
    }
    if ($("#work-menu").data("current").next().length == 0)
    {
        deactivate_stateimg("#work-menu-down");
    }

    $(".work-menu-link").mouseenter(function(e)
    {
        $(e.currentTarget).addClass("work-menu-hover");
    });
    $(".work-menu-link").mouseleave(function(e)
    {
        $(e.currentTarget).removeClass("work-menu-hover");
    });
    $(".work-menu-link").click(function(e)
    {
        var uri = $(e.currentTarget).find(".uri").html();
        $(".work-menu-current").removeClass("work-menu-current");
        var links = $(".work-menu-link");
        for (var i = 0; i < links.length; i++)
        {
            if ($(links[i]).find(".uri").html() === uri)
            {
                $(links[i]).addClass("work-menu-current");
            }
        }
        load_tiles(uri);
    });

    if ($("#tiles-wrapper").children().length > 0)
    {
        $(".tile").fadeOut(0);
        fadein_tiles($("#tiles-wrapper").children().first());
    }
});

/* resize afer all has loaded - fixes scrollbar width bug */
$(window).load(function()
{
    resize_adjust_work();

    if ($("#project").find(".pid").length > 0)
    {
        show_project($("#project").children().clone());
    }
});

function resize_adjust_work()
{
    var width = resize_adjust();
    $("#work-menu").width(width - 248);
    $("#project").width(width - 40);
    $("#soundcloud-embed").width($("#project").width() - $("#soundcloud-label").width());
    $("#content").width($("#content-wrapper").width() - $("#sidebar").outerWidth(true));

    if ($("#project").data('is-open'))
    {
        var project_height = $("#project").outerHeight(true) + 34;
        $("#content-wrapper").css('top', project_height);
        $("#project-wrapper").height(project_height);

        var left = $("#mediareel-list").css('left');
        if (typeof(left) === 'string')
        {
            var lshift = Number(left.replace(/px/, ''));
            if (lshift - $("#project-mediareel").width() + $("#mediareel-list").width() <= 0)
            {
                $("#mediareel-right").fadeOut(0);
            }
            else
            {
                $("#mediareel-right").fadeIn(0);
            }
        }
    }

    $("#content, #sidebar").css("min-height", $(window).height() - 220);
}

function setup_sidebar()
{
    $("#sidebar img").each(function()
    {
        $(this).data("uri", $(this).attr("title"));
        $(this).removeAttr("title");
        $(this).bind("mouseenter mouseleave", function(e)
        {
            var alt = $(this).attr("alt");
            if (typeof(alt) === "string" && alt.length > 0)
            {
                $(this).attr("alt", $(this).attr("src"));
                $(this).attr("src", alt);
            }
        });
        $(this).click(function(e)
        {
            uri = $(e.currentTarget).data("uri");
            if (typeof(uri) === "string" && uri.length > 0)
            {
                $(".work-menu-current").removeClass("work-menu-current");
                var links = $(".work-menu-link");
                for (var i = 0; i < links.length; i++)
                {
                    if ($(links[i]).find(".uri").html() === uri)
                    {
                        $(links[i]).addClass("work-menu-current");
                    }
                }
                $(window).scrollTo({top: 22, left: 0}, 600);
                load_tiles(uri);
            }
        });
    });
}

function setup_tiles(selector)
{
    $(selector).mouseenter(function(e)
    {
        $(e.currentTarget).clearQueue().stop();
        $(e.currentTarget).animate({ backgroundColor: '#101010' }, 200);
    });
    $(selector).mouseleave(function(e)
    {
        $(e.currentTarget).clearQueue().stop();
        $(e.currentTarget).animate({ backgroundColor: '#1e1e1e' }, 600);
    });

    $(selector).click(function ()
    {
        load_project($(this).find('.pid').html());
    });
}

function load_tiles(uri)
{
    $.ajax({ url: base_url()+"work/load_tiles/"+get_lang()+"/"+uri,
             global: false,
             async: true,
             tilesUri: uri,
             success: function(data, textStatus, jqXHR)
             {
                 set_uri('tiles', this.tilesUri);
                 $("#tiles-wrapper").data("new-tiles", data);
                 if ($("#project").data("is-open"))
                 {
                     close_project(show_tiles);
                 }
                 else
                 {
                     show_tiles();
                 }
             } });
}

function load_project(pid)
{
    $.ajax({ url: base_url()+"work/load_project/"+get_lang()+
                  "/project/"+pid,
             global: false,
             async: true,
             projectId: pid,
             success: function(data, textStatus, jqXHR)
             {
                 set_uri('project', this.projectId);
                 show_project($(data));
             } });
}

function show_tiles()
{
    var tiles_fadeout = ($("#tiles-wrapper").children().length > 0) ? 200 : 0;
    $("#tiles-wrapper").fadeOut(tiles_fadeout, function()
    {
        $("#tiles-wrapper").empty();
        $("#tiles-wrapper").html($("#tiles-wrapper").data("new-tiles"));
        $("#tiles-wrapper").fadeIn(0);
        $(".tile").fadeOut(0);
        fadein_tiles($("#tiles-wrapper").children().first());
    });
}

function fadein_tiles(tile)
{
    $(tile).fadeIn(200, function()
    {
        setup_tiles(this);
        if ($(this).next().length > 0)
        {
            fadein_tiles($(this).next());
        }
    });
}

function show_project(html)
{
    $("#project").data('is-open', false);
    $(window).scrollTo({top: 22, left: 0}, 600, { onAfter: function()
    {
        var fadeout_duration = 300;
        var resize_duration = 600;
        if ($("#project-wrapper").height() == 0)
        {
            fadeout_duration = 0;
            resize_duration = 1200;
        }
        $("#project").fadeOut(fadeout_duration, function()
        {
            clean_tooltips("#project");
            $("#project").empty();

            if ($.cookie('autoplay') !== "on")
            {
                $(html).find("param").each(function()
                {
                    $(this).val($(this).val().replace(/&auto_play\=true/g, ''));
                });
                $(html).find("embed").each(function()
                {
                    $(this).attr("src", $(this).attr("src").replace(/&auto_play\=true/g, ''));
                });
            }
            $("#project").html(html);

            var project_height = $("#project").outerHeight(true) + 34;
            $("#project").data('soundcloud', $("#soundcloud-embed").detach());
            $("#project").data('mediareel', $("#mediareel-list").detach());

            $("#content-wrapper").animate(
                { top: project_height + 'px' },
                { duration: resize_duration,
                  step: function ()
                  {
                      $("#project-wrapper").height($(this).css('top'));
                  },
                  complete: function()
                  {
                      $("#project").data('is-open', true);
                      $("#project-soundcloud").append($("#project").data('soundcloud'));
                      resize_adjust_work();
                      setup_project_buttons();
                      setup_stateimg('#project .state-image');
                      setup_extlinks('#project a');
                      setup_tooltips("#project");
                      $("#project").fadeIn(600, function()
                      {
                          setup_mediareel();
                      });
                  } });
        });
    } });
}

function setup_project_buttons()
{
    var cur_pid = $("#project .pid").html();
    var cur_tile = $('.tile .pid[title="'+cur_pid+'"]').parents('.tile');
    if ($(cur_tile).prev().length == 0)
    {
        deactivate_stateimg("#project .project-prev");
    }
    if ($(cur_tile).next().length == 0)
    {
        deactivate_stateimg("#project .project-next");
    }
    $("#project .project-prev").click(function(e)
    {
        var cur_pid = $("#project .pid").html();
        var cur_tile = $('.tile .pid[title="'+cur_pid+'"]').parents('.tile');
        if ($(cur_tile).prev().length > 0)
        {
            load_project($(cur_tile).prev().find('.pid').html());
        }
    });
    $("#project .project-next").click(function(e)
    {
        var cur_pid = $("#project .pid").html();
        var cur_tile = $('.tile .pid[title="'+cur_pid+'"]').parents('.tile');
        if ($(cur_tile).next().length > 0)
        {
            load_project($(cur_tile).next().find('.pid').html());
        }
    });
    $("#project .project-close").click(function(e)
    {
        close_project(null);
    });
    if ($.cookie('autoplay') === "on")
    {
        $(".autoplay-on").addClass("autoplay-current");
    }
    else
    {
        $(".autoplay-off").addClass("autoplay-current");
    }
    $(".autoplay-on").click(function(e)
    {
        $(".autoplay-on").addClass("autoplay-current");
        $(".autoplay-off").removeClass("autoplay-current");
        $.cookie('autoplay', "on", {path: '/'});
    });
    $(".autoplay-off").click(function(e)
    {
        $(".autoplay-off").addClass("autoplay-current");
        $(".autoplay-on").removeClass("autoplay-current");
        $.cookie('autoplay', "off", {path: '/'});
        if ($("#soundcloudPlayer").length > 0)
        {
            soundcloud.getPlayer('soundcloudPlayer').api_pause();
        }
    });
    $(".autoplay-on, .autoplay-off").mouseenter(function(e)
    {
        $(e.currentTarget).addClass("autoplay-hover");
    });
    $(".autoplay-on, .autoplay-off").mouseleave(function(e)
    {
        $(e.currentTarget).removeClass("autoplay-hover");
    });
}

function close_project(callback)
{
    $("#project").data('is-open', false);
    $("#project").data('close-callback', callback);
    set_uri('project', null);
    $("#project").fadeOut(300, function()
    {
        clean_tooltips("#project");
        $("#project").empty();
        $("#content-wrapper").animate(
            { top: '0px' },
            { duration: 1200,
              step: function()
              {
                  $("#project-wrapper").height($(this).css('top'));
              },
              complete: function()
              {
                  if ($("#project").data("close-callback"))
                  {
                      $("#project").data("close-callback")();
                  }
              } });
    });
}

function setup_mediareel()
{
    $("#project-mediareel").append($("#project").data('mediareel'));
    $("#mediareel-list").children().fadeOut(0);
    $("#mediareel-list").children().last().css('margin-right', 0);
    $("#mediareel-list").width($($("#mediareel-list").children().first()).outerWidth(true));

    $("#project-mediareel").scrollable({ vertical: false, 
                                         mousewheel: false, 
                                         keyboard: true,
                                         speed: 200 });
    var scrollable = $("#project-mediareel").data("scrollable");
    scrollable.onBeforeSeek(function(event, index)
    {
        if ($(this).data("animating") || $(this).data("scrolling"))
        {
            return false;
        }
        $(this).data("scrolling", true);
        if (this.getIndex() < index)
        {
            var remaining = 0;
            var items = this.getItems();
            for (var i = index; i < items.length; i++)
            {
                remaining += $(items[i]).outerWidth(true);
            }
            if (remaining < $("#project-mediareel").width())
            {
                var cur = $("#mediareel-list").css('left').replace(/px/, '') - $("#project-mediareel").width() + $("#mediareel-list").width();
                if (cur > 0 && !$(this).data("animating"))
                {
                    $(this).data("animating", true);
                    $("#mediareel-list").animate(
                        { left: "-="+cur },
                        100,
                        function()
                        {
                            $($("#project-mediareel").data("scrollable")).data("animating", false);
                            adjust_reel_arrows();
                        });
                                                 
                }
                $(this).data("scrolling", false);
                return false;
            }
        }
        else if (index < this.getIndex())
        {
            var onleft = 0;
            var items = this.getItems();
            for (var i = 0; i < this.getIndex(); i++)
            {
                onleft -= $(items[i]).outerWidth(true);
            }
            cur = Number($("#mediareel-list").css('left').replace(/px/, ''));
            if (cur < onleft)
            {
                $(this).data("animating", true);
                $("#mediareel-list").animate(
                    { left: onleft },
                    100,
                    function()
                    {
                        $($("#project-mediareel").data("scrollable")).data("animating", false);
                        adjust_reel_arrows();
                    });
                $(this).data("scrolling", false);
                return false;
            }
        }
    });
    scrollable.onSeek(function(event, index)
    {
        $(this).data("scrolling", false);
        adjust_reel_arrows();
    });
    scrollable.focus();

    $("#mediareel-left").click(function(e)
    {
        $("#project-mediareel").data("scrollable").prev(200);
    });
    $("#mediareel-right").click(function(e)
    {
        $("#project-mediareel").data("scrollable").next(200);
    });

    fadein_reelitems($("#mediareel-list").children().first());
}

function adjust_reel_arrows()
{
    var left = $("#mediareel-list").css('left');
    if (typeof(left) === 'string')
    {
        var lshift = Number(left.replace(/px/, ''));
        if (lshift == 0)
        {
            $("#mediareel-left").clearQueue();
            $("#mediareel-left").fadeOut(150);
        }
        else
        {
            $("#mediareel-left").clearQueue();
            $("#mediareel-left").fadeIn(150);
        }
        if (lshift - $("#project-mediareel").width() + $("#mediareel-list").width() <= 0)
        {
            $("#mediareel-right").clearQueue();
            $("#mediareel-right").fadeOut(150);
        }
        else
        {
            $("#mediareel-right").clearQueue();
            $("#mediareel-right").fadeIn(150);
        }
    }
}

function fadein_reelitems(item)
{
    adjust_reel_arrows();
    $(item).fadeIn(300, function()
    {
        adjust_reel_arrows();
        if ($(this).next().length > 0)
        {
            $("#mediareel-list").width($("#mediareel-list").width() + $(this).next().outerWidth(true));
            fadein_reelitems($(this).next());
        }
        else
        {
            $("#mediareel-list").children().fadeIn(0);
            $("#mediareel-list").children(".mediareel-embed").click(function(e)
            {
                if ($("#soundcloudPlayer").length > 0)
                {
                    soundcloud.getPlayer('soundcloudPlayer').api_pause();
                }
            });
        }
    });
}

