if (!window['sb']) {
    window['sb'] = {};
    var sb = window['sb'];
}

sb.browserSucks = (jQuery.browser.msie && jQuery.browser.version < 8) ? true : false;
sb.browserSucksEggs = (jQuery.browser.msie && jQuery.browser.version < 7) ? true : false;


(function() { // This is where jQuery code can safely go without foobarring prototype
    var $ = jQuery;
    
    
    $(document).ready(function() { // These functions get called on DOM ready
        $('a').click(function() { $(this).blur(); }); // prevents outlines on links for IE
        sb.homepageActions();
		    sb.hero();
        sb.lightbox();
        sb.navigationSubnav();
        sb.playlistZebra();
    })
    
    $(window).load(function() { // These functions get called when everything has loaded
    })
    
    sb.homepageActions = function() {
        if(!$('body.homepage').size()) {
            return;
        }
        function heroSlideIn() {
            $('#undernavmain').slideDown('slow', 'easeOutBounce');
            createCookie('riverwood_hero_cookie', cookie_life);
        }


        var cookie_life = 3600;

        function createCookie(name,minutes) {
            var expires = "";
            var value = new Date();
            if (minutes) {
                var date = value;
                date.setTime(date.getTime()+(minutes*1000*24)); // expires in 24 hours
                // date.setTime(date.getTime()+(minutes*1000)); // expires in 1 hour
                expires = "; expires="+date.toGMTString();
            } else {
                expires = "";
            }
            document.cookie = name+"="+value+expires+"; path=/";
        }

        function readCookie(name) {
            var i=0;
            var nameEQ = name + "=";
            var ca = document.cookie.split(';');
            for(i=0;i < ca.length;i++) {
                var c = ca[i];
                while (c.charAt(0)===' ') { c = c.substring(1,c.length); }
                if (c.indexOf(nameEQ) === 0) { return c.substring(nameEQ.length,c.length); }
            }
            return null;
        }

        var sbHeroCookie = readCookie('riverwood_hero_cookie');

        if (!sbHeroCookie) {
            // if no cookie do this
            setTimeout(heroSlideIn, 1000);
        } else {
            // if there is a cookie do this
            $('#undernavmain').show();
        }



        // $('#blog_content_sb').load('/meta/blog/teaser.inc');
    }
    
    sb.playlistZebra = function() {
        if(!$('table#playlist').size()) {
            return;
        }
        $('table#playlist tr:even').each(function() {
            $(this).addClass('alt');
        });
        
    }
    
    sb.navigationSubnav = function() {
        var allLinks = $('ul#navbar li');
        allLinks.each(function() {
            var thisItem = $(this)
            thisItem.hover(function() {
                thisItem.find('ul').css('left','auto');
                thisItem.addClass('sfhover');
            },
            function() {
                thisItem.find('ul').css('left','-999em');
                thisItem.removeClass('sfhover');
            })
        })
    }

	

    sb.hero = function() { // Heroshot crossfader; set options below this function

        if(!$('.heroshots').size()) {
            return;
        }
        $('.heroshots').each(function(index) {
            var heroshot = $(this);
            var fade = heroshot.find('input[name=fadevalue]');
            fade = fade.val() * 1000;
            heroshot.find('input[name=fadevalue]').remove();

            var dur = heroshot.find('input[name=showvalue]');
            dur = dur.val() * 1000;
            heroshot.find('input[name=showvalue]').remove();
            
            heroshot.attr({
                'fade': fade,
                'dur': dur
            })
            
            
            if(heroshot.children('div.slide').size() < 2) { // Less than two images, we don't need to xfade or add controls
                return
            }

            
            heroshot.children('div.slide:first-child').attr({current: 'current'});
            heroshot.children('div.slide:not(:first-child)').hide();
            
            setInterval(function() {
                sb.hero.rotate('next', heroshot)
            }, dur + fade)
            
        });

        


        sb.hero.rotate = function(dir, heroshot) {
            if(typeof dir == 'undefined') {
                var dir = 'next'
            }
            if(typeof heroshot == 'undefined') {
                return
            }
            
            var images = heroshot.children('div.slide')
            var current = heroshot.children('div.slide[current]')
            if(dir == 'next') {
                if(current.next('div.slide').size()) {
                    var to = current.next('div.slide')
                } else {
                    var to = $(images[0])
                }
            } else {
                if(current.prev('div.slide').size()) {
                    var to = current.prev('div.slide')
                } else {
                    var to = $(images[images.size() - 1])
                }
            }
            
            var fade = heroshot.attr('fade')
            current.removeAttr('current').fadeOut(fade / 2);
            //current.removeAttr('current').hide("slide", { direction: "right" }, fade / 2);
            to.attr({current: 'current'}).fadeIn(fade /2);
            //to.attr({current: 'current'}).show("slide", { direction: "left" }, fade / 2);
            
        }
            
    }

    

        sb.lightbox = function(ajax, html) {
            if(typeof ajax == 'undefined') {
                ajax = false;
            }
            if(typeof html == 'undefined') {
                html = '';
            }
            if(typeof initLightbox == 'function') {
                Event.stopObserving(window, 'load', initLightbox, false);
            }
            $(window).load(function(){
                Lightbox = function() {
                    return false;
                }
                ImageGallery = function() {
                    return false;
                }
            })
            if(!$('#overlay').size()) {
                $('body').append(
                        $(jQuery('<div />'))
                            .attr({ 'id': 'overlay' })
                            .css({'display': 'none'})
                    )
            }
            sb.lightbox.overlay = $('#overlay').height($('body').height())

            if(!$('#popup').size()) {
                $('body').append(
                        $(jQuery('<div />'))
                            .attr({ 'id': 'popup' })
                            .addClass('lightbox')
                            .css({'display': 'none'})
                    )
            }
            sb.lightbox.popup = $('#popup')

            sb.lightbox.closeLightbox = function() {
                sb.lightbox.popup.fadeOut('normal', function(){
                    if(sb.browserSucks) {
                        sb.lightbox.overlay.hide()
                    } else {
                        sb.lightbox.overlay.fadeOut('normal')
                    }
                })
                sb.lightbox.popup.fadeOut('normal')
                if(typeof sb.lightbox.photoTarget != 'undefined') {
                sb.lightbox.photoTarget.find('img').remove()
                }
            }

            if(!sb.lightbox.popup.find('a.close').size()) {
                sb.lightbox.close = $(jQuery('<a />'))
                sb.lightbox.close.addClass('close').html('Close').attr({'href': '#close'}).click(function(c){
                    c.preventDefault() 
                    sb.lightbox.closeLightbox()
                })
                sb.lightbox.close.appendTo(sb.lightbox.popup)
            }

            sb.lightbox.hotkeys = function(e) {
                e.preventDefault()
                var key = e.which
                if(key == 0 || key == 120) { // Esc or X
                    sb.lightbox.closeLightbox()
                } else if(key == 110) { // P
                    if(typeof sb.lightbox.next != 'undefined') {
                        sb.lightbox.next.click()
                    }
                } else if(key == 112) { // N
                    if(typeof sb.lightbox.prev != 'undefined') {
                        sb.lightbox.prev.click()
                    }
                }
            }

            if(!ajax) {
                sb.lightbox.links = $('a[rel*=lightbox]')
            } else if(typeof html == 'object') {
                sb.lightbox.links = html.find('a[rel*=lightbox]')
            } else {
                return
            }

            if(!sb.lightbox.links.size()) {
                return
            }

            if(sb.lightbox.thumbsOnPopup && !sb.lightbox.popup.find('photo-wrapper').size()) {
                sb.lightbox.thumbs = $(jQuery('<div />'))
                sb.lightbox.thumbs.addClass('thumbs')
                sb.lightbox.thumbsTarget = $(jQuery('<div />'))
                sb.lightbox.thumbsTarget.addClass('thumbs-wrapper').appendTo(sb.lightbox.thumbs)
                sb.lightbox.photoTarget = $(jQuery('<div />'))
                sb.lightbox.photoTarget.addClass('photo-wrapper')
                sb.lightbox.thumbsTarget.width(sb.lightbox.thumbWidth * sb.lightbox.links.size())
            } else {
                sb.lightbox.photoTarget = sb.lightbox.popup
            }
            if(sb.lightbox.thumbsOnPopup) {
                if(!sb.lightbox.popup.find('photo-wrapper').size()) {
                    sb.lightbox.popup.append(sb.lightbox.photoTarget)
                    sb.lightbox.popup.append(sb.lightbox.thumbs)
                }
                sb.lightbox.thumbs.prev = $(jQuery('<a />'))
                sb.lightbox.thumbs.prev.addClass('prev').html('Previous').attr({'href': '#previous','title': 'Previous Photos'}).click(function(c) {
                    c.preventDefault()
                    sb.lightbox.thumbs.prev.blur()
                    var totalWidth = sb.lightbox.thumbsTarget.width()
                    var viewWidth = sb.lightbox.thumbs.width()
                    var currentLeft = parseInt(sb.lightbox.thumbsTarget.css('left'),10)
                    if(currentLeft + viewWidth >= 0) {
                        if(currentLeft != 0 ) {
                            sb.lightbox.thumbsTarget.animate({
                                'left': 0
                            })
                        }
                    } else {
                        sb.lightbox.thumbsTarget.animate({
                            'left': currentLeft + viewWidth
                        })
                    }
                })
                sb.lightbox.thumbs.prev.prependTo(sb.lightbox.thumbs)
                sb.lightbox.thumbs.next = $(jQuery('<a />'))
                sb.lightbox.thumbs.next.addClass('next').html('Next').attr({'href': '#next','title': 'Next Photos'}).click(function(c) {
                    c.preventDefault()
                    sb.lightbox.thumbs.next.blur()
                    var totalWidth = sb.lightbox.thumbsTarget.width()
                    var viewWidth = sb.lightbox.thumbs.width()
                    var currentLeft = parseInt(sb.lightbox.thumbsTarget.css('left'),10)
                    if(currentLeft - viewWidth < 0 - totalWidth) {
                        if(totalWidth + (currentLeft - viewWidth) < totalWidth % viewWidth) {
                            sb.lightbox.thumbsTarget.animate({
                                'left': 0 - totalWidth + (totalWidth % viewWidth)
                            })
                        }
                    } else {
                        sb.lightbox.thumbsTarget.animate({
                            'left': currentLeft - viewWidth
                        })
                    }
                })
                sb.lightbox.thumbs.next.appendTo(sb.lightbox.thumbs)
            }
            if(!sb.lightbox.thumbsOnPopup || sb.lightbox.prevNextAlways) {
                if(typeof sb.lightbox.prev == 'undefined') {
                    sb.lightbox.prev = $(jQuery('<a />'))
                    sb.lightbox.prev.addClass('prev').html('Previous').attr({'href': '#previous','title': 'Previous Photo'}).css({'visibility': 'hidden'}).click(function(c) {
                        c.preventDefault()
                        sb.lightbox.prev.blur()
                        if(sb.lightbox.photoTarget.find('img').size()) {
                            var count = parseInt(sb.lightbox.photoTarget.find('img').attr('count'),10)
                            $(sb.lightbox.links[count - 1]).click() 
                        }
                    })
                    sb.lightbox.prev.prependTo(sb.lightbox.photoTarget)
                }

                if(typeof sb.lightbox.next == 'undefined') {
                    sb.lightbox.next = $(jQuery('<a />'))
                    sb.lightbox.next.addClass('next').html('Next').attr({'href': '#next','title': 'Next Photo'}).css({'visibility': 'hidden'}).click(function(c) {
                        c.preventDefault()
                        sb.lightbox.next.blur()
                        if(sb.lightbox.photoTarget.find('img').size()) {
                            var count = parseInt(sb.lightbox.photoTarget.find('img').attr('count'),10)
                            $(sb.lightbox.links[count + 1]).click() 
                        }
                    })
                    sb.lightbox.next.appendTo(sb.lightbox.photoTarget)
                }

                sb.lightbox.photoTarget.hover(
                    function() {
                        sb.lightbox.prev.css({'visibility': 'visible'})
                        sb.lightbox.next.css({'visibility': 'visible'})
                    },
                    function() {
                        sb.lightbox.prev.css({'visibility': 'hidden'})
                        sb.lightbox.next.css({'visibility': 'hidden'})
                    }
                )
            }
            if(sb.lightbox.useCaptions) {
                sb.lightbox.caption = $(jQuery('<div />'))
                sb.lightbox.caption.addClass('caption').appendTo(sb.lightbox.photoTarget)
            }

            sb.lightbox.links.each(function(i){
                var link = $(this)
                link.find('img').css({
                    'width': '',
                    'height': ''
                })
                link.attr({'count': i})
                if(sb.lightbox.thumbsOnPopup) {
                    link.clone(true).click(function(c) {
                        c.preventDefault()
                        link.click()
                    }).appendTo(sb.lightbox.thumbsTarget)
                }
                link.click(function(c){
                    c.preventDefault()
                    link.blur()
                    var img = new Image()
                    if(sb.lightbox.popup.css('display') != 'block') {
                        img.onload = function() {
                            $(img).appendTo(sb.lightbox.photoTarget)
                            if(sb.browserSucks) {
                                sb.lightbox.overlay.show()
                                if(sb.browserSucksEggs) {
                                    scroll(0,0)
                                }
                            } else {
                                sb.lightbox.overlay.fadeIn('normal')
                            }
                            if(img.height > $(window).height()) {
                                sb.lightbox.popup.css({'position': 'absolute'})
                            }
                            sb.lightbox.photoTarget.width(img.width)
                            sb.lightbox.photoTarget.height(img.height)
                            sb.lightbox.photoTarget.css({
                                'margin-top': 0 - Math.ceil(img.height / 2),
                                'margin-left': 0 - Math.ceil(img.width / 2)
                            })
                            sb.lightbox.popup.fadeIn('normal')
                            if(ajax) {
                                sb.lightbox.overlay.find('.loading').remove()
                            }
                        }
                        img.src = link.attr('href')
                        $(img).attr({ 'count': link.attr('count') })
                        if(sb.lightbox.useCaptions) {
                            sb.lightbox.caption.html(link.attr('title'))
                        }
                    } else {
                        sb.lightbox.photoTarget.addClass('loading')
                        if(sb.lightbox.useCaptions) {
                            sb.lightbox.caption.fadeOut('normal', function() {
                                sb.lightbox.caption.html(link.attr('title'))
                            })
                        }
                        sb.lightbox.photoTarget.width(sb.lightbox.photoTarget.width())
                        sb.lightbox.photoTarget.height(sb.lightbox.photoTarget.height())
                        sb.lightbox.photoTarget.find('img').fadeOut('normal', function() {
                            img.style.display = 'none'
                            img.onload = function() {
                                sb.lightbox.photoTarget.find('img').remove()
                                $(img).appendTo(sb.lightbox.photoTarget)
                                if(sb.lightbox.useCaptions) {
                                    sb.lightbox.caption.fadeIn('normal')
                                }
                                if(img.height > $(window).height()) {
                                    sb.lightbox.popup.css({'position': 'absolute'})
                                }
                                sb.lightbox.photoTarget.css({
                                    'margin-top': 0 - Math.ceil(img.height / 2),
                                    'margin-left': 0 - Math.ceil(img.width / 2)
                                }, 'normal')
                                sb.lightbox.photoTarget.animate({
                                    'width': img.width,
                                    'height': img.height
                                }, 'normal')
                                $(img).fadeIn('normal', function() {
                                    sb.lightbox.photoTarget.removeClass('loading')
                                })
                                if(ajax) {
                                    sb.lightbox.overlay.find('.loading').remove()
                                }
                            }
                            img.src = link.attr('href')
                            $(img).attr({ 'count': link.attr('count') })
                        })
                    }
                })
            })
        }

        // Lightbox options
        sb.lightbox.thumbsOnPopup = false
        sb.lightbox.useCaptions = true
        sb.lightbox.thumbWidth = 196
        sb.lightbox.prevNextAlways = false

})();
