$(function(){
  
  setTimeout(function(){
    $('.notice').hide('blind');
  }, 5000);
  
  // ageless tv carousel setup
  $(".scrollable").scrollable({
    items: ".items",
    vertical: true,
    speed: 800,
    disabledClass: 'disabled-scroll',
    mousewheel: true 
    });
  
  // for the sub .bbq widget, keep a data object containing a mapping of
  // url-to-container for caching purposes.
  $('#sub').data( 'bbq', {
    cache: {
      // default content.
      'game-on': $(this).find('.bbq-default')
    }
  });
  
  // For all links inside a .bbq widget, push the appropriate state onto the
  // history when clicked.
  $('.bbq a[href^=#]:not(.play-video)').live( 'click', function(e){
    var state = {},
      
      // Get the id of this .bbq widget.
      id = $(this).closest( '.bbq' ).attr( 'id' ),
      
      // Get the url from the link's href attribute, stripping any leading #.
      url = $(this).attr( 'href' ).replace( /^#/, '' );
      
    // if id is 'main', set sub to main's top sub link
    if(id == 'main'){
      var sub = $("#sub .nav-"+url+" li:first a").attr('href').replace(/#/,'');
      // Set the state!
      state[ id ] = url;
      state[ 'sub' ] = sub;
      $.bbq.pushState( state );
    }else{
      // Set the state!
      state[ id ] = url;
      $.bbq.pushState( state );
    }
    
    // And finally, prevent the default link click behavior by returning false.
    return false;
  });
  
  // Bind an event to window.onhashchange that, when the history state changes,
  // iterates over all .bbq widgets, getting their appropriate url from the
  // current state. If that .bbq widget's url has changed, display either our
  // cached content or fetch new content to be displayed.
  $(window).bind( 'hashchange', function(e) {
    //alert('hash changed');
    var defaultMain = 'opportunity';
    
    // get the main url hash
    var main = e.getState('main') || '',
      sub = e.getState('sub') || '';
    
    // vars for validation
    var mainValid = false;
    var subValid = false;
    
    // check that main exists
    var mainurls = [];
    $("#main li a").each(function(){
      mainurls.push($(this).attr('href').replace(/#/,''));
    });
    // if main is blank or doesn't exist set it to the default value 
    // and set sub to the top side of the default value
    if($.inArray(main,mainurls) == -1){
      main = defaultMain;
      sub = $("#sub .nav-"+main+" li:first a");
      if(sub.length != 0){
        sub = sub.attr('href').replace(/#/,'');
      }
    }else{
      // if main passed all of the above validations...
      mainValid = true;
    }
    
    // now main is validated
    // check that sub exist in the current main
    var suburls = [];
    $("#sub .nav-"+main+" li a").each(function(){
      suburls.push($(this).attr('href').replace(/#/,''));
    });
    // if sub isn't in main's sub nav then set it to the top of main's sub nav
    if($.inArray(sub,suburls) == -1){
      sub = $("#sub .nav-"+main+" li:first a")
      if(sub.length != 0){
        sub = sub.attr('href').replace(/#/,'');
      }
    }else{
      // if sub passed all of the above validations...
      subValid = true;
    }
    
    if(mainValid != true || subValid != true){
      // main and/or sub had to be changed
      // call pushState to update to the new values
      $.bbq.pushState({'main':main,'sub':sub});
    }else{
      // the url is valid, move on
      
      // set the title to be the 'sub'
      // THIS CANNOT BE DONE WITH JQUERY
      document.title = sub.replace(/-/g," ").capitalize()
      
      // turn current images 'off'
      $('.bbq-current img').each(function(){
        var imgOn = $(this).attr('src');
        $(this).attr('src', imgOn.replace(/on/,'off'));
      });
      // remove .bbq-current class from any previously "current" links
      $('a.bbq-current').removeClass('bbq-current');
      
      // add .bbq-current to current links
      $('a[href=#'+main+']').addClass('bbq-current');
      $('a[href=#'+sub+']').addClass('bbq-current');
      
      // turn new current images 'on'
      $('.bbq-current img').each(function(){
        var imgOff = $(this).attr('src');
        $(this).attr('src', imgOff.replace(/off/,'on'));
      });
      
      // hide any visible sub navs
      // show sub nav
      // if 'sub' is in the currently visible skip this
      if($("#sub ul:visible li a[href='#"+sub+"']").length == 0){
        if($("#sub ul:visible").length != 0){
          $("#sub ul:visible").hide('slide',function(){
            $("#sub .nav-"+main).show('slide');
          });
        }else{
          $("#sub .nav-"+main).show('slide');
        }
      }
      
      // load cached content if it's already stored
      // else make ajax call to load content
      
      // sub is the important part concerning the cached content
      // get sub's data cache
      var data = $('#sub').data('bbq');
      
      if ( data.cache[ sub ] ) {
        // Since the widget is already in the cache, it doesn't need to be
        // created, so instead of creating it again, let's just show it!
        if($(".content .bbq-item:visible").length != 0){
          $(".content .bbq-item:visible").hide('blind',function(){
            data.cache[sub].show('blind');
          });
        }else{
          data.cache[sub].show('blind');
        }
        
      } else {
        // hide current content and show loading div
        $('.bbq-loading').show();
        data.cache[sub] = $( '<div class="bbq-item"/>' )
          .appendTo($('.content'))
          .load(sub.replace(/-/g,'_'), function(){
            $('.bbq-loading').hide();
            if($(".content .bbq-item:visible").length != 0){
              $(".content .bbq-item:visible").hide('blind',function(){
                $(".content .bbq-item:has(."+sub+")").show('blind');
              });
            }else{
              $(".content .bbq-item:has(."+sub+")").show('blind');
            }
          });
      }
      
    }
  });
  
  // Since the event is only triggered when the hash changes, we need to trigger
  // the event now, to handle the hash the page may have loaded with.
  $(window).trigger( 'hashchange' );
  
  // Video code
  $('.aw-video, .aw-tv').live('click', function(e){
    var cdn = 's19cpp0ci72lha.cloudfront.net/';
    var href = $(this).attr('href');
    var formattedHref = href.replace(/_\d\d\dx\d\d\d/,"");
    var windowWidth = $(window).width();
    var windowHeight = $(window).height();
    
    // set video tag and wrapper based on clicked class
    var videoWrap, videoBg;
    var agelessTv = false;
    if($(this).hasClass('aw-tv')){
      agelessTvClose();
      agelessTv = true;
      videoWrap = $('.ageless-tv-wrap');
      videoBg = $('.video-bg');
      // setting highlighted link
      $('.active-tv').removeClass('active-tv');
      $(this).addClass('active-tv');
    }else{
      videoWrap = $('.video-wrap');
      videoBg = $('.video-bg');
    }
    
    // setting width and height based on youtube check
    if(href.indexOf("youtube") == -1){
      var wReg = /_\d\d\dx/;
      var hReg = /x\d\d\d/;
      var videoWidth = wReg.exec(href).toString().replace(/_/,"").replace(/x/,"");
      var videoHeight = hReg.exec(href).toString().replace(/x/,"");
    }else{
      var wReg = /width="\d\d\d/;
      var hReg = /height="\d\d\d/;
      var videoWidth = wReg.exec(href).toString().replace(/width="/,"");
      var videoHeight = hReg.exec(href).toString().replace(/height="/,"");
    }
    
    if($(this).hasClass('aw-video')){
      videoWrap.css('width', videoWidth + "px");
      videoWrap.css('height', videoHeight + "px");
      var marginLR = Math.floor((windowWidth - videoWidth)/2);
      var marginTB = Math.floor((windowHeight - videoHeight)/2);
      videoWrap.css('margin', marginTB+'px '+marginLR+'px '+marginTB+'px '+marginLR+'px');

      // Only height needs to be set (width is done in css)
      videoBg.css('height', windowHeight.toString() + 'px');
    }else{
      var ratio = videoWidth/videoHeight;
      if(videoHeight < videoWrap.width()/ratio){
        videoWrap.css('height', videoHeight + "px");
      }else{
        videoWrap.css('height', videoWrap.width()/ratio + "px");
      }
    }
    
    // check if the browser has flash
    if($.browser.flash == true){
      
      // check if the href is to youtube
      if(href.indexOf("youtube") == -1){
        // href is not to youtube so load flowplayer with correct file
        
        // putting "video" in the a tag was necessary to get the unload function to work
        videoWrap.append('<a id="rtmpPlayer" href="'+formattedHref+'">video</a>');
        
        flowplayer("rtmpPlayer","/flowplayer-3.2.1.swf",{
          clip: {
            urlResolvers: 'bwcheck',
            provider: 'rtmp',
            scaling: "fit",
            bitrates: [
              {url: 'mp4:'+formattedHref+'_600.mp4', bitrate: 600, isDefault: true},
              {url: 'mp4:'+formattedHref+'_350.mp4', bitrate: 350},
              {url: 'mp4:'+formattedHref+'_1200.mp4', bitrate: 1200}
            ]
          },
          plugins: {
            bwcheck: {
              url: '/flowplayer.bwcheck-3.2.1.swf',
              serverType: 'fms',
              dynamic: true,
              netConnectionUrl: 'rtmp://'+cdn+'cfx/st'
            },
            rtmp: {
              url: '/flowplayer.rtmp-3.2.0.swf',
              netConnectionUrl: 'rtmp://'+cdn+'cfx/st'
            }
          }
        });
        
        if($(this).hasClass('aw-video')){
          videoWrap.fadeIn();
          videoBg.fadeIn();
        }
        // Because the a tag has content you need to force the player to start
        $f().play();
      }else{
        // code for youtube video embeds
        youTubeEmbed(href,agelessTv);
      }
    }else{
      // no flash
      // check for youtube link
      if(href.indexOf("youtube") == -1){
        // not youtube, add video tag with href and style tags
        videoWrap.css('width', videoWidth + "px");
        videoWrap.css('height', videoHeight + "px");
        var marginLR = Math.floor((windowWidth - videoWidth)/2);
        var marginTB = Math.floor((windowHeight - videoHeight)/2);
        videoWrap.css('margin', marginTB+'px '+marginLR+'px '+marginTB+'px '+marginLR+'px');
        videoWrap.append('<video poster="/images/'+formattedHref+'.png" width="'+videoWidth+'px" height="'+videoHeight+'px"> \
                                  <source src="http://d26c8csmorb8lw.cloudfront.net/'+formattedHref+'_600.mp4" /> \
                                 </video>');
        videoWrap.fadeIn();
        videoBg.fadeIn();
      }else{
        // youtube video still accessible on iphone/ipad/android
        youTubeEmbed(href);
      }
    }
    return false;
  });
  // Closing video
  $('.video-bg, .video-wrap img').click(function(){
    closeVideo();
  });
  // keeping the movie and background centered on window resizing
  $(window).resize(function() {
    var videoWrap = $('.video-wrap');
    $('.video-bg').css('height', $(window).height() + "px");
    var marginLR = Math.floor(($(window).width() - videoWrap.width())/2);
    var marginTB = Math.floor(($(window).height() - videoWrap.height())/2);
    $('.video-wrap').css('margin', marginTB+'px '+marginLR+'px '+marginTB+'px '+marginLR+'px');
  });
});

var youTubeEmbed = function(href,agelessTv){
  if(agelessTv == false){
    $('.video-wrap').append(href);
    $('.video-wrap').fadeIn();
    $('.video-bg').fadeIn();
  }else{
    $('.ageless-tv-wrap').append(href);
  }
  
}

var closeVideo = function(){
  $f('*').each(function(){
    this.unload();
  });
  $('.video-wrap a, .video-wrap object, .video-wrap video').remove();
  $('.video-wrap').hide();
  $('.video-bg').fadeOut();
}

var agelessTvClose = function(){
  $f('*').each(function(){
    this.unload();
  });
  $('.ageless-tv-wrap a, .ageless-tv-wrap object, .ageless-tv-wrap video').remove();
}

// capitalization code added to String class
String.prototype.capitalize = function(){
 return this.replace( /(^|\s)([a-z])/g , function(m,p1,p2){ return p1+p2.toUpperCase(); } );
};