/*global $, FS, document, window */ 

// Namespace
var FS = FS || {};

// Modules
(function (ns) {
    
    "use strict";
    
    ns.dependencies = { 'jQuery' : '1.6.2', 'Sammy.js' : '0.7.0' };
    
    ns.tmpl = {
        
        post : function (data) {
            
            var html = '';
            
            html += '<li class="project">';
                html += '<a href="'+ data.permalink +'">';
                    html += '<div class="project-description">';
                        html += '<h3>'+ data.title +'</h3>';
                        html += '<p class="project-client">';
                        
                        for ( var j in data.client ) {

                            html += ''+ data.client[j].name +'';

                        }
                        
                        html += '</p>';
                        html += '<p class="project-category">'+ data.category[0].name +'</p>';
                    html += '</div>';
                    html += '<div class="project-slideshow">';
                    
                    for ( var i = 0; i < data.slides.length; i ++ ) {
                        
                        html += '<img src="'+ data.slides[i].location +'" alt="" />';
                        
                    }
                    
                    html += '</div>';
                html += '</a>';
            html += '</li>';
            
            return html;
            
        },
        description : function (data) {
            
            var html = '';
            
            html += '<h3>'+ data.title +'</h3>';
            html += '<p>';
            for ( var k in data.client ) { html += ''+ data.client[k].name +''; }
            html += ' / '+ data.category[0].name +'</p>';
            html += '<p>'+  data.excerpt +'</p>';
            
            return html;
            
        }
        
    };
    
    ns.get_projects = function(href) {
        
        this.json_url = href + '?json';
        
        var self = this;
        
        var $loader = $('#loader'),
            $portfolio = $('#portfolio'),
            $projects = null;
        
        $loader.show();
        
        $portfolio.empty();
        
        $.getJSON(self.json_url, function (data) {
            
            var $posts = data.posts,
                total = $posts.length,
                i;
            
            for ( i = 0; i < total; i++ ) {
                
                $portfolio.append( ns.tmpl.post( $posts[i] ) );
                
            }
            
            ns.portfolio();
            
        });
        
    };
    
    ns.get_project = function(href) {
        
        this.json_url = href + '?json';
        
        var self = this;
        
        var $loader = $('#loader'),
            $container = $('#container'),
            $overlay = $('#project'),
            $content = $overlay.find('.content'),
            $slides = $overlay.find('#project-slides'),
            $description = $overlay.find('#project-description'),
            $close = $overlay.find('.close-page');
        
        var scroll_top = 0,
            overlay_height = 0,
            time = 500;
        
        $loader.show();
        
        $slides.empty();
        
        $description.empty();
        
        scroll_top = $(window).scrollTop();
        
        $.getJSON(self.json_url, function (data) {
            
            $slides.css('opacity', '0').append( data.content );
            
            $description.append( ns.tmpl.description(data) );
            
            overlay_height = $content.height() + 100;
            
            $overlay.css({
                
                top : -overlay_height,
                height : overlay_height
                
            }).animate({
                
                top : 0
                
            }, time * 2, function () {
                
                $('#loader').hide();
                
                $container.css('position','fixed');
                
                $slides.fadeTo(time, 1);
                
                $close
                    .animate({ bottom : 0 }, time / 2)
                    .click(function () {
                        
                        $close.animate({ bottom : -80 }, time / 2);
                        
                        $slides.fadeTo(time / 2, 0);
                        
                        $container.css('position','static');
                        
                        $overlay.animate({

                            top : -overlay_height

                        }, time * 2);
                        
                        $('html,body')
                            .stop()
                            .animate({ scrollTop : scroll_top }, time);
                        
                    });
                
            });
            
            $('html,body').stop(true, true).animate({ scrollTop : 0 }, time);
            
        });
        
    };
    
    ns.get_about = function () {
        
        var $hand = $('#hand'),
            $about = $('#about');
        
        $hand.animate({
            
            bottom : -40
            
        }, 500, function () {
            
            $hand
                .css('background-position', '-64px 0')
                .animate({ bottom : -40 }, 250);
            
            $about.animate({ top : 0 }, 1000, function () {
                
                $hand.css({ 'background-position' : '-128px 0', 'cursor' : 'pointer' });
                
            });
            
        });
        
        $hand.click(function () {
            
            $about.animate({ top : -600 }, 1000, function () {
                
                $hand
                    .css({ 'background-position' : '0 0', 'cursor' : 'auto' })
                    .animate({ bottom : -120 }, 500);
                
            });
            
        });
        
    };
    
    ns.portfolio = function () {
        
        var $portfolio = $('#portfolio'),
            $projects = $portfolio.children(),
            $scroll = $('.scroll-top');
        
        ns.project();
        
        $projects.each(function () {
            
            var $project = $(this),
                $slideshow = $project.find('.project-slideshow'),
                $images = $slideshow.find('img');
            
            var time = 500,
                current = 0,
                total = ($images.length - 1) * -520 + 'px',
                offset,
                start;
            
            $images.eq( current ).animate({ opacity : 1 }, time);
            
            $scroll.show().animate({ opacity : 1 }, time);
            
            $('#loader').hide();
            
            $project.hover(
                
                function () {
                                       
                   $project
                       .find('img:eq('+current+')')
                           .siblings()
                               .animate({ opacity : 0.5 }, time / 2); 
                    
                    $slideshow.animate({ left : '-=520' }, time, function () {

                        current++;

                        $project.find('img:eq('+current+')')
                            .animate({ opacity : 1 }, time /2)
                                .siblings()
                                    .animate({ opacity : 0.5 }, time / 2);

                    });
                    
                    start = setInterval(function () {
                                
                                offset = $slideshow.css('left');
                                
                                if ( offset === total ) {
                                    
                                    $project.find('img').animate({ opacity : 0.5 }, time / 2);
                                    
                                    $slideshow.animate({
                                        
                                        left : 0
                                        
                                    }, time * 2, function () {
                                        
                                        current = 0;
                                        
                                        $project.find('img:eq('+current+')').animate({ opacity : 1 }, time / 2).siblings().animate({ opacity : 0 }, 250);
                                        
                                        clearInterval(start);
                                        
                                    });
                                
                                } else {
                                    
                                    $project.find('img:eq('+current+')').siblings().stop(true, true).animate({ opacity : 0.5 }, time / 2); 
                                    
                                    $slideshow.stop(true, true).animate({

                                        left : '-=520'

                                    }, time, function () {

                                        current++;

                                        $project
                                            .find('img:eq('+current+')')
                                                .stop(true, true)
                                                .animate({ opacity : 1 }, time / 2);

                                    });
                                    
                                }
                                
                            }, time * 3);
                    
                },
                function () {
                    
                    clearInterval(start);
                    
                    $project.find('img').css('opacity','0.5');
                            
                    $slideshow.stop(true, true).animate({ left : 0 }, time , function () {
                        
                        current = 0;
                        
                        $project
                            .find('img:eq('+current+')')
                                .stop(true, true)
                                .animate({ opacity : 1 }, time / 2)
                            .siblings()
                                .stop(true, true)
                                .animate({ opacity : 0 }, time / 2);
                        
                    });
                    
                }
                
            );
            
            return current;
        
        });
        
    };
    
    ns.project = function () {
        
        var $projects = $('.project a');
        
        $projects.each(function () {
            
            var href = $(this).attr('href');
            
            $(this)
                .removeAttr('href')
                .click(function () { 
                    
                    ns.get_project(href);
                    
                });
            
        });
        
        $(window).scroll(function () { ns.follow(this); });
        
    };
    
    ns.follow = function (window) {
        
        var $window = $(window),
            $description = $('#project-description'),
            win_top = $window.scrollTop();
        
        $description.stop(true).animate({ top : win_top }, 500);
        
    };
    
    ns.contrast = {
        
        slider : function () {
            
            var $handle = $('#handle'),
                $slider = $('#slider');
            
            if ( !$handle.length ) { return; }
            
            var offset = parseInt($handle.offset().left, 10),
                sliderWidth = $slider.width();
            
            $handle
                .click(function (e) { e.preventDefault(); })
                .bind('mousedown', function () {

                    $slider.bind('mousemove', function (e) {

                        var sliderOffset = (e.pageX - offset),
                            position = (sliderOffset / sliderWidth) * 100,
                            percent = parseInt(position, 10);

                        if (position > 0 && position < 100) {

                            $handle.css('left', percent + '%');

                        }

                        ns.contrast.adjust(percent);     

                    });

                    return false;

                })
                .bind('mouseup', function () { $slider.unbind('mousemove'); });
        
        },
        adjust : function (percent) {
            
            var b2w = ( (percent / 100) * 255 ).toFixed(0),
                w2b = ( ( (100 - percent) / 100) * 255 ).toFixed(0),
                rgb = function (value) {

                    var string = '';

                    string += 'rgb('+value+','+value+','+value+')';

                    return string;

                };

            var white_bg = ['#header', '#header .content', '.project-description', '#secondary li'],
                white_txt = ['#pager a', '.count', 'a.about', 'a.categories', 'a.scroll-top', '#about p', '#about h4'],
                black_bg = [ '#about', 'a.about', 'a.categories', 'a.scroll-top', '#bar', '#block', '#block span', '#pager a', '#pager span' ],
                black_txt = [ '.project-description h3', '.project-description p', '#secondary a'];

            $(''+ white_bg +'').css({ background : rgb(w2b) });
            $(''+ white_txt +'').css({ color : rgb(w2b) });

            $(''+ black_bg +'').css({ background : rgb(b2w) });
            $(''+ black_txt +'').css({ color : rgb(b2w) });
            
        }
        
    };
    
    ns.scrolltop = function (window) {
        
        var $trigger = $('.scroll-top');
        
        $trigger.click(function () {
            
            $('html,body').animate({
                scrollTop : 0
            }, 500);
            
        });
        
    };
    
    ns.menu = function () {
          
        var $trigger = $('.categories'),
            $block = $('#block'),
            $sub_block = $block.find('span'),
            $sub_menu = $('#secondary'),
            $sub_menu_items = $sub_menu.find('a');
        
        var duration = 200,
            animate = {
                
                show : function () {
                    
                    $block.animate({ height : '82px' }, duration, function () {
                        
                        $sub_block.animate({ width : '162px' }, duration * 1.5, function () {
                            
                            $trigger.addClass('open');
                            
                            for ( var i = 0; i < 5; i++ ) {
                                
                                $sub_menu.animate({ height : '+=42px' }, duration / 2);
                                
                            }
                            
                        });
                        
                    });
                    
                },
                hide : function () {
                    
                    for ( var i = 0; i < 5; i++ ) {
                        
                        $sub_menu.animate({ height : '-=42px' }, duration / 2, function () {
                            
                            if ( $(this).height() === 0 ) {
                                
                                $sub_block.animate({ width : '-162px' }, duration * 1.5, function () {
                                    
                                    $block.animate({ height : '-82px' }, duration);
                                    
                                    $trigger.removeClass('open');
                                    
                                });
                                
                            }
                            
                        });
                        
                    }
                    
                }
                
            };
        
        $trigger.click(function () {
            
            if ( !$trigger.hasClass('open') ) {
            
                animate.show();
            
            } else {
                
                animate.hide();
            } 
           
        });
        
        $sub_menu_items.each(function () {
            
            var href = $(this).attr('href');
            
            $(this)
                .removeAttr('title')
                .removeAttr('href')
                .click(function () {
                    
                    ns.get_projects(href);
                    
                });
            
        });
        
    };
    
} (FS) );

// Implementation
(function (ns) {
    
    "use strict";
    
    $(document).ready(function () {
        
        ns.menu();
        
        $('.about').click(function () {
            
            ns.get_about();
            
        });
        
        ns.contrast.slider();
        
        ns.get_projects('http://www.familysohn.com/');
        
        //ns.scrolltop();
        
    });
    
} (FS) );
