"use strict";
// URL

var URL = {
    Config: {
        interval: 100
    },
    State: {
        currLocation: window.location.href,
        currHash: window.location.hash,
        prevLocation: "",
        prevHash: "",
        listen: true
    },
    Keys : '',
    Init : function () {
        URL.Functions.CheckLocation();
        URL.Functions.UpdateKeys(window.location.hash);
        
        
        $(window.location).bind('change', function (e, o) {
            URL.Functions.UpdateKeys(o.currentHash); 
            Filter.Update(URL.Keys);        
        });
        
    },
    Update : function (n, v) {
        if (v === undefined) {
            var f = n.match(/([\w]+)-([\w-]+)/);
            n = f[1];
            v = f[2];          
        }
        
        var pair = n + '-' + v;            
        if (URL.State.currHash.indexOf('/' + n + '-') > -1) { // we're updating        
            var re = new RegExp(n + '-([\\w-]+)', 'g');
            window.location.hash = URL.State.currHash.replace(re,pair);            
        } else { // we're creating
            var pre = window.location.hash.indexOf('/') > 0 ? '' : '/';
            window.location.hash = pre + URL.State.currHash + pair + '/';   
        }
    },
    Clear : function (n) {           
        if (URL.State.currHash.indexOf('/' + n + '-') > -1) { // we're clearing   
            URL.State.listen = false;  
            var re = new RegExp(n + '-([\\w-]+)/', 'g');
            window.location.hash = URL.State.currHash.replace(re,''); 
            URL.State.listen = true;           
        }
        
    },
    Functions : {        
        UpdateKeys : function (raw) {    
            raw = raw.match(/([\w-]+)/g);
            if (raw != undefined && raw.length > 0) {
                URL.Functions.GenerateKeys(raw); 
            }      
        },
        GenerateKeys : function (arr) {
            if (arr === null) { 
                return false; 
            }
            var nv = [];
            for (var i = 0; i < arr.length; i ++) {
                var key = arr[i].match(/([\w]+)-([\w-]+)/);
                
                if (typeof(key[2]) != 'undefined') {
                    nv[key[1]] = key[2];
                    URL.Keys.length += 1;
                }
            }    
            URL.Keys = nv;
        },
        CheckLocation: function () {
            setInterval(function() {
                if (URL.State.currLocation !== window.location.href && URL.State.listen) {

                    URL.State.prevLocation = URL.State.currLocation;
                    URL.State.prevHash = URL.State.currHash;
                    URL.State.currLocation = window.location.href;
                    URL.State.currHash = window.location.hash;
                    $(window.location).trigger("change", {
                        currentHref: URL.State.currLocation,
                        currentHash: URL.State.currHash,
                        previousHref: URL.State.prevLocation,
                        previousHash: URL.State.prevHash
                    });
                }
            }, URL.Config.interval);
        }
    }
}
var Filter = {
    filters : [
        'section',
        'thumb'
    ],
    Init: function () {
        // Init Nav
        if ($('ul#section-filter').exists()) {
            $('#main-content').removeClass('sections-loading');
            var start = URL.Keys['section'] != undefined ? '.section-' + URL.Keys['section'] : undefined;
            $('ul#section-filter li a:not([class^=thumb])').click(function(e) {
                var c = $(this).attr('class'); 
                URL.Clear('thumb');
                URL.Update(c);           
                return false; 
            });            
            var start = URL.Keys['section'] != undefined ? 'section-' + URL.Keys['section'] : $('ul#section-filter li:first a').attr('class');
            URL.Update(start);
            Filter.Update();
        }
    },
    Update: function (keys) {  
        keys  = keys != undefined ? keys : URL.Keys;
        if (keys['section'] == 'work') {
            $('ul#thumb-filter').show();
        } else {
            $('ul#thumb-filter').hide();            
        }
        
        $('li a').parent().removeClass('selected');
        $('li a.section-'+keys['section']).parent().addClass('selected');
        
        for (var i = 0; i < Filter.filters.length; i ++) {
            if (keys[Filter.filters[i]] != undefined) {
                Filter.Functions.Filter('.' + Filter.filters[i] + '-item' , '.' + Filter.filters[i] + '-' + keys[Filter.filters[i]]);
            }
        }
    },
    Functions : {
        Filter: function (k,f) {
            if ($('#main-content ' + f).exists()) {
                $('#main-content ' + k).hide();   
                setTimeout(function(){ // This needs to be outside as the hide() is fired for each item it applies to.
                    $('#main-content ' + f).show();  
                    setTimeout(function(){
                        $(window.location).trigger("flowers.filter");
                        
                    },500);   
                },500);   
            }
        }
    }
}
var ImageBrowser = {
    Config : {
        navigation: 'ul.item-nav li a',
        navWidth : 585,
        onInit: function () { }
    },
    State : {
        hasScrollBar : false,
        currSrc : ''
    },
    Init: function () {
        var $this = $('div.image-browser');
        var $nav = $(ImageBrowser.Config.navigation, $this);
        
        var totalImg = $nav.length;        
        
        //setTimeout(function(){
            ImageBrowser.Functions.ResetScrollBar();            
        // },500)

        if (!$('#side-content .inner p.image-caption').exists()) {            
            $('#side-content .inner').append('<p class="image-caption">' + $($nav[0]).next('span').html() + '</p>');
        }
        $('div.shield').fadeOut(500,function() {
            $(this).remove();
        });
        
        $nav.click(ImageBrowser.Events.ThumbClick);
        
    },
    Prepare : function (shouldInit) {
        
        var $this = $('div.image-browser');
        var $viewer = $('div.viewer');
        var $nav = $(ImageBrowser.Config.navigation, $this);
        
        var $shield = $('<div />').addClass('shield');
        
        $shield.appendTo($this);
        //$viewer.prependTo($this);
        
        
        var loaded = false;
         
        //var src = $nav.parent('li:first').children('a').attr('href');
        //ImageBrowser.Functions.LoadImage(src, $viewer);
        //ImageBrowser.State.currSrc = src;
        
        $('ul.item-nav li:last img').load(function () { // Wait for the last image to load before firing scrollbar
                   
            if (!loaded) {                 
                 
                loaded = true;   
                setTimeout(function () {                                                      
                
                    if (shouldInit) {             
                        ImageBrowser.Init();
                    }
                }, 2000);
                
            }
            
        });
        
        setTimeout(function () { // this is the fallback, if the image doesn't load
               
            if (!loaded) {
                                 
                loaded = true;                   
                if (shouldInit) {             
                    ImageBrowser.Init();
                }
               
            }
                        
        }, 5000); // perhaps need to be adjusted based on image count?
    },
    Events : {
        ThumbClick : function (e) {            
                                    
            var src = $(this).attr('href');
            
            var width = $('div.item-wrap').width();    
            var maxOffset = parseInt(width - ImageBrowser.Config.navWidth);
            var minOffset = 0;
            var leftOffset = $('div.item-wrap')[0].offsetLeft;        
            var adjust = centerOffset < 0 ? -1 : 1; 
            
            var ol = this.offsetLeft != 0 ? this.offsetLeft : this.offsetLeft + this.parentNode.offsetLeft; // IE 6/7 needs this.parentNode.offsetLeft
            var imgMiddlePoint = ol + $(this).width() / 2;
            var centerOffset = leftOffset * adjust + (ImageBrowser.Config.navWidth / 2) - 20 ;
                        
            var pos = imgMiddlePoint - (ImageBrowser.Config.navWidth / 2) ;
                   
            //alert(this.offsetLeft + this.parentNode.offsetLeft)
                
            pos = pos > maxOffset ? maxOffset : (pos < minOffset ? minOffset : pos);
            
            $('div.item-wrap').animate({left : -pos}, 500);
            $('.jScrollPaneTrack .jScrollPaneDrag').trigger('update', Math.round((pos / width) * $('.jScrollPaneTrack').width()));
                      
            if (ImageBrowser.State.currSrc != src) {
                ImageBrowser.State.currSrc = src;
                ImageBrowser.Functions.LoadImage(src);
                ImageBrowser.Functions.SwapCaption($(this).next('span').html());
            }
            
            return false;
            
        }
    },
    Functions : {
        LoadImage : function (src) {   
            var $viewer = $('div.image-browser div.viewer');
            $viewer.empty().removeClass('error').addClass('loading');
            var img = $('<img />').load(function() {
                var $i = $(this);
                $i.hide();                
                setTimeout(function() {
                    $viewer.html($i).removeClass('loading');                    
                    $i.fadeIn();
                }, 500);
            }).error(function() {
                $viewer.removeClass('loading').addClass('error');
            }).attr('src', src);
        },
        ResetScrollBar : function () {
            ImageBrowser.State.hasScrollBar = true;
            $('.jScrollPaneDrag').hide();
            ImageBrowser.Functions.ResetWidths();              
        },        
        SwapCaption : function (cap) {
            $('p.image-caption').html(cap);            
        },
        ResetWidths : function () {  
            var $nav = $(ImageBrowser.Config.navigation)
            var width = 100000;      
            $nav.parent().parent('ul').width(width);
            width = 0; 
            $nav.each(function(i){
                
                var m = 15;
                if (i === 0) {
                    m = 0;
                    width = 0;                   
                }  
                
                if ($(this).parent().is(':visible')) {
                    var w = $(this).children('img').width() + m;
                    if (w !== NaN) {
                        parseInt(width += w);
                    }
                }
                
                if (i == $nav.length - 1) {
                    $('div.image-browser ul.item-nav').width(width);                  
                    $('div.image-browser div.item-wrap').jScrollHorizontalPane();  
                    $('.jScrollPaneDrag').show();   
                    $('div.jScrollPaneDrag').css('left','0px');           
                }
                  
            });
        }
    }
}

var ArtistDetail = {
    State : {
        hasImageBrowser : false
    },
    Init : function () {
        
        ImageBrowser.Prepare(true);
        ArtistDetail.State.hasImageBrowser = true;
        
        
        $(window.location).bind('flowers.filter', ArtistDetail.Events.FlowersFilter);
        $(window.location).bind('flowers.thumbfilter', ImageBrowser.Functions.ResetScrollBar);
        
        $('ul#thumb-filter li a').click(ArtistDetail.Events.FilterThumbs);            
                
       
    },
    Events : {
        FlowersFilter : function (e) {
                        
            if (URL.Keys['section'] == 'work' || URL.Keys['section'] == 'images') {
                $('p.image-caption').show();      
                ImageBrowser.Functions.ResetScrollBar();
            } else {
                $('p.image-caption').hide();
            }    
            if (URL.Keys['thumb'] == 'all') {
                
            }    
        },
        FilterThumbs : function (e) {
            if (!ArtistDetail.State.hasImageBrowser) {
                ImageBrowser.Init();
                ArtistDetail.State.hasImageBrowser = true;
            }
            e.preventDefault();
            if (URL.Keys['section'] != 'work') {
                URL.Update('section-work');
            }
            var f = '.' + $(this).attr('class');
            var k = '.thumb-item';
            var $n = $('ul.item-nav');
            if ($(f, $n).exists()) {
                $(k, $n).hide();   
                $('.first', $n).removeClass('first');
                $('ul.item-nav').css('width', 10000);
                setTimeout(function(){ // This needs to be outside as the hide() is fired for each item it applies to.
                                        
                    $(f + ':first', $n).addClass('first');
                    $(f, $n).show(); 
                    $(f + ':first a', $n).click();
                        
                    $(window.location).trigger("flowers.thumbfilter"); // This needs to be outside as the show() callback is fired for each item it applies to.    
                },500);   
            }             
        }
    }
}
var ExhibitionDetail = {
    Init : function () {
                
        ImageBrowser.Prepare(true);
        
    }
}
var ProjectDetail = {
    Init : function () {
        
        ImageBrowser.Prepare(true);
        
        $(window.location).bind('flowers.filter', function() {         
        
             if (URL.Keys['section'] == 'images') {
                $('p.image-caption').show();      
                ImageBrowser.Functions.ResetScrollBar();
            } else {
                $('p.image-caption').hide();
            }    
            
        });
        
    }
}
var TextList = {
    Init : function () {
       
       var $img = $('<img />').attr('id','item-image').hide();
       if ($('body.text-list div#main-content h2.top').length) {
           $img.addClass('down');
       }
       
       if ($('body.text-list div#side-content p.footer-link').exists()) {
           $('body.text-list div#side-content p.footer-link').before($img);         
       } else {          
           $('body.text-list div#side-content div.inner').append($img);   
       }
    
       
       $('body.text-list div.item a').mouseover(TextList.Events.MouseOver).mouseout(TextList.Events.MouseOut);
       
       if ($('ul#year-filter').exists()) { 
            $.fn.equalcolitem();
           $('ul#year-filter').dropdown();           
       }
       
    },
    Events : {
        MouseOver : function () {
            var $anchor = $(this);
            var height = $anchor.parent().prev().attr('height');
            var width = $anchor.parent().prev().attr('width');
            height = height > 0 ? height : $anchor.parent().prev().height();
            width = width > 0 ? width : $anchor.parent().prev().width();            
            $('body.text-list div#side-content div.inner img#item-image').load(function() {
                $(this).show();
            }).attr('src', $anchor.parent().prev().attr('src')).attr('height', height).attr('width', width);
        },
        MouseOut : function () {
            $('body.text-list div#side-content div.inner img#item-image').hide();
        }
    }
}

// Navigation
var Nav = {
    State: {
        pageHasChildren: false,
        pageDefaultSubNav: {}
    },
    Init: function () {
        // save the current sub nav
        if ($('div#header ul#main-nav li.selected ul.second').exists()) {
            Nav.State.pageHasChildren = true;
            Nav.State.pageDefaultSubNav = $('div#header ul#main-nav li.selected ul.second').outerHTML();
            var $s = Nav.Functions.PrepareForPromotion(Nav.State.pageDefaultSubNav);
            $s.appendTo('div#header div.inner');
            Cufon.refresh();
        }

        $('div#header ul#main-nav li a').mouseover(Nav.Events.MouseOver);
        $('div#header').mouseleave(Nav.Events.MouseOut);
    },
    Events: {
        MouseOver: function () {
            var $t = $(this);
            $('div#header div.inner ul.top.out').remove();
            if ($t.siblings('ul.second').exists()) {
                var $s = Nav.Functions.PrepareForPromotion($t.siblings('ul.second').outerHTML());
                $s.appendTo('div#header div.inner');
            }
            Cufon.refresh();
        },
        MouseOut: function (e) {
            var $t = $(this);
            $('div#header div.inner ul.top.out').remove();
            if (Nav.State.pageHasChildren) {
                var $s = Nav.Functions.PrepareForPromotion(Nav.State.pageDefaultSubNav);
                $s.appendTo('div#header div.inner');
            }
            Cufon.refresh();
        }
    },
    Functions: {
        PrepareForPromotion: function ($ul) {
            return $($ul).removeClass('second').addClass('out top');
        }
    }
}

// Home
var Home = {
    State : {
        homeImageVisible : true
    },
    Init : function () {
        
        var $homeimg = $('div#home-image');
        
        if ((document.referrer == null || (document.referrer.indexOf(window.location.hostname) < 0 && document.referrer.indexOf('tumblr.com') < 0)) && Flowers.SiteContent.images.length > 0) {
            App.Functions.LoadImage(Flowers.SiteContent.images[Math.randomMax(Flowers.SiteContent.images.length - 1)], $homeimg);
            $('#wrapper-side .base').hide();
            
            
            $('div#home-image').mouseover(Home.Events.HomeImageMouseOver).mouseout(Home.Events.HomeImageMouseOut).click(Home.Events.HomeImageClick);
            
            setTimeout(function(){
                Home.Functions.RemoveHomeImage();
            },10000);    
            
        } else {
            $homeimg.remove();
        }
        
    },
    Events : {
        HomeImageMouseOver : function () {
            var $t = $(this);
            if (! $t.children('a').exists()) {
                var $a = $('<a />').text('Skip');
                $a.appendTo($t);                   
            } else {
                $t.children('a').show();
            }
        },
        HomeImageMouseOut : function () {
            var $t = $(this);
            $t.children('a').hide();            
        },
        HomeImageClick : function () {
            Home.Functions.RemoveHomeImage();            
        }
    },
    Functions : {
        RemoveHomeImage : function () {
            if (Home.State.homeImageVisible) {
                $('div#home-image').fadeOut(500, function () {
                    $(this).remove();
                    Home.State.homeImageVisible = false;                       
                });    
                $('#wrapper-side .base').fadeIn();
            }     
        }
    }
}
var App = {
    pageType: "",
    Init: function(pageType) {

        App.pageType = pageType;

        $('body').addClass('hasJS');
        

        Nav.Init();

        URL.Init();

        Filter.Init();
        

        $('ul.dropdown').dropdown();  

        if ($('ul.slideshow:not(.dead)').exists()) {
            $('ul.slideshow:not(.dead)').innerfade({
                speed: 1000,
                timeout: 5000,
                type: 'sequence',
                containerheight: 480
            });
        }

        if (pageType.indexOf("home") > -1) {
            Home.Init();
        } else if (pageType.indexOf("artist-detail") > -1) {
            ArtistDetail.Init();
        } else if (pageType.indexOf("exhibition-detail") > -1) {
            ExhibitionDetail.Init();
        } else if (pageType.indexOf("project-detail") > -1) {            
            ProjectDetail.Init()
        } else if (pageType.indexOf("text-list") > -1) {
            TextList.Init();
        }

    },
    Functions: {
        LoadImage: function(src, $c) {

            $c.empty().removeClass('error').addClass('loading');
            var img = $('<img />').load(function() {
                $(this).hide();
                $c.html($(this)).removeClass('loading');
                $('img', $c).fadeIn();
            }).error(function() {
                $c.removeClass('loading').addClass('error');
            }).attr('src', src);
        }
    }
};
// Start of JSChain
$(function() {
    Cufon.replace('#header ul:has(ul) > li a, ul.out.top li a, h1, h2, div.base h4, body.publications #main-content h3',{
        hover: true
    });
    if ($('body').hasClass('editmode')) {

        $('body').addClass('hasJS');

        Nav.Init();
        Home.Init();

    } else {
        var mode = $('body').attr('class');
        App.Init(mode);
    }
});

// Helpers
$.fn.outerHTML = function () {
    return $('<div>').append(this.eq(0).clone()).html();
};
$.fn.exists = function () {
    return $(this).length > 0;   
};
Math.randomMax = function(maxVal,asFloat){
    var val = Math.random()*maxVal;
    return asFloat?val:Math.round(val);
}
var lg = function() {
    //console.log(arguments)
}

$.fn.equalcolitem = function () { 
    var $cols = $('div#main-content div.column');
    var $col0 = $($cols[0]);
    var $col1 = $($cols[1]);
    var $col2 = $($cols[2]);
           
    var col0heights = [], col1heights = [], col2heights = []
    
    var $col0items = $('div.item',$col0).each(function(i){
        col0heights.push($(this).height());
    });
    var $col1items = $('div.item',$col1).each(function(i){
        col1heights.push($(this).height());
    });
    var $col2items = $('div.item',$col2).each(function(i){
        col2heights.push($(this).height());
    });
    
    var colheights = [col0heights, col1heights, col2heights];
    
    var keycol = [];
    var len = 0
    for (var i = 0; i < colheights.length; i++) {
        if (colheights[i].length > len) {
            len = colheights[i].length;
            keycol = i;
        }
    } 
    
    var heights = [];
    
    for (var i = 0; i < colheights[keycol].length; i++) {
        
        var col0 = colheights[0][i] === undefined ? 0 : colheights[0][i];
        var col1 = colheights[1][i] === undefined ? 0 : colheights[1][i];
        var col2 = colheights[2][i] === undefined ? 0 : colheights[2][i];
        
        var itemheights = [col0, col1, col2];
        var highest = 0;
        for(var p = 0; p < itemheights.length; p++) {
            if (itemheights[p] > highest) {
                highest = itemheights[p];
            }
        }  
        heights.push(highest);
    }
    
    $col0items.each(function(i) {
        $(this).height(heights[i] + 12);
    });
    $col1items.each(function(i) {
        $(this).height(heights[i] + 12);
    });
    $col2items.each(function(i) {
        $(this).height(heights[i] + 12);
    });
    
}
$.fn.dropdown = function () {   
    return this.each(function() {
        var starttop = $(this).offset().top - $('#side-content').offset().top;
        
        var $this = $(this).hide();        
        var hidetimer;          
        
        var $current = $('li.current',$this);
        $this.before('<a href="#" class="dd-head">' + $current.text() +'</a>');
        var $tog = $this.prev('a.dd-head');
        
        $this.css({
            position : 'absolute',
            top : starttop + $tog.height() + 6,
            left : 30,
            width : 175
        });
        
        
        var out = false; 
        
        $('img#item-image.down').addClass('hasdd');
        
        $tog.mouseover(function() {
            clearTimeout(hidetimer);
            $tog.addClass('dead');
        }).mouseout(function() {
            $tog.removeClass('dead');
            hidetimer = setTimeout(function () {
                if (out) {
                    $current.addClass('current');
                    $this.hide();
                    out = false;
                } 
            }, 2000)
        });
        
        $('li a',$this).mouseover(function() {
            clearTimeout(hidetimer);
            $current.removeClass('current');
            $tog.addClass('dead')
        }).mouseout(function() {
            $tog.removeClass('dead');
            hidetimer = setTimeout(function () {
                if (out) {
                    $current.addClass('current');
                    $this.hide();
                    out = false;
                } 
            }, 2000)
        });
        
        $('*:not(.dd-head)').click(function() {                
            if (out) {
                $current.addClass('current');
                $this.hide();
                out = false;
            } 
        });
        
        $tog.click(function(){
            if (out) {
                $this.hide();
                out = false;
            } else {
                $this.show();
                out = true;
            }
            return false;
        });
    });
}
