
$( function() {
   Site.init();
});


var Site = {
    current_page : null,

    init: function() {
        var self = this;
        
        // Redirect to the proper ajax page if there
        // if this isn't the home page.
        var pathname = window.location.pathname;
        if (pathname && pathname != '/') {
            pathname = pathname.replace(/^\//, '');
            window.location = '/#' + pathname;
            return;
        }

        $.ajaxHistory.initialize();
        self.frontpage();
        var h = window.location.hash.split('/');
        if( h.length > 2 ) {
            var args = []
            while( h.length > 2 ) args[args.length] = h.pop();
            var f = h.join('_').replace('#','');
            args = args.join(',');
            eval('self.'+f+'("'+args+'")');
        }        
    },

    frontpage: function() {
        var self = this;
        $('div.page').empty();
        // Menu Events
        $('#projects-side-menu').click( function(){
            var open_it = ! $('#collections-menu').is(':visible');
            self._close_menus();
            if( open_it ) self.show_top_menu();
            return false;
        });
        $('#about-side-menu').click(function(){ 
            var open_it = ! $('#about-menu').is(':visible');
            self._close_menus();
            if( open_it ) self.show_middle_menu();
            return false;
        });
        $('#laurels-side-menu').click( function(){ 
            var open_it = ! $('#laurels-menu').is(':visible');
            self._close_menus();
            if( open_it ) self.show_bottom_menu();
            return false;
        });        
        $('#main-logo').ifixpng();
        $('#logo-bg').ifixpng();
    },

    _get_url_hash : function(href) {
        var path = href.replace( 'http://','').replace( window.location.host,'').replace(/^\//,'');
        return '#'+path;
    },

    _page_loading: function() {
        $('<img src="/img/page_loading.gif" alt="loading" />').addClass('page-loading').
            css('display','none').appendTo(document.body).fadeIn(2000);
    },

    _stop_page_loading: function() {
        $('.page-loading').remove();
    },

    show_top_menu: function() {
        var self = this;
        self._page_loading();
        $('#menus').load('/collections/?format=ajax', function() {
            $menu = $('#collections-menu');
            $('> div', $menu).vcenter();
            $('a', $menu).imageReplace({size: 12}).textover().each( function() {
                this.href = self._get_url_hash(this.href);
            }).click(function() {
                self.collections_index( this.href.split('/').pop() );
            }).find('img').ifixpng();
            self._stop_page_loading();
            $menu.hide().slideRight('slow');
        });        
    },
    
    show_middle_menu: function() {
        var self = this;
        self._page_loading();
        $('#menus').load('/pages/index/about?format=ajax', function() {
            $menu = $('#about-menu');
            $('a', $menu).imageReplace({size: 12}).textover().each( function(){
                this.href = self._get_url_hash(this.href);
            }).click(function() {
                self.pages_view( this.href.split('/').pop() );
            }).find('img').ifixpng();
            $('> ul', $menu).vcenter();
            self._stop_page_loading();
            $menu.hide().slideRight('slow');
        });        
    },

    show_bottom_menu: function() {
        var self = this;
        self._page_loading();
        $('#menus').load('/pages/index/laurels?format=ajax', function() {
            $menu = $('#laurels-menu');
            $('a', $menu).imageReplace({size: 12}).textover().each( function(){
                this.href = self._get_url_hash(this.href);
            }).click(function() {
                self.pages_view( this.href.split('/').pop() );
            }).find('img').ifixpng();
            $('> ul', $menu).vcenter();
            self._stop_page_loading();
            $menu.hide().slideRight('slow');
        });       
    },

    _close_menus: function() {
        $('.menu-strip:visible').hide().remove();
    },

    // Resize the scroller and center
    _carousel_resize: function(scroller) {
        var $p = $(scroller.container).parent();
        if( $p.length < 1 ) return;
        var pwidth = $p.parent().width();
        var lwidth = $('li', scroller.container).width();
        var count = $('li', scroller.container).length;
        var w = pwidth - (lwidth*2);
        var visible = Math.ceil(w / lwidth);
        if( visible >= count ) {
            visible = count;
            $('.jcarousel-next, .jcarousel-prev').hide();
        } else {
            $('.jcarousel-next, .jcarousel-prev').show().ifixpng();
        }
        newwidth = visible * lwidth;
        $p.width(newwidth); 
        $p.center();
        scroller.options.scroll = visible;
    },

    pages_view : function(page) {
        var self = this;
        if( $('#page-'+page).length > 0 ) return;
        $page = $('<div class="page" id="page-'+page+'"></div>').appendTo(document.body);
        self._page_loading();
        $.get('/pages/view/'+encodeURIComponent(page)+'?format=ajax', function(data) {
                data = $.trim( data.replace(/<!--.*-->/,''));
                $page.append(data);
                self.current_page = $page[0];
                // Get Page Type
                var page_type = $('.menu-strip:eq(0)',$page).attr('id').replace(/-menu$/,'').toLowerCase();
                switch( page_type ){
                    case 'about':
                        self.load_about_page($page, page);
                        break;
                    case 'laurels':
                        self.load_laurels_page($page, page);
                        break;
                }   
                self._stop_page_loading();
            });
    },

    // Take single color in hex format and generate color scheme
    _get_colors: function( htmlcolor ) {
        var rgb, bg_avg, forecolor, overcolor;
        htmlcolor = (htmlcolor == 'transparent' || htmlcolor == '' )? '94989A' : htmlcolor;  
        rgb = $.hex2rgb(htmlcolor);
        bg_avg = parseInt( (rgb[0]+rgb[1]+rgb[2]) / 3);
        if(bg_avg < 165 ){ forecolor = 'ffffff'; overcolor = '000000'}
        else { forecolor = '000000'; overcolor = 'ffffff'; }
        return {
            bg : htmlcolor,
            fore : forecolor,
            over : overcolor
        };
    },

    load_about_page: function(container, page) {
        var self = this;
    
        // Get color settings
        var colors = self._get_colors($.colorFormat( $('.bgcolor', container).css('background-color') ));
        
        // Set container style
        $(container).show().css({
            top: '-10000px',
            left: '-10000px',
            width: '100%',
            height: '100%',
            background: '#'+colors['bg'],
            color: '#'+colors['fore']
        });
        
        // Set up side bar images
        $side_menu = $('<div class="pages-side-menu"></div>').appendTo(container);
        $('<a href="#" class="top-menu"><img src="/img/back_to_main_menu.png" alt="back to main menu" /></a>').
            appendTo($side_menu).click(function() {
                $('.page').remove();
                self._close_menus();
            }).rollover().find('img').ifixpng();
        $('<a class="middle-menu"><img src="/img/about.png" alt="images" /></a>').
            appendTo($side_menu).find('img').ifixpng();

        $('<a class="bottom-menu"><img src="/img/laurels.png" alt="text" /></a>').
            appendTo($side_menu).
            css({cursor: 'pointer'}).
            toggle( 
                function() {
                    // open laurels menu
                    $.get('/pages/index/laurels/?format=ajax', function(data) {
                        // clean up data
                        data = $.trim( data.replace(/<!--.*-->/,'').replace('id="laurels-menu"','') );
                        var $menu = $(data).appendTo(container).hide().addClass('laurels-menu');
                        $('> ul li a', $menu).each(function(){
                            this.href = self._get_url_hash(this.href);
                        }).
                        click( function() {
                            self.pages_view( this.href.split('/').pop() );
                        });
                        $menu.show().slideRight('slow');
                        $('> ul', $menu).vcenter();
                    });
                }, 
                function() {
                    // close laurels menu
                    $('.laurels-menu', container).hide().remove();
                }
            ).find('img').ifixpng();

        // Set up page menu links
        $('ul li a', container).imageReplace({size: 12, color: colors['fore']}).textover({color: colors['over']}).
            each(function() {
                this.href = self._get_url_hash(this.href);                        
            }).
            click( function() {
                self.pages_view( this.href.split('/').pop() );
            }).
            find('img').ifixpng();                
        $("ul li a >img[@alt="+page+"]", container).parent().mouseover().addClass('ignore');
        $('ul', container).vcenter();
        $('.menu-strip', container).width(340); // avoid overlap
        
        // Center page body
        $('.page-text',container).width( $('.page-text',container).width() );
        $('.page-body',container).Scroller({postInit: function() {$('.scroller-prev, .scroller-next').ifixpng();} }).vcenter();
        
        // Show the page
        $(container).css({top:'0px',left:'0px'}).slideLeft('slow',function(){ 
            self._cleanup();
            $('.page-text',container).css({'width' : ''});
        });
    },

    load_laurels_page: function(container, page) {
        var self = this;
        
        // Get color settings
        var colors = self._get_colors($.colorFormat( $('.bgcolor', container).css('background-color') ));

        $(container).show().css({
            top: '-10000px',
            left: '-10000px',
            width: '100%',
            height: '100%',
            background: '#'+colors['bg'],
            color: '#'+colors['fore']
        });
        $('.page-text', container).css( {
            'margin-left' : '80px',
            'height' : '69%'
        });

        // Set up side bar images
        $side_menu = $('<div class="pages-side-menu"></div>').appendTo(container);
        $('<a href="#" class="top-menu"><img src="/img/back_to_main_menu.png" alt="back to main menu" /></a>').
            appendTo($side_menu).click(function() {
                $('.page').remove();
                self._close_menus();
            }).rollover().find('img').ifixpng();
        $('<a class="middle-menu"><img src="/img/about.png" alt="images" /></a>').
            appendTo($side_menu).
            css({cursor: 'pointer'}).
            toggle( 
                function() {
                    // open about menu
                    $.get('/pages/index/about/?format=ajax', function(data) {
                        // clean up data
                        data = $.trim( data.replace(/<!--.*-->/,'').replace('id="about-menu"','') );
                        var $menu = $(data).appendTo(container).hide().addClass('about-menu');
                        $('> ul li a', $menu).each(function(){
                            this.href = self._get_url_hash(this.href);
                        }).
                        click( function() {
                            self.pages_view( this.href.split('/').pop() );
                        });
                        $menu.show().slideRight('slow');
                        $('> ul', $menu).vcenter();
                    });
                }, 
                function() {
                    // close about menu
                    $('.about-menu', container).hide().remove();
                }
            ).find('img').ifixpng();

        $('<a class="bottom-menu"><img src="/img/laurels.png" alt="text" /></a>').
            appendTo($side_menu).find('img').ifixpng();


        // Set up page menu links
        $('.menu-strip', container).css('background', '');
        $('ul li a', container).imageReplace({size: 12}).textover().
            each(function() {
                this.href = self._get_url_hash(this.href);                        
            }).
            click( function() {
                self.pages_view( this.href.split('/').pop() );
            }).
            find('img').ifixpng();
        $("ul li a >img[@alt="+page+"]", container).parent().mouseover().addClass('ignore');
        $('ul', container).vcenter();
        
        // Center page body
        $('.page-text',container).width( $('.page-text',container).width() );
        $('.page-body',container).Scroller({postInit: function() {$('.scroller-prev, .scroller-next').ifixpng();} }).vcenter();
        
        // Show the page
        $(container).css({top:'0px',left:'0px'}).slideRight('slow',function(){ 
            self._cleanup();
            $('.page-text',container).css({'width':''});            
        });
    },

    _cleanup : function() {
        var self = this;
        $('.page').each( function() {
            if( this != self.current_page ) {
                $(this).hide().remove();
            }
        });
    },

    collections_index: function(category) {
        var self = this;
        if( $('#collection-'+category).length > 0 ) return;
        self._page_loading();
        $page = $('<div class="page" id="collection-'+category+'"></div>').appendTo(document.body).
            load('/collections/index/'+encodeURIComponent(category)+'?format=ajax', 
            function() {
                var container = self.current_page = this;
                
                // Get colors
                var top_colors = self._get_colors($.colorFormat( $('.collections-menu', container).css('background-color') ));
                var middle_colors = self._get_colors($.colorFormat( $('.collection-images', container).css('background-color') ));
                var bottom_colors = self._get_colors($.colorFormat( $('.collection-text', container).css('background-color') ));

                // Set page styles
                $(container).show().each(function() {
                    $('.collections', this).vcenter();
                }).css({
                    top: '-10000px',
                    left: '-10000px',
                    width: '100%', height: '100%',
                    display: 'block', 
                    position: 'absolute'
                });

                // Set up side bar images
                $side_menu = $('<div class="pages-side-menu"></div>').appendTo(container);
                $('<a href="#" class="top-menu"><img src="/img/back_to_main_menu.png" alt="back to main menu" /></a>').
                    appendTo($side_menu).click(function() {
                        $('.page').remove();
                        self._close_menus();
                    }).rollover().find('img').ifixpng();
                $('<a class="middle-menu"><img src="/img/images.png" alt="images" /></a>').
                    appendTo($side_menu).find('img').ifixpng();

                $('<a class="bottom-menu"><img src="/img/text.png" alt="text" /></a>').
                    appendTo($side_menu).find('img').ifixpng();
                
                // Center collections menus and add rollovers
                $('.collection-types', container).vcenter();
                $('.collection-types a', container).imageReplace({size: 12}).textover().each(function() {
                    this.href = self._get_url_hash(this.href);
                    if( this.href.split('/').pop() == category )  $(this).mouseover().addClass('ignore');
                }).click(function() {
                    self.collections_index( this.href.split('/').pop() );
                }).find('img').ifixpng();
                

                // Collections Menu
                $('.collections a', container).imageReplace({wrap:'40',align:'left', size: 11}).textover().click( function() {
                    self.collections_view( this.href.split('/').pop() );
                    return false;
                }).find('img').ifixpng(); 
                
                $('.collections', container).show().vcenter();
                               
                // Make scroller for description
                $('.description', container).width( parseInt($(window).width() * 0.6) ).center();
                $('.short-description', container).width( parseInt($(window).width() * 0.962));
                $('.collection-text', container).css({
                    color: '#'+bottom_colors['fore']
                });

                // Make thickbox for images
                tb_init('.collection-images .container li a');

                // Make thumbnail carousel
                $('.collection-images .container ul', container).jcarousel({
                    wrap:'both', scroll: 4,
                    reloadCallback: self._carousel_resize,
                    initCallback : self._carousel_resize
                }).parent().parent().parent().vcenter();
               
                
                $(container).css({top:'0px',left:'0px'}).slideRight(1000,function(){
                    $('.description', container).css({width: ''}).
                        Scroller({postInit: function() {$('.scroller-prev, .scroller-next').ifixpng()} });
                    $('.short-description', container).css({width: ''});
                    $('.collections', container).vcenter();
                    self._stop_page_loading();
                    self._cleanup();
                });
            });
    },

    collections_view: function(collection)  {
        var self = this;
        $.getJSON('/collections/view/'+collection + '?format=json', function(data) {

            // Reset the image scroller
            var $scroller = $('.collection-images .container');
            var $list = $('ul', $scroller);
            if( $list.length && $list[0].jcarousel ) {
                $(window).unbind('resize', $list[0].jcarousel.funcResize);
                $list[0].jcarousel = null;
            }
            $scroller.empty();
            if( data['Image'].length > 0 ) {
                $scroller.append('<ul>');
                $list = $('ul', $scroller);
                $.each(data['Image'], function(i, img) {
                    $list.append('<li><a href="/img/gallery/'+img['filename']+'" title="'+escape(img['caption'] || '')+'" target="_blank" rel="collection"><img src="/img/thumbnail.php?img=gallery/'+img['filename']+'&w=200&h=280&crop=1" alt="image" /></a></li>');
                });                
                $list.jcarousel({
                    wrap: 'both', scroll : 4,
                    reloadCallback: self._carousel_resize,
                    initCallback: self._carousel_resize
                }).hide().fadeIn('slow');                
            }
            // Thickbox init
            tb_init('.collection-images .container li a');

            // Change project description
            $('.short-description').empty().append(data['Collection']['short_description']).hide().fadeIn('slow');
            $('.description').empty().append(data['Collection']['description']).
                Scroller({postInit: function() {$('.scroller-prev, .scroller-next').ifixpng()} }).
                hide().fadeIn('slow');
        });
    }
};



// Utilities /////////////////////////////////////////////////////////

jQuery.fn.slideRight = function(speed,f) {
    var $ = jQuery;
    return this.each( function(i,el) {
        var w = $(el).css('width');
        $(el).width(0);
        $(el).animate({
            width: $(window).width()
          }, 
          speed,
          function() {
              $(this).css('width',w);
              if( f ) f();
          }
        );
        
    });
};

jQuery.fn.slideLeft = function(speed,f) {
    var $ = jQuery;
    return this.each( function(i,el) {
        var saved_width = $(el).css('width');
        var saved_body_overflow = $(document.body).css('overflow');
        $(document.body).css('overflow','hidden');
        $(el).css({
            left: $(window).width() + 'px',
            width: $(window).width() + 'px'
        }).
        animate({
            left: 0
          }, 
          speed,
          function() {
              $(this).css({'width' : saved_width});
              $(document.body).css('overflow', saved_body_overflow);
              if( f ) f();
          }
        );
        
    });
};


