/*****
 * NAMESPACE: Skyline
 *****/

var Skyline = {
  tabletBreakpoint: 768,
  bodyListener: null,
  tabletDown: false,
  initCtas: false,
  mobileCalls: false,
  slideshowLoadFinished: false,
  winWidth: 0,    // used to fix Mobile Chrome resize bug
  
  // menu font scaling controls
  menuFont: {
    family: '',   // font family
    max: 18,      // max font size in px
    min: 8,       // min font size in px
    cur: 0,       // cur font size (leave at 0 to auto-initialize)
    height: 105,  // max height of target container
    inc: 0.5      // font scale increments
  },

  // cta font scaling controls
  ctaFont: {
    family: '',   // font family
    max: 18,      // max font size in px
    min: 8,       // min font size in px
    cur: 0,       // cur font size (leave as 0 to auto-initialize - HACK: used as array for ctas)
    height: 55,   // max height of target container
    inc: 0.5      // font scale increments
  },

  // callout font scaling controls
  calloutFont: {
    family: '',   // font family
    max: 25,      // max font size in px
    min: 8,       // min font size in px
    cur: 0,       // cur font size (leave as 0 to auto-initialize - HACK: used as array for ctas)
    height: 50,   // max height of target container
    inc: 0.5      // font scale increments
  },

  // corp search font scaling controls
  searchFontCorp: {
    family: '',   // font family
    max: 30,      // max font size in px
    min: 8,       // min font size in px
    cur: 0,       // cur font size (leave as 0 to auto-initialize - HACK: used as array for ctas)
    height: 67,   // max height of target container
    inc: 0.5      // font scale increments
  },
  
  /**
   * Fires on document.ready
   */
  init: function(){
    this.initNavMenu();
    this.changeNavBreakpoint();
    this.typekit();
    this.adjustRowsForWindowWidth();
    this.initSlideshow();
    this.moveCalls();
    this.moveCtas();
    this.moveSocial();
    this.stripImgBorders();
    this.initVideos();
    this.responsiveVideos();
    this.initZipFocus();
    this.wrapContentLIs();
    this.cleanupPhoneNumbers();
    this.suppressTelLink();
    this.addHcardToFooter();
    this.initFloorplanModal();
    this.fixChromeWindowWidth();
  },

  /**
   * Fires on resize and orientationchange events
   *
   * @param     context   {Object}    self-referential context (required by debouncer for timeout)
   */
  resize: function(context) {
    if (!context) { context = this; }

    context.changeNavBreakpoint();
    context.typekit();
    context.adjustRowsForWindowWidth();
    context.positionCall();
    context.moveSocial();
    context.resizeVideos();
  },

  fixChromeWindowWidth: function(){
    if ($.browser.chrome && this.isTouchDevice()){
      return this.setWindowWidth();
    }
    return true;
  },

  setWindowWidth: function(){
    var wWidth = $(window).width();
    if (wWidth != this.winWidth){
      this.winWidth = wWidth;
      return true;
    }
    return false;
  },

  isCorp: function(){
    return $('body').hasClass('corp');
  },

  isStore: function(){
    return $('body').hasClass('store');
  },

  isHome: function(){
    return $('body').hasClass('home');
  },

  isInterior: function(){
    return $('body').hasClass('interior');
  },

  /**
   * Fires when typekit font-scaling needs updating
   */
  typekit: function() {
    this.fitNavMenuFonts();
    this.fitCalloutFonts();
    this.fitCTAFonts();
  },

  /**
   * Returns true if viewport width is <= tablet width (768px)
   */
  isTabletDown: function(){
    return Modernizr.mq('(max-width: '+this.tabletBreakpoint+'px)');
  },

  /**
   * Returns true if viewport width is <= tablet width (575px)
   */
  is575Down: function(){
    return Modernizr.mq('(max-width: 575px)');
  },

  /**
   * Returns true if device supports touch (or is IE Mobile, since Windows Phones hate Modernizr)
   */
  isTouchDevice: function(){
    return (Modernizr.touch || this.isIEMobile());
  },

  isIEMobile: function(){
    return navigator.userAgent.match(/iemobile/i)
  },

  cleanupPhoneNumbers: function() {
    try {
      var contents = $('body *').addBack().contents();
      var regex = /[0-9][0-9][0-9]-[0-9][0-9][0-9]-[0-9][0-9][0-9][0-9]/;
      contents.each(function() {
        if (this.nodeType == 3){ // only parse text nodes
           var match = this.nodeValue.match(regex);
           if (match && match.length){
              for(i = 0; i < match.length; i++){
                var start = this.nodeValue.indexOf(match[i]);
                for (j = start; j < start+match[i].length; j++){
                  if (this.nodeValue.substr(j, 1) == '-'){
                    this.nodeValue = this.nodeValue.substr(0, j) + "." + this.nodeValue.substr(j+1);
                  }
                }
              }
           }
        }
      });
    } catch (e) {
      // suppress IE9's false XSS detection
    }
  },

  /**
   * Initializes the navigation menu parent classes and toggle menu states
   */
  initNavMenu: function(){
    $(".nav li a").each(function() {
      if ($(this).next().length > 0) {
        $(this).addClass("parent");
      };
    })

    var touchEvent = (this.isTouchDevice() && !this.isIEMobile()) ? 'touchstart' : 'click';
    $(".toggleMenu").on(touchEvent, function(e) {
      var elem = $(e.currentTarget);
      if (elem.hasClass('active')){
        elem.removeClass('active');
        $('.nav').hide();
        $('.nav-holder').removeClass('active');
      } else {
        elem.addClass('active');
        $('.nav-holder').addClass('active');
        $('.nav').show();
        this.addBodyListener();
      }
      return noEvent(e);
    }.bind(this));
    this.adjustNavMenu();
  },

  /**
   * Adjusts the navigation menu and sets click/touch bindings based on device metrics
   */
  adjustNavMenu: function() {
    // clear all nav menus on resize or orientation
    this.hideNavMenu();

    var $toggleMenu = $('.toggleMenu');
    var $nav = $('.nav');
    var $navLi = $nav.find('li');
    
    // if in < tablet resolution, add hover bindings
    if (this.isTabletDown()) {
      $toggleMenu.css("display", "inline-block");
      if (!$toggleMenu.hasClass("active")) {
        $nav.hide();
      } else {
        $nav.show();
        this.addBodyListener();
      }
      $navLi.unbind('mouseenter mouseleave');
      this.bindMobileMenu();
    }

    // if > tablet resolution and touch device, add touch detection to nav menus
    else if (this.isTouchDevice() && !this.isIEMobile() && !this.isTabletDown()) {
      $toggleMenu.removeClass('active').css("display", "none");
      $nav.show();
      this.bindMobileMenu();
    }
    // if > tablet resolution and not touch, add click detection
    else if (!this.isTabletDown()) {
      this.bindDesktopNavMenu();
    }
    // if Modernizr fails, use fallback desktop behavior
    else if (Modernizr.mq() === false) {
      this.bindDesktopNavMenu();
    }
  },

  /**
   * Removes the hover CSS properties on all LIs that are siblings or
   * descendants of the siblings of the specified LI. Prevents same-level nav
   * menus form getting stuck.
   *
   * @param     $li   {jQuery}    LI jQuery object with new hover state
   */
  removeNavSiblingHover: function($li){
    // disable multiple hover states on desktop mode
    if (!this.isTabletDown() && $li){
      $li.siblings('li').each(function(){
        $(this).removeClass("hover");
        $(this).find('li').removeClass("hover");
        $(this).find('a').removeClass("hover");
      });
    }
  },

  /**
   * Sets the hover CSS properties for a nav menu LI and it's child A tag.
   * This is used to smooth out bad hover state hit detection on touch devices
   * by removing dependency on the :hover pseudo-state
   *
   * @param     $li   {jQuery}          nav LI jQuery object
   * @param     hover       {boolean}   if true, set hover, otherwise remove hover
   */
  setNavMenuHover: function($li, hover){
    if ($li){
      var $link = $li.find('> a');
      if (hover){
        $li.addClass('hover');
        $link.addClass('hover');
      } else {
        $li.removeClass('hover');
        $link.removeClass('hover');
      }
    }
  },

  /**
   * Bind touch/click behavior to touch device menus
   */
  bindMobileMenu: function() {
    var $navLi = $('.nav li');
    $navLi.removeClass('hover');
    $navLi.find('a').removeClass('hover');

    // stop propagation up to body listener if we touch on the menu
    if (this.isTouchDevice() && !this.isIEMobile()){
      $navLi.unbind('touchstart').bind('touchstart', function(e){
        e.stopPropagation();
      });
    } else {
      $navLi.unbind('mouseenter').bind('mouseenter', function(e){
        //this.setNavMenuHover($(e.currentTarget), true);
        $(e.currentTarget).find('> a').addClass('hover');
      }.bind(this));
      $navLi.unbind('mouseleave').bind('mouseleave', function(e) {
        //this.setNavMenuHover($(e.currentTarget), false);
        $(e.currentTarget).find('> a').removeClass('hover');
      }.bind(this));
    }
    // bind normal click behavior
    $navLi.find("a").unbind('click').bind('click', function(e){
      var $elem = $(e.currentTarget);
      var $li = $elem.parent('li');
      this.removeNavSiblingHover($li);
      this.setNavMenuHover($li, true);
      window.location = $elem.attr("href");
      return noEvent(e);
    }.bind(this));

    // bind parent menu toggle behavior
    var clickEvent = (this.isTouchDevice() && !this.isIEMobile()) ? 'touchstart' : 'click';
    $navLi.find("a.parent").unbind(clickEvent).bind(clickEvent, function(e) {
      var $elem = $(e.currentTarget);
      var $li = $elem.parent('li');
      this.removeNavSiblingHover($li);
      this.setNavMenuHover($li, !$li.hasClass('hover'));

      // add body touch listener if we are in 'hover' subnav
      if ($li.hasClass('hover')){
        this.addBodyListener();
      }
      return noEvent(e);
    }.bind(this));
  },

  /**
   * Bind hover behavior to desktop menu
   */
  bindDesktopNavMenu: function(){
    if (!this.isTouchDevice()){
      $(".toggleMenu").removeClass('active').css("display", "none");

      var $nav = $('.nav');
      var $navLi = $nav.find('li');

      $nav.show();
      $navLi.find('a').removeClass('hover').unbind('click');
      
      $navLi.unbind('mouseenter').bind('mouseenter', function(e){
        var $li = $(e.currentTarget);
        this.removeNavSiblingHover($li);
        this.setNavMenuHover($li, true);
      }.bind(this));
      $navLi.unbind('mouseleave').bind('mouseleave', function(e) {
        var $li = $(e.currentTarget);
        this.setNavMenuHover($li, false);

        // remove hover from all sub LIs
        $li.find('li').removeClass('hover');
        $li.find('li a').removeClass('hover');

        // recursively clean up hover states on parent in case mouseleave doesn't propagate
        var $parentLi = $li.parents('li').length ? $li.parents('li').first() : [];
        while ($parentLi.length && !$parentLi.is(":hover")){
          this.setNavMenuHover($parentLi, false);
          $parentLi = $parentLi.parents('li').length ? $parentLi.parents('li').first() : [];
        }
      }.bind(this));
    }
  },

  /**
   * Hides the navigation menu
   */
  hideNavMenu: function(){
    $('.nav li').removeClass('hover');
    $('.nav li a').removeClass('hover');
    if (this.isTabletDown()){
      $('.nav').hide();
      $('.nav-holder').removeClass('active');
      $('.toggleMenu').removeClass('active');
    }
  },

  /**
   * Adds a body listener, which hides menus on touch devices when touched outside the menu
   */
  addBodyListener: function(){
    if (this.isTouchDevice() && !this.isIEMobile() && !this.bodyListener){
      this.bodyListener = $('body').bind('touchstart', function(e){
        if (this.bodyListener){
          this.hideNavMenu();
          $('body').unbind('touchstart', this.bodyListener);
          this.bodyListener = null;
          return noEvent(e);
        }
      }.bind(this));
    }
  },

  /**
   * Attempts to fit any given font-family into the space allocated for the #nav (in desktop mode only)
   */
  fitNavMenuFonts: function(){
    if (!this.isTabletDown()) {
      var nav = $('#nav');
      var topTierLinks = nav.find('a.top-level');
      var navWidth = Math.floor(nav.width());

      if (!this.menuFont.cur){
        this.menuFont.cur = parseInt(topTierLinks.first().css('font-size'));
      }
      if (!this.menuFont.family.length){
        this.menuFont.family = parseInt(topTierLinks.first().css('font-family'));
      }

      // set starting font size (reduces double-tapping on resize events)
      var fontSize = this.menuFont.cur;

      // if actual nav width is less than total width needed, shrink font until it fits or min is reached
      if (navWidth <= this.getNavMenuWidth()){
        while (navWidth <= this.getNavMenuWidth() && fontSize > this.menuFont.min){
          fontSize -= this.menuFont.inc;
          topTierLinks.css('font-size',fontSize+'px');
        }
      }
      // if actual nav width is greater than total width needed, increase font until it fits or max is reached
      else {
        while (navWidth > this.getNavMenuWidth() && fontSize < this.menuFont.max){
          fontSize += this.menuFont.inc;
          topTierLinks.css('font-size',fontSize+'px');
        }
        while (navWidth <= this.getNavMenuWidth() && fontSize > this.menuFont.min){
          fontSize -= this.menuFont.inc;
          topTierLinks.css('font-size',fontSize+'px');
        }
      }

      // remember last font size
      this.menuFont.cur = fontSize;
    } else {
      if (this.menuFont.cur != this.menuFont.max){
        this.menuFont.cur = this.menuFont.max;
        $('#nav a.top-level').css('font-size', this.menuFont.cur);
      }
    }
  },

  /**
   * Sums up the actual outer widths of each LI in the #nav, so we can manually detect overflow
   *
   * @return    {integer}     pixel width of total LIs in #nav
   */
  getNavMenuWidth: function(){
    var nw = 0;
    $('#nav > li').each(function(){
      nw += $(this).outerWidth();
    });
    return nw + this.getBrowserWidthFix();
  },

  /**
   * Firefox and IE don't get the right outerWidth calcs (they use floor versus ceiling),
   * so adjust by the partial remaining partial pixels
   */
  getBrowserWidthFix: function(){
    if ($('body').hasClass('firefox') || $('body').hasClass('msie')){
      return $('#nav > li').length; // add 1px for each LI
    }
    return 0;
  },

  /**
   * Fits Callout fonts inside the individual Callout title wrappers
   */
  fitCalloutFonts: function(){
    var ctaHeadings = $('.cta-block h4 > a');
    if (!ctaHeadings.length) { return; }

    // set default callout font family
    if (!this.calloutFont.family.length){
      this.calloutFont.family = parseInt(ctaHeadings.first().css('font-family'));
    }

    // initialize callout font array
    if (!this.calloutFont.cur){
      this.calloutFont.cur = new Array();
      for(i = 0; i < ctaHeadings.length; i++){
        this.calloutFont.cur[i] = $(ctaHeadings[i]).css('font-size');
      }
    }

    // adjust each of the callout headings independently
    ctaHeadings.each(function(idx, elem){
      var fontSize = parseInt(this.calloutFont.cur[idx]);
      var cta = $(elem);

      // while callout height exceeds max height and font is greater than min, shrink font size
      if (this.calloutFont.height < cta.height()) {
        while (this.calloutFont.height < cta.height() && fontSize > this.calloutFont.min) {
          fontSize -= this.calloutFont.inc;
          cta.css('font-size', fontSize);
        }
      } else {
      // while callout height fits within max height and font is less than max, increase font size
        while (this.calloutFont.height >= cta.height() && fontSize < this.calloutFont.max) {
          fontSize += this.calloutFont.inc;
          cta.css('font-size', fontSize);
        }
        while (this.calloutFont.height < cta.height() && fontSize > this.calloutFont.min) {
          fontSize -= this.calloutFont.inc;
          cta.css('font-size', fontSize);
        }
      }

      // remember last font size for each CTA
      this.calloutFont.cur[idx] = fontSize;
    }.bind(this));
  },

  /**
   * Fits CTA fonts inside the individual CTA wrappers
   */
  fitCTAFonts: function(){
    if ($('body').hasClass('corp')){
      return this.fitCorpCTAFonts();
    }

    var ctas = $('.calls .ctas li > a');
    if (!ctas.length) { return; }

    // set default cta font family
    if (!this.ctaFont.family.length){
      this.ctaFont.family = ctas.first().css('font-family');
    }

    // initialize cta font array
    if (!this.ctaFont.cur){
      this.ctaFont.cur = new Array();
      for(i = 0; i < ctas.length; i++){
        this.ctaFont.cur[i] = parseInt($(ctas[i]).css('font-size'));
      }
    }

    // scale the font of each cta independently
    ctas.each(function(idx, elem){
      var cta = $(elem);
      this.fitCTASpanFonts(cta, cta.find('span:not(.arrow)'), this.ctaFont, idx);
    }.bind(this));
  },

  fitCTASpanFonts: function(cta, span, fontSettings, idx) {
    var fontSize = parseInt(fontSettings.cur[idx]);
    var hasSpace = (cta.text().indexOf(' ') !== -1);
    if (!hasSpace && cta.hasClass('long')) { 
      cta.removeClass('long'); 
    }
    // while cta height exceeds max height and font is greater than min, shrink font size
    if (fontSettings.height < cta.height() || cta.width() <= span.width()) {
      while ((fontSettings.height < cta.height() || cta.width () < span.width()) && fontSize > fontSettings.min) {
        if (!hasSpace || cta.hasClass('long')) {
          fontSize -= fontSettings.inc;
          cta.css('font-size', fontSize);
        } else {
          cta.addClass('long');
        }
      }
    } else {
    // while cta height fits within max height and font is less than max, increase font size
      while (fontSettings.height >= cta.height() && fontSize < fontSettings.max) {
        fontSize += fontSettings.inc;
        cta.css('font-size', fontSize);
      }
      while ((fontSettings.height < cta.height() || cta.width() <= span.width()) && fontSize > fontSettings.min) {
        fontSize -= fontSettings.inc;
        cta.css('font-size', fontSize);
      }
      if (fontSize === this.ctaFont.max && cta.hasClass('long')){
        cta.removeClass('long');
      }
      while ((fontSettings.height < cta.height() || cta.width() <= span.width()) && fontSize > fontSettings.min) {
        if (!hasSpace || cta.hasClass('long')){
          fontSize -= fontSettings.inc;
          cta.css('font-size', fontSize);
        } else {
          cta.addClass('long');
        }
      }
    }
    // remember last font size for each CTA
    fontSettings.cur[idx] = fontSize;
  },

  fitCorpCTAFonts: function(){
    var ctas = $('.calls li:not(.search)');
    var search = $('.calls li.search');
   
    if (ctas.length){
      // set default cta font family
      if (!this.ctaFont.family.length){
        this.ctaFont.family = ctas.first().css('font-family');
      }
      // initialize cta font array
      if (!this.ctaFont.cur){
        this.ctaFont.cur = new Array();
        for(i = 0; i < ctas.length; i++){
          this.ctaFont.cur[i] = parseInt($(ctas[i]).find('a span').css('font-size'));
        }
      }

      ctas.each(function(idx, elem){
        // resize top text
        var cta = $(elem);
        this.fitCTASpanFonts(cta.find('a'), cta.find('a span'), this.ctaFont, idx);
      }.bind(this));
    }
    
    if (search.length){
      var searchLabel = search.find('p');
      var searchLabelSpan = searchLabel.find('span');
      var searchInput = search.find('input');
      var searchButton = search.find('button');

      // set default search font family
      if (!this.searchFontCorp.family.length){
        this.searchFontCorp.family = search.css('font-family');
      }
      // initialize search font array
      if (!this.searchFontCorp.cur){
        this.searchFontCorp.cur = { label: 0, button: 0 };
        this.searchFontCorp.cur['label'] = parseInt(searchLabelSpan.css('font-size'));
      }

      //resize search label
      var fontSize = this.searchFontCorp.cur['label'];
      if (searchLabelSpan.width() > searchLabel.width()){
        while (searchLabelSpan.width() > searchLabel.width() && fontSize > this.searchFontCorp.min){
          fontSize -= this.searchFontCorp.inc;
          searchLabelSpan.css('font-size',fontSize);
        }
      } else {
        while (searchLabel.width() < searchLabel.width() && fontSize < this.searchFontCorp.max){
          fontSize += this.searchFontCorp.inc;
          searchLabel.css('font-size',fontSize);
        }
        while (searchLabel.width() > searchLabel.width() && fontSize > this.searchFontCorp.min){
          fontSize -= this.searchFontCorp.inc;
          searchLabel.css('font-size',fontSize);
        }
      }
      this.searchFontCorp.cur['label'] = fontSize;

      // adjust input to fit

      var adj = (Modernizr.mq('(max-width: 575px)')) ? 30 : 20;
      searchInput.css({width: search.width() - searchLabel.outerWidth(true) - searchButton.outerWidth() - adj});
    }
  },

  /** 
   * Changes the string formatting in the menu between desktop and tablet resolutions by adding/removing BR tags
   */
  changeNavBreakpoint: function(){
    if (this.isTabletDown()) {
      $('#nav li a.top-level').each(function(i){
        var htmlCleaned = $(this).html().replace(/<br\s?\/?>/, '<i> </i>');
        $(this).html(htmlCleaned);
      });
    } else {
      $('#nav li a.top-level').each(function(i){
        var htmlCleaned = $(this).html().replace('<i> </i>', '<br>');
        $(this).html(htmlCleaned);
      });
    };
  },

  /**
   * Applies "magic" classes to rows as row width responds to devices and resizing
   */
  adjustRowsForWindowWidth: function() {
    var wrapperWidth = $('.row_magic').width();
    if ( wrapperWidth > 630) $('.row_magic').removeClass('smaller').removeClass('medium').addClass('bigger');
    if (wrapperWidth <= 630 && wrapperWidth > 420) $('.row_magic').removeClass('bigger').removeClass('smaller').addClass('medium');
    if (wrapperWidth <= 420) $('.row_magic').removeClass('bigger').removeClass('medium').addClass('smaller');
  },

  /**
   * Strips borders from IMG tags wrapped in A tags
   */
  stripImgBorders: function(){
    $("a").has("img").css({"border": "0 none"});
  },

  /**
   * Applies fitVids plugin to responsive videos
   */
  responsiveVideos: function(){
    // Responsive video
    if ($(".responsive-video").length > 0){
      Modernizr.load([
        {
          // TODO: remove hardcode
          load: "/javascripts/fitvids.js",
          complete:function(){
            $(".responsive-video").fitVids();
          }
        }
      ]);
    }
  },

  /**
   * Wraps inner content LIs in SPAN tags
   */
  wrapContentLIs: function(){
    $('.content ul > li, .content ol > li').wrapInner('<span>');
  },

  /**
   * Initializes scroll-to-content links for leads and CTAs
   */
  initScrollToContent: function(){
    $('#nav a[href], .ctas a[href], .main a[href*="lead"]').scrollToContent({
      'scrollTo': '.content'
    });
  },

  /**
   * Sets search ZIP field to hide/show default value on focus/blur
   */
  initZipFocus: function(){
    $('#search').each(function() {
      var default_value = this.value;
      $(this).focus(function() {
          if(this.value == default_value) {
              this.value = '';
          }
      });
      $(this).blur(function() {
          if(this.value == '') {
              this.value = default_value;
          }
      });
    });
  },

  /**
   * Init floorplan modal reveal behavior
   */
  initFloorplanModal: function(){
    $(".floorplan-modal").click(function() {
      var data_url = $(this).attr('data');
      $("#floorPlanModal").reveal({
        open: function(){
          $("#floorPlanModal img").attr("src", data_url);
        }
      }
      );
    });
  },

  /**
   * Moves social icons responsively between desktop and tablet resolutions
   */
  moveSocial: function(){
    var socialIconLoc = $('.social.block').parent();
    if (this.isTabletDown() && $(".main .social.block").length > 0) {
      var socialBlock = $(".social.block").detach();
      $('.footer .footer-left').append(socialBlock);
    } else if(!this.isTabletDown() && $(".footer .social.block").length > 0) {
      var socialBlock = $(".social.block").detach();
      socialIconLoc.append(socialBlock);
    }
  },

  changeTabletDown: function(){
    this.tabletDown = this.isTabletDown();
  },

  /**
   * Moves CTAS responsively
   */
  moveCtas: function(){
    return (this.isStore()) ? this.locMoveCtas() : this.corpMoveCtas();
  },

  /**
   * Moves location CTAs responsively between desktop and tablet resolutions
   */
  locMoveCtas: function(){
    if (!this.isHome() || !this.isStore()){ return false; }
    
    if (this.isTabletDown() && !this.tabletDown){
      this.changeTabletDown();
      if ($('.cta-blocks').length > 0) {
        var ctaBlocks = $(".cta-blocks").detach();
        ctaBlocks.insertAfter('.content');
        $('.content').addClass('adjust-content');
        $(".cta-blocks").css("margin-top", "12px");
        return true;
      }
    } else if(!this.isTabletDown() && this.tabletDown) {
      this.changeTabletDown();
      if ($('.cta-blocks').length > 0) {
        var ctaBlocks = $(".cta-blocks").detach();
        ctaBlocks.insertBefore('.content');
        $('.content').removeClass('adjust-content');
        $(".cta-blocks").removeAttr('style');
        return true;
      }
    }
    return false;
  },

  /**
   * Moves corp CTAs responsively
   */
  corpMoveCtas: function(){
    if (!this.isHome() || !this.isCorp()){ return false; }
    
    if (this.isTabletDown() && !this.tabletDown) {
      this.changeTabletDown();
      if($('.cta-blocks').length > 0) {
        var ctaBlocks = $(".cta-blocks").detach();
        ctaBlocks.insertAfter('.welcome');
        $(".welcome").addClass('adjust-content');
        $(".cta-blocks").css("margin-top", "0");
        return true;
      }
    } else if(!this.isTabletDown() && this.tabletDown){
      this.changeTabletDown();
      if($('.cta-blocks').length > 0) {
        var ctaBlocks = $(".cta-blocks").detach();
        ctaBlocks.insertBefore('.welcome');
        $(".welcome").removeClass('adjust-content');
        $(".cta-blocks").removeAttr('style');
        return true;
      }
    }
    return false;
  },

  /**
   * Moves the callouts responsively
   */
  moveCalls: function(){
    if (this.isHome()){
      if (this.is575Down() && !this.mobileCalls) {
        this.mobileCalls = true;
        if($(".calls").length > 0) {
          var calls = $(".calls").detach();
          $('.main-wrapper .main').prepend(calls);
          return true;
        }
      } else if(!this.is575Down() && this.mobileCalls){
        this.mobileCalls = false;
        if($('.calls').length > 0) {
          var calls = $(".calls").detach();
          $('.main-wrapper').prepend(calls);
          return true;
        }
      }
    }
  },


  /**
   * Adds a HCARD to the footer if no sidebar
   */
  addHcardToFooter: function(){
    if ($('.sidebar').length <= 0){
      $('.footer-content .footer-left .vcard').css('display', 'block');
    }
  },

  /**
   * Prepares lead params if site is using device_lead_param CV
   */
  prepareLeadParams: function() {
    $('a[href*="/leads/"]').each(function(idx,elem){
      var touch = "?touch=" + this.isTouchDevice();
      var height = "&height=" + $(window).height();
      var width = "&width=" + $(window).width();
      var url = $(elem).attr("href").split("?")[0];
      $(elem).attr("href", url + touch + height + width);
    }.bind(this));
  },

  /**
   * Switches lead links to mobile if not using device_lead_param CV
   */
  switchToMobileLeads: function() {
    if(Modernizr.mq('all and (max-device-width: 768px)') && this.isTouchDevice()) {
      $('a[href*="/leads/"]').each(function(){
        url = this.href.split('/');
        url[4] = "mobile_" + url[4];
        this.href = url.join('/');
      });
    }
  },

  /**
   * Supresses Tel links on non-touch devices
   */
  suppressTelLink: function(){
    if (!this.isTouchDevice()){
      $('a[href^="tel"]').each(function(){
        $(this).addClass('no-click');
        $(this).click(function(e){
          return noEvent(e);
        });
      });
    }
  },

  /**
   * Hides/shows the Turn Social responsively
   */
  turnSocial: function() {
    if (this.isTabletDown() && !$.turnsocial_mobile) {
      // Hide TurnSocial toolbar below iPad portrait
      if ($('#ts').length) {
        $("#ts").hide();
      }
    } else {
      // Show TurnSocial toolbar iPad portrait and above
      if ($('#ts').length) {
        $("#ts").show();
      }
      else {
        if (!$.turnsocial_loaded) {
          $.turnsocial_loaded = true;
          $.getScript($.turnsocial_url);
        }
      }
    }
  },

  /**
   * Adjusts the positions of the CTAs relative to the slideshow responsively
   */
  positionCall: function(){
    if (!this.isHome()){ return; }

    var slideHeight = $("#slideshow").height();
    var $ctaBlocks = $(".main .cta-blocks");

    if (slideHeight > 0){
     
      var $mainWelcome = $(".main .welcome");
      var $mainContent = $(".main .content");
      var $sidebar = $('aside.sidebar');

      if (Modernizr.mq('(min-width: 1000px)') && $ctaBlocks.length > 0 ) {
        if (this.isCorp()){
          $ctaBlocks.css("margin-top", "-134px");
        } else {
          $ctaBlocks.css("margin-top", "-120px");
        }
      }
      else if (Modernizr.mq('(min-width: 1000px)') && $ctaBlocks.length === 0){
        if ($mainWelcome.length > 0){
          $mainWelcome.css("margin-top", "0px").addClass('solo');
        }
      }
      else if ($ctaBlocks.length > 0){
        $ctaBlocks.css("margin-top", "20px");
      }

      if ($ctaBlocks.length === 0 && $mainWelcome.length ===0){
        //var mainOffset = (Modernizr.mq('(max-width: 575px)')) ? 0 : Math.max(30, slideHeight);
        mainOffset = 0;
        if ($mainContent.length > 0){
          $mainContent.css("margin-top", mainOffset);
          if ($sidebar.length > 0){
            $sidebar.css("margin-top", mainOffset);
          }
        }
      }
    } else {
      $ctaBlocks.css("margin-top", "90px");
    }

    if (this.isCorp()){
      var corp_main_check = $(".corp.home .main .content");
      if( corp_main_check.children().length === 0){
        corp_main_check.addClass("empty");
      }
      
      $('.corp .row_magic .main').each(function() {
          if($(this).children().length === 0) {
             $(this).addClass("empty");
          }
      });
    }
  },

  /**
   * Initializies Galleria slideshow
   */
  initSlideshow: function(){
    if (typeof(Galleria) != 'undefined'){
      Galleria.on('loadfinish', function(e) {
       if(e.index == 0 && !this.slideshowLoadFinished){
          setTimeout(function(){
            this.positionCall();
            this.moveCtas();
          }.bind(this), 1);
          this.slideshowLoadFinished = true;
        }
      }.bind(this));
    }
  },

  /**
   * Gets all Vimeo and Youtube videos embedded on a page
   */
  getAllVideos: function(){
    return $("iframe[src^='http://player.vimeo.com'], iframe[src^='http://www.youtube.com']");
  },

  /**
   * Strips all YouTube and Vimeo IFRAMEs of their width/height attributes
   */
  initVideos: function(){
    var $allVideos = this.getAllVideos();
    // Figure out and save aspect ratio for each video
    $allVideos.each(function() {
      $(this).data('aspectRatio', $(this).height() / $(this).width()).removeAttr('height').removeAttr('width');
    });
    this.resizeVideos();
  },

  /**
   * Resizes all YouTube and Vimeo IFRAMES relative to their content row
   */
  resizeVideos: function(){
    var $allVideos = this.getAllVideos();
    var $fluidEl = $(".content"); // The element that is fluid width
    var newWidth = $fluidEl.width();
    // Resize all videos according to their own aspect ratio
    $allVideos.each(function() {
      $(this).width(newWidth).height(newWidth * $(this).data('aspectRatio'));
    });
  },

  /**
   * Debounces resize events so that we don't overload our memory with tons of font calculations
   * Borrowed from underscorejs.com
   */
  debounce: function(func, wait, immediate) {
    var timeout, args, context, timestamp, result;

    var later = function() {
      var last = (Date.now || new Date().getTime()) - timestamp;
      if (last < wait) {
        timeout = setTimeout(later, wait - last);
      } else {
        timeout = null;
        if (!immediate) {
          result = func.apply(context, args);
          context = args = null;
        }
      }
    };

    return function() {
      context = this;
      args = arguments;
      timestamp = (Date.now || new Date().getTime());
      var callNow = immediate && !timeout;
      if (!timeout) {
        timeout = setTimeout(later, wait);
      }
      if (callNow) {
        result = func.apply(context, args);
        context = args = null;
      }

      return result;
    };
  }

}; // END Skyline

// initialize Skyline once the doc is ready
$(document).ready(function(){ Skyline.init(); });

// adjust position after the window has finished loading
$(window).load(function() { Skyline.positionCall(); });

// need to call this on all resize events so that it doesn't feel too laggy or cause a race condition
$(window).on('resize orientationchange', function(e){ 
  if (!e.type == 'resize' || Skyline.fixChromeWindowWidth()){
    Skyline.adjustNavMenu();
    Skyline.moveCalls();
    Skyline.moveCtas();
    // hack to make debounce resize fire
    Skyline.winWidth = 0;
  }
});

// use debounce for more complex resizing functions (throttles firing of resize by 50ms)
var debounceResize = Skyline.debounce(function(e) { 
  if (Skyline.fixChromeWindowWidth()){
    Skyline.resize(Skyline);
  }
}, 50);
$(window).on('resize orientationchange', debounceResize);

/**
 * Adds scrollToContent jQuery plugin
 */
(function($) {
  $.fn.scrollToContent = function(options) {
    var settings = $.extend({
      'scrollTo': '.content',
      'scrollSpeed': 500,
      'runConditions': Modernizr.mq ? Modernizr.mq('all and (max-width: 480px)') && Modernizr.touch : true
    }, options);

    var pathname = window.location.href;
    if (pathname.indexOf("scrollto=true") >= 0){
      var offset = $(settings.scrollTo).offset().top;
      $('html, body').animate({
        scrollTop: offset
      }, settings.scrollSpeed);
    }

    if(settings.runConditions) {
      return this.each(function() {
        var $this = $(this);
        $this.attr("href", function(index, href) {
          var param = "scrollto=true";
          var match = href.match(/[?]/);
          var sep = match ? "&" : "?";
          return href + sep + param;
        });
      });
    }
  };
})(jQuery);

/** 
 * Squashes an event and prevents any further bubbling up the DOM
 *
 * @param       e     {Event}     DOM event
 * @return            {boolean}   false (ALWAYS!)
 */
function noEvent(e){
  if (e){
    e.preventDefault();
    e.stopPropagation();
  }
  return false;
}





