$(document).ready( function() {
    cache.create();
    gallery.create();
    project.create();
    pages.create();

    $('a[href*=]').click(function() {
        if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') && location.hostname == this.hostname) {
        var $target = $(this.hash);
            if(this.hash.indexOf('project') != -1)
                return false;

            $target = $target.length && $target || $('[name=' + this.hash.slice(1) +']');
            if ($target.length) {
                var targetOffset = $target.offset().top;
                $('html,body').animate({scrollTop: targetOffset}, 1000);
                _gaq.push(['_trackEvent', 'Navigation', this.hash.slice(1)]);
                return false;
            }
        }
    });

    $(window).scroll(function(e) {
        if($(this).scrollTop() >= $('div.projects').position().top - 40)
        {
            $('div#scroller').fadeIn('fast');
        } else {
            $('div#scroller').fadeOut('fast');
        }

    });

    if (location.hash == '#teknologia') {
        // Check that forces opening of a subpage
        var link = $('a[href=teknologia]');
        $('html,body').animate({scrollTop: link.offset().top}, 1000);
        link.click();
    }

    var select = function() {
        $('.comment')
            .removeClass('selected');
        $(this)
            .addClass('selected')
            .find('.callout').css('left', ($(this).width() - 40) / 2);
        $('.comments > .text')
            .html($(this).find('.text').html());
    };

    select.call($('.comment.selected'));
    $('.comment').live('click', function() {
        select.call(this);
    });
});

$(window).bind('hashchange', function() {
    console.log(location.hash);
});

taiste = {
    wrap: function() {
        var params = [],
            callback = null;

        $(arguments).each(function(i,o) { params.push(o); });
        callback = params.pop();

        return function() {
             $(arguments).each(function(i,o) { params.push(o); });
             callback.apply(null, params);
         }
    },

    link: function(current, next, href, handler) {
        current.removeClass('active');
        next.addClass('active');
    }
}

cache = {
    create: function() {
        this._cache = {}
    },
    get: function(key, handler) {
        if( cache._cache[key] == null)
        {
            $.getJSON(base_url+key+'.json', null, function(data, textStatus) {
                cache._cache[key] = data;
                handler(data);
            })
        }
        else
        {
            handler(cache._cache[key]);
            return true;
        }

        return false;
    }
}

gallery = {
    create: function() {

        $("div.project div.photos ul").jqGalScroll({height: '620', width: '960', direction: 'horizontal', ease:'easeOutCubic',speed: 750});
        $("div.project div.photos a").click( gallery.onImageSelected );
        if( gallery.previousImage && gallery.previousImage != "0" )
        {
            $("div.projects div.info").toggle();
        }
        gallery.previousImage = "0"
    },
    onImageSelected: function(event) {
        var id = '#image-';
        var target = event.target.href;
        target = target.substring(target.indexOf(id) + id.length);

        if( ( (gallery.previousImage != "0" && target == "0") || gallery.previousImage == "0" && target != "0") )
        {
            var easing = 'easeOutCubic';

            $("div.projects div.info")
                .toggle("slide", {
                    direction: "left", easing: easing
                }, 500);
        }
        gallery.previousImage = target;
    }
}

var project_loading = false;
project= {
    create: function() {
        $("div.projects ul.submenu a").click(project.onProjectSelected);
        project.currentProject = "0";
    },
    onProjectSelected: function(event) {
        _gaq.push(['_trackEvent', 'Projects', $(this).text()]);
        event.preventDefault();

        var id = '#project-';
        var index = event.target.href;
        if(project.currentProject == /#project-(\d+)/.exec(index)[1] || project_loading) { return false; }
        project_loading = true;

        index = index.substring(index.indexOf(id) + id.length );
        if( project.currentProject != index )
        {
            $('li#project-'+project.currentProject).removeClass('active');
            $('li#project-'+index).addClass('active');

            if(index == 'showreel')
            {
                cache.get('showreel', function(data) {
                        $("div.projects div.project").fadeOut(500, function() { project.showreel(data); });
                    });
            }
            else
            {
                fadeOutItem = "div.projects div.project";

                if(project.currentProject == 'showreel')
                {
                    fadeOutItem = "div.projects div.showreel"

                    if($("div.projects div.showreel div.videowindow div.image").is(':hidden'))
                    {
                        $("div.projects div.showreel div.videowindow div.image").show();
                        $("div.projects div.showreel div.videowindow div.video").hide();
                    }
                }

                cache.get('projects/'+index, function(data) {
                    $(fadeOutItem).fadeOut(500, function() { project.update(data); });
                });
            }
            project.currentProject = index;
        }
    },
    update: function(data) {
        var TITLE = 0, CATEGORY = 1, DESCRIPTION = 2, LINK = 3, PHOTOS = 4;
        var info = $("div.project div.info"), photos = $("div.project div.photos");

        info.find("h1").html(data[TITLE]); info.find("h2").html(data[CATEGORY]);
        info.find("div.project-description").html(data[DESCRIPTION]);

        if( data[LINK] != "" )
        {
            info.find(".link").show();
            info.find("a").attr('href', data[LINK]).html(data[LINK]);
        } else
        {
            info.find(".link").hide();
        }

        photos.children().remove();
        photos.append('<ul></ul>')

        $(data[PHOTOS]).each(function(index, data) {
            photos.find('ul').append('<li><img src="'+data+'" /></li>')
        })

        gallery.create();
        $("div.projects div.project").fadeIn(500,
            function() { project_loading = false; });
    },
    showreel: function(data) {
        var showreel = $("div.projects div.showreel");

        showreel.html(data[0]);
        $("div.projects div.showreel").fadeIn(500);
        $("div.projects div.showreel a").click(project.playShowreel);
    },
    playShowreel: function(event) {
        event.preventDefault();
        $("div.projects div.showreel div.videowindow div.image").hide();
        $("div.projects div.showreel div.videowindow div.video").show();
    }
}

pages = {
    create: function() {
        $("div.content:not(.projects) ul.submenu a").click( function(event) {
            var context = $(event.target).parents("div").attr('id');
            _gaq.push(['_trackEvent', 'Pages', $(event.target)]);
            pages.onPageSelected(context, event);
        });

        pages.currentPage = {'content-1': 0, 'content-2':0};
    },
    onPageSelected: function(context, event) {
        event.preventDefault();
        var ul = $("div#"+context+" ul.submenu"),
            next = $(event.target).parent("li"),
            current = $(ul.children()[pages.currentPage[context]]);

        taiste.link(current, next, current.find("span").data('href'), taiste.wrap(context, pages.onPageSelected));

        cache.get($(event.target).attr('href'), taiste.wrap(context, pages.update) );

        pages.currentPage[context] = ul.children().index(next);
    },
    update: function(context, data) {
        var content = $("div#"+context+" div.fp");
        if( $.browser.msie )
        {
            content.html( data[2] );
        } else
        {
            content.slideUp(500, function(){
                content.html( data[2] );
                content.slideDown(500);
            });
        }
    }
}

