/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    Sitewide and Public Functions (Responsive)
  ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/

smartoffice = (function ($) {
  'use strict';

  var E  = {}, /* set an object to streamline all DOM elements */
      fn = {}, /* set an object to streamline all functions */
      jsFolder = '/themes/javascript/compressed/jquery/plugins/', /* The path to the JS folder */
      size = {
        /* in base.scss we can calculate
           ( $column-width + $gutter-width ) * $tablet ) - $gutter-width
           if normal values [480,768,1024] aren't good for site's design */
        'mobile'  : 480, /* 480 = iPhone4s height (width on landscape) */
        'tablet'  : 704, /* 768 = iPad width in portrait */
        'desktop' : 944 /* 1024 = ipad width in landscape and desktop */
      },
      device;

/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/ 
// Set up contextual regions for quicker selection/searching later   
  fn.initializeVars = function () {
      E.header      = $('header[role="banner"]');
      E.mainNav     = $('nav.main');
      E.subNav      = $('nav.subnav');
      E.mainContent = $('#main-content');
      E.footer      = $('footer[role="contentinfo"]');
  };

/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/ 
/* get device based on responsive size
   you can test against "device" variable in any function
   DEPENDENCIES - global vars "size" and "device"
 */
  fn.getDevice = function () {
    var runCheck = function () {
          if ( ($(window).width() >= size['mobile'] && $(window).width() <= size['tablet']) || $(window).width() < size['mobile']) {
            device = 'mobile'
          }
          if ( $(window).width()  > size['tablet'] && $(window).width() <= size['desktop'] ) {
            device = 'tablet'
          }
          if ( $(window).width() >= size['desktop'] ) {
            device = 'desktop'
          }
        };
    runCheck();
    $(window).resize( function () {
      runCheck();
    });
  }

/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
// A test function to show load success and give color swatches if you want
  fn.testFunction = function () {
      if (window.console) {
          console.log('Nailed it! The custom javascript is loaded!');
          console.log('You can remove "fn.testFunction()" from line 115 of the custom js file.');
          console.log('Then you can call it whenever you want by following the example on lines 100-107.')
          console.log('To see the base swatches add "<div class=\"color-test\"></div> to your page.') 
      };
      if ($('div.color-test').length) {
        if (window.console) {
          console.log('Oh! I see you\'ve done that! Nice work!');
        };
        var ctx = $('div.color-test'),
            S   = [
                    '<p>Swatch One (.swatch-one)</p>',
                    '<div class="swatch-one',
                    '">&nbsp</div>',
                    '<p>Swatch Two (.swatch-two)</p>',
                    '<div class="swatch-two'
                  ],
            content = [];
        content.push(S[0] + S[1] + S[2]);
        for (var i = 1; i < 10; i++) {
          content.push(S[1] + '-' + i + S[2])
        };
        content.push(S[3] + S[4] + S[2]);
        for (var i = 1; i < 10; i++) {
          content.push(S[4] + '-' + i + S[2])
        };
        ctx.append(content);
      };
      if (window.console) {
        console.log('Device:' + device);
        $(window).resize( function () {
          console.log('Device:' + device);
        })
        console.log('Remove these console.logs or the whole testFunction when satisfied.')
      }
  };

/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
  fn.mobileSideNav = function () {
    var body        = $('body'),
        openButton  = $('a.open-navigation', E.header),
        closeButton = $('a.close-navigation', E.header),
        makeMobile  = function () {
          if (device != 'mobile') {
            //tablet/desktop 
            $('html').removeClass('js-ready');
            if ($('div.wrapper', E.mainNav).length == 0) {
              E.mainNav.wrapInner('<div class="wrapper"></div>');
            };
            $('div.mobile-wrapper, div.mobile-wrapper > *').unwrap();
          };
          if (device == 'mobile') {
            //mobile
            $('html').addClass('js-ready');
            $('div.wrapper > ul', E.mainNav).unwrap();
            if ($('div.mobile-outer-wrapper').length == 0) {
              body.wrapInner('<div class="mobile-outer-wrapper"><div class="mobile-wrapper">');
            };
          };
        };

    makeMobile();

    $(window).resize(function() {
      makeMobile();
    })

    openButton.add(closeButton).on('click', function (e) {
      e.preventDefault();
      $('html').toggleClass('js-nav');
    });

  };

/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
/* Load appropriately sized images from data-mobile|data-tablet|data-desktop attributes.
   Triggered by class="responsive" on <img>.
     <img
       class="responsive"
       alt="XXXXXXX"
       src="[path to mobile - for best result, use mobile as default]"
       data-mobile ="[path to mobile]"
       data-tablet ="[path to tablet]"
       data-desktop="[path to desktop]">
   DEPENDECIES - fn.getDevice();
 */
  fn.responsiveImageSize = function () {
    var responsiveImage = $('img.responsive'),
        getImage = function () {
          responsiveImage.each(function () {
            var image = $(this),
                src  = image.data(device);
            $(this).attr('src', src);
          });
        };
     getImage();
     $(window).resize(function () {
       getImage();
     });
  };

/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
  fn.loadCycle = function () {
    var scriptURL = jsFolder + 'jquery.cycle2.min.js';
    if ($('.slideshow:visible')) {
      $.getScript(scriptURL)
        .done(function () {
          $('.slideshow').cycle({
                            log : false,
                         slides : '> div.slide',
                       // paused : true,
                   pauseOnHover : true,
                          speed : 600,
                          pager : '> div.pager',
                  pagerTemplate : '<span>&emsp;</span>',
               pagerActiveClass : 'current'
           });
        })
        .fail(function () {
          if (window.console) {
            console.log(scriptURL + ' didn\'t load');
          }
        });
    };
  };

/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
  fn.runFancyBox = function () {
    // calling jquery.fancybox.pack.js and jquery.fancybox-media.js in head
    if ($('a.fancybox').length) {
      $('.fancybox').fancybox({
        helpers : {
          media : {}
        },
        afterShow : function () {
          $('.fancybox-overlay').addClass('no-underline');
        }
      });
    };
  };

/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
  fn.showMoreInfo = function (q,a,remove) {
    //call like this:
    //siteName.showMoreInfo('.q-selector', '.a-selector', [true|false]);
    //q == what you click
    //a == what gets revealed
    //remove == BOOLEAN remove q?
    //DEPENDENCY: fn.hideMoreInfo

    var clickMe = $(q);

    clickMe.addClass('trigger').next(a).addClass('drawer').hide().end().parent('.entry, .main-text, section').addClass('fn_showMoreInfo');

    clickMe.on('click', function (e) {
      var ctx     = $(this).parent('.entry, .main-text, section'),
          trigger = $(this),
          drawer  = $(this).next(a, ctx);

      e.preventDefault();

      if (!ctx.hasClass('open')) {

        if (remove) {
          trigger.slideUp();
        }

        drawer.slideDown();

        if (!remove) {
          drawer.append('<a class="close button"><i class="fa fa-close"></i>&ensp;Close</a>');
          ctx.addClass('open');
        }

        fn.hideMoreInfo();

      };
    });

  }

/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
  fn.hideMoreInfo = function () {
    $('.fn_showMoreInfo.open a.close').on('click', function () {
      var ctx     = $(this).parents('.fn_showMoreInfo.open'),
          trigger = $(this),
          drawer  = $('.drawer', ctx);
      drawer.slideUp();
      ctx.removeClass('open');
      trigger.remove();
    });
  }

  return {
    /*-----------------------------*
      set Public APIs that can be
      called on any page using
      <script type="text/javascript">
        $(document).ready(function(){
          'use strict';
          smartoffice.testFunction();
        });
      </script>
      -----------------------------*/
    testFunction : fn.testFunction,
    showMoreInfo : fn.showMoreInfo,

    init : function () {
    /*-----------------------------*
      these always run
      -----------------------------*/
      fn.initializeVars();
      fn.getDevice();
      fn.mobileSideNav();
      fn.responsiveImageSize();
      fn.loadCycle();
      // fn.loadTestimonial();
      fn.runFancyBox();
    }
  }
})(jQuery);

/*-----------------------------------*
  When DOM is loaded, call the functions in "init" section
  -----------------------------------*/
$(document).ready(function(){
  'use strict';
  smartoffice.init();
});
