$(function() {
    
    window.Frontpage = window.Frontpage || {}
    
    
    var SimpleCarousel = function(container, items, dotContainer) {
        
        var itemInterval = null
        ,   self = this
        ,   navLocked = false
        ,   $pc = $(container)
        ,   $items = $(items)
        ,   $dotContainer = dotContainer ? $(dotContainer) : null
        ,   curItem = 0
        ,   itemWidth = $items.first().width()
        ;
    
        var navTo = function(i) {
            if (i >= $items.length) return false
            if (navLocked) return false;
            if (curItem == i) return false;
            var $item = $(items).get(i)
            //pos = parseInt($pc.css('left')) - itemWidth
            navLocked = true;
            $pc.animate({left:-itemWidth * i +'px'}, function() {
                navLocked = false;
                curItem = i;
                if ($dotContainer) {
                    setDot(i)
                }
            })
            return true
        }
        var setDot = function(i) {
            var $dots = $dotContainer.find('.pos-dot').removeClass('active')
            ,   $active = $($dots.get(i)).addClass('active')
        }
        
        // Associate a position dot with each item element
        // add the position dot to the position dot container
        if ($dotContainer.length > 0) {
            $items.each(function(i,elem) {
                var $elem = $(elem)
                ,   $posDot = $('<div class="pos-dot"></div>')

                $elem.data('posDotNum',i);
                $posDot.data('posDotNum',i)
                    .click(function() {
                        navTo($(this).data('posDotNum'));
                    })

                $dotContainer.append($posDot);
            })
        }
        
        
    
        this.itemNavForward = function() {
            if (curItem+1 >= $items.length)
                return navTo(0)
            return navTo(curItem+1)
        }
        this.itemNavBack = function() {
            if (curItem-1 < 0)
                return navTo($items.length-1)
            return navTo(curItem-1)
        }
        this.itemNavReset = function() {
            navTo(0);
        }
        this.itemNavSkipToEnd = function() {
            navTo($items.length-1);
        }
        this.startItemScroll = function() {
            if (itemInterval) return
            itemInterval = setInterval(function() {
                if (!self.itemNavForward()) self.itemNavReset()
            },3000)
        }
        this.pauseItemScroll = function() {
            clearInterval(itemInterval);
            itemInterval = null;
        }
        navTo(0);
        setDot(0);
        this.startItemScroll();
    }
    
    
    /*
    * Floating Header
    *
    */
    var $curHighlighted = null
    ,   $menuHighlight = $('<div class="menu-highlighter">')
            .hide()
            .data('hidden',true)
            .appendTo($('.floating-header .header-inner'))
    ,   $sections = $('section')
    ,   scrollTimeout = null
    ,   isScrolledIntoView = function($elem) {
            var docViewTop = $(window).scrollTop() + 250 //$(window).height()/2
            ,   docViewBottom = docViewTop + $(window).height()
            ,   elemTop = $elem.offset().top
            ,   elemBottom = elemTop + $elem.height()

            return ((elemBottom >= docViewTop) && (elemTop <= docViewBottom)
              && (elemBottom <= docViewBottom) &&  (elemTop >= docViewTop) );
    }
    ,   moveHighlightTo = function($menuElem) {
            if (!$menuElem) {
                if (!$curHighlighted) return
            } else {
                if ($curHighlighted && $menuElem[0] == $curHighlighted[0]) return
            }
            $curHighlighted ? $curHighlighted.removeClass('highlighted') : null
            $curHighlighted = $menuElem;
            if (!$menuElem) {
                $menuHighlight.data('hidden',true);
                $menuHighlight.hide();
                return
            }
            $menuElem.addClass('highlighted');
            highlightAttrs = {
                left:parseInt($menuElem.closest('.menu-item').position().left)+5+'px', 
                top:parseInt($menuElem.closest('.menu-item').position().top)+2+'px',
                width:$menuElem.width()
            }
            if ($menuHighlight.data('hidden')) {
                $menuHighlight.css(highlightAttrs).show().data('hidden',false);
                return
            }
            $menuHighlight.stop(true,true).animate(highlightAttrs,400)
            
        }
    ,   scrollPageTo = function($elem,callback) {
            $('html,body').animate({scrollTop:$elem.offset().top-40},300,callback)
        }
    ;
    
    $(document).scroll(function(e) {
        if (scrollTimeout) return
        scrollTimeout = setTimeout(function() {
            scrollTimeout = null;
            var elem = document.elementFromPoint(0,120)
            ,   elId = $(elem).closest('div.section').attr('id')
            ,   $menuLink = $('a[href=#'+elId+']')
            moveHighlightTo($menuLink.length == 0 ? null : $menuLink)  
            if($(elem).attr('id') == 'about'){
                $('#contact-us-popup').animate({
		    //opacity:'0.4',
		    opacity:'1',
                    bottom: '-200px'
                },500,function(){
                    $('div.header-switch span.switch-icon').html('+').removeClass('open');
                    $(this).addClass('hidden');
                });
            }
            else if($(elem).attr('id') != 'about' && $('#contact-us-popup').hasClass('hidden')){
                $('#contact-us-popup').animate({
                    bottom: '-150px'
                },500,function(){
                    $(this).removeClass('hidden');
                });
            }

        },300)

    })
    $('.menu-item a').click(function() {
	//moveHighlightTo($(this)); // Move menu highlight
        
        var anchor = $(this).attr('href')
        ,   $section = $(anchor);
        scrollPageTo($section, function() {
            location.hash = anchor
        });
        return false;
    })
    $('.floating-header .logo').click(function() {
        scrollPageTo($('#splash'), function() {
            location.hash = ''
        })
    })
    
    
    /*
    * Promos
    *
    */
    $('.promo .about').hide()
    $('.promo').hover(function() {
        $(this).find('.about').show('fade',400);
    }, function() {
        $(this).find('.about').hide('fade',400);
    });
    
    var promoCarousel = new SimpleCarousel('.promo-container','.promo','.promo-dots')
    promoCarousel.pauseItemScroll();
    
    $('.promo-nav.forward').click(function() {
        promoCarousel.itemNavForward();
    });
    $('.promo-nav.back').click(function() {
        promoCarousel.itemNavBack();
    });
    
    /*
    * Examples
    *
    */
    var exampleCarousel = new SimpleCarousel('.example-container','.example','.example-dots')
    exampleCarousel.pauseItemScroll(); // Just turn off scrolling
    
    $('.example-nav.forward').click(function() {
        exampleCarousel.itemNavForward()
    });
    $('.example-nav.back').click(function() {
        exampleCarousel.itemNavBack()
    });
    
    
    /* 
    * Logos
    *
    */
    Frontpage.setupLogo = function(posX,posY,width,height,className,link) {
        var $logo = $('<div class="logo '+className+'"><div class="colored"></div></div>').css({
                position:'absolute',
                left:posX+'px',
                top:posY+'px',
                width:width+'px',
                height:height+'px',
                cursor:link ? 'pointer' : 'default'
            }).click(function() {
                if (link) window.open(link)
            })
        ,   $colored = $logo.find('.colored').css({
                'background-position':-posX + 'px ' + -posY + 'px',
                position:'relative',
                width:width+'px',
                height:height+'px',
                overflow:'hidden'
            }).hide()
        
        var timeouts = {}
        $logo.hover(function() {
            /*$('.logo.'+className+' .colored').show('fade',400)
            $('.logo:not(.'+className+') .colored').hide('fade',400)*/
            $(this).find('.colored').show('fade',400);
        },function() {
            $(this).find('.colored').hide('fade',400);
        })
        
        $('.logos-container').append($logo);
    }
    
    // Setup all the logos
    $.each([
        [0,0,  240,120,'airport','http://www.portseattle.org'],// Port of seattle
        [0,120,240,120,'airport','http://www.flyoakland.com/'],
        [0,240,240,120,'hotel','http://www.ichotelsgroup.com/crowneplaza/'],
        [0,360,240,120,'hotel','http://doubletree1.hilton.com/en_US/dt/index.do'],
        //[0,480,240,120,'hotel','http://www.hiexpress.com/hotels/us/en/reservation'],
        
        [240,0,  180,120,'foodservice','http://www.buffalowildwings.com'],
        [240,120,180,120,'airport','http://flydenver.com/'],
        [240,240,180,120,'hotel','http://hiltongardeninn1.hilton.com/en_US/gi/index.do'],
        [240,360,180,120,'hotel','http://www.radisson.com/'],
        //[240,480,180,120,'airport','http://www.san.org/'],
        
        [420,0,  180,120,'airport','http://www.ocair.com'],
        [420,120,180,120,'transit','http://www.bp.com/productslistsearch.do?categoryId=9006961&contentId=7013632'],
        [420,240,180,120,'hotel','http://www.starwoodhotels.com/fourpoints/index.html'],
        [420,360,180,120,'hotel','http://www.americinn.com/'],
        //[420,480,180,120,'hotel','http://www.lq.com/'],
        
        [600,0,  180,120,'airport','http://www.mccarran.com/'],
        [600,120,180,120,'airport','http://charmeck.org/city/charlotte/Airport/'],
        [600,240,180,120,'airport','http://www.flysanjose.com/'],
        [600,360,180,120,'hotel','http://www.ichotelsgroup.com/candlewood/'],
        //[600,480,180,120,'hotel','http://www.countryinns.com/'],
        
        [780,0,  240,120,'foodservice','http://www.subway.com/'],
        [780,120,240,120,'hotel','http://www.starwoodhotels.com/westin/'],
        [780,240,240,120,'hotel','http://www.holidayinn.com/'],
        [780,360,240,120,'airport','http://www.pitairport.com/'],
        //[780,480,240,120,'airport','http://www.yvr.ca/en/Default.aspx'],
        
    ], function(i,logoData) {
        Frontpage.setupLogo.apply(this,logoData)
   });
   var secret = 'KITTEN'.split('')
   $(document).bind('keyup', function(e) {
       (secret.indexOf(String.fromCharCode(e.keyCode)) == 0) && secret.shift()
       if (secret.length == 0) {
          var im = $($('.bio img').get(Math.floor(Math.random()*$('.bio img').length)))
          ,    r1 = Math.floor(Math.random()*30)
          ,    r2 = Math.floor(Math.random()*30)
          im.attr('src','http://www.placekitten.com/g/'+(parseInt(im.width())+parseInt(r1))+'/'+(parseInt(im.height())+parseInt(r2))+'/')
          secret = 'KITTEN'.split('')
       }
   })
    
});
