// Fix device-width scalability crossbrowser
// https://gist.github.com/901295
// By @mathias, @cheeaun and @jdalton
(function(doc) {

  var addEvent = 'addEventListener',
      type = 'gesturestart',
      qsa = 'querySelectorAll',
      scales = [1, 1],
      meta = qsa in doc ? doc[qsa]('meta[name=viewport]') : [];

  function fix() {
    meta.content = 'width=device-width,minimum-scale=' + scales[0] + ',maximum-scale=' + scales[1];
    doc.removeEventListener(type, fix, true);
  }

  if ((meta = meta[meta.length - 1]) && addEvent in doc) {
    fix();
    scales = [.25, 1.6];
    doc[addEvent](type, fix, true);
  }

}(document));
;
/**
 * jQuery Plugin to obtain touch gestures from iPhone, iPod Touch and iPad, should also work with Android mobile phones (not tested yet!)
 * Common usage: wipe images (left and right to show the previous or next image)
 * 
 * @author Andreas Waltl, netCU Internetagentur (http://www.netcu.de)
 * @version 1.1.1 (9th December 2010) - fix bug (older IE's had problems)
 * @version 1.1 (1st September 2010) - support wipe up and wipe down
 * @version 1.0 (15th July 2010)
 */
(function($){$.fn.touchwipe=function(settings){var config={min_move_x:20,min_move_y:20,wipeLeft:function(){},wipeRight:function(){},wipeUp:function(){},wipeDown:function(){},preventDefaultEvents:true};if(settings)$.extend(config,settings);this.each(function(){var startX;var startY;var isMoving=false;function cancelTouch(){this.removeEventListener('touchmove',onTouchMove);startX=null;isMoving=false}function onTouchMove(e){if(config.preventDefaultEvents){e.preventDefault()}if(isMoving){var x=e.touches[0].pageX;var y=e.touches[0].pageY;var dx=startX-x;var dy=startY-y;if(Math.abs(dx)>=config.min_move_x){cancelTouch();if(dx>0){config.wipeLeft()}else{config.wipeRight()}}else if(Math.abs(dy)>=config.min_move_y){cancelTouch();if(dy>0){config.wipeDown()}else{config.wipeUp()}}}}function onTouchStart(e){if(e.touches.length==1){startX=e.touches[0].pageX;startY=e.touches[0].pageY;isMoving=true;this.addEventListener('touchmove',onTouchMove,false)}}if('ontouchstart'in document.documentElement){this.addEventListener('touchstart',onTouchStart,false)}});return this}})(jQuery);;
/**
* hoverIntent r6 // 2011.02.26 // jQuery 1.5.1+
* <http://cherne.net/brian/resources/jquery.hoverIntent.html>
* 
* @param  f  onMouseOver function || An object with configuration options
* @param  g  onMouseOut function  || Nothing (use configuration options object)
* @author    Brian Cherne brian(at)cherne(dot)net
*/
(function($){$.fn.hoverIntent=function(f,g){var cfg={sensitivity:7,interval:100,timeout:0};cfg=$.extend(cfg,g?{over:f,out:g}:f);var cX,cY,pX,pY;var track=function(ev){cX=ev.pageX;cY=ev.pageY};var compare=function(ev,ob){ob.hoverIntent_t=clearTimeout(ob.hoverIntent_t);if((Math.abs(pX-cX)+Math.abs(pY-cY))<cfg.sensitivity){$(ob).unbind("mousemove",track);ob.hoverIntent_s=1;return cfg.over.apply(ob,[ev])}else{pX=cX;pY=cY;ob.hoverIntent_t=setTimeout(function(){compare(ev,ob)},cfg.interval)}};var delay=function(ev,ob){ob.hoverIntent_t=clearTimeout(ob.hoverIntent_t);ob.hoverIntent_s=0;return cfg.out.apply(ob,[ev])};var handleHover=function(e){var ev=jQuery.extend({},e);var ob=this;if(ob.hoverIntent_t){ob.hoverIntent_t=clearTimeout(ob.hoverIntent_t)}if(e.type=="mouseenter"){pX=ev.pageX;pY=ev.pageY;$(ob).bind("mousemove",track);if(ob.hoverIntent_s!=1){ob.hoverIntent_t=setTimeout(function(){compare(ev,ob)},cfg.interval)}}else{$(ob).unbind("mousemove",track);if(ob.hoverIntent_s==1){ob.hoverIntent_t=setTimeout(function(){delay(ev,ob)},cfg.timeout)}}};return this.bind('mouseenter',handleHover).bind('mouseleave',handleHover)}})(jQuery);;
/**
 * Usage:
 *
 * $('slideshow').cycleEnhanced({
 *  'keyNext': 'right',
 *  'keyPrev': 'left',
 *  'swipe': true
 *  'fnNext': function() {
 *    $(this).cycle("next");
 *  },
 *  'fnPrev': function() {
 *    $(this).cycle("prev");
 *  }
 * });
 */
(function($, doc){
  $.cycleEnhanced = function(el, options){
    var base = this;

    // Access to jQuery and DOM versions of element
    base.$el = $(el);
    base.el = el;

    // Add a reverse reference to the DOM object
    base.$el.data("cycleEnhanced", base);

    base.init = function() {
      var i, key;

      base.options = $.extend({},$.cycleEnhanced.defaultOptions, options);

      // Replace key strings with char codes
      for(key in keys) {
        if (base.options[key]) {
          base.options[key] = map[base.options[key]] || base.options[key].toUpperCase().charCodeAt(0);
        }
      }


      // Enable swipe events
      if (base.options.swipe) {
        base.$el.touchwipe({
          wipeLeft: function() { base.options.fnNext.apply(base.$el, arguments); },
          wipeRight: function() { base.options.fnPrev.apply(base.$el, arguments); },
          preventDefaultEvents: base.options.preventDefaultEvents,
          min_move_x: base.options.min_move_x,
          min_move_y: base.options.min_move_y
        });
      }
      
      // Enable keypress events 
      if (base.options.keyNext || base.options.keyPrev) {
        $(doc).bind("keydown", base.keypress);
      }
    };

    base.keypress = function(event) {

      // Iterate over allowed key functions
      for (var key in keys) {

        // This was the key pressed
        if (event.which === base.options[key]) {

          // Call the appropiate function
          base.options[keys[key]].apply(base.$el);
        }
      }
    };

    // Map of keycodes
    var map = {
          'left': 37,
          'right': 39,
          'up': 38,
          'down': 40,
          'tab': 9,
          'space': 32,
          'enter': 13
        },

        // Allowed key handlers
        keys = {'keyNext': 'fnNext', 'keyPrev': 'fnPrev'};


    // Run initializer
    base.init();
  };

  $.cycleEnhanced.defaultOptions = {
    'keyNext': null,
    'keyPrev': null,
    'min_move_x': 20,
    'min_move_y': 20,
    'swipe': true,
    'fnNext': function() {
      $(this).cycle("next");
    },
    'fnPrev': function() {
      $(this).cycle("prev");
    },
    'preventDefaultEvents' : true
  };

  $.fn.cycleEnhanced = function(options){
    return this.each(function(){
      (new $.cycleEnhanced(this, options));

    });
  };

})(jQuery, document);
;

(function($){

  Drupal.base = Drupal.base || {};

  Drupal.behaviors.base = {
    attach: function(context, settings) {

      $(window).bind('hashchange', Drupal.base.scrollFragment);
      Drupal.base.scrollFragment();

      // In case of fragment link change so not to use browser-scroll
      $(context).delegate('a', 'mousedown', Drupal.base.changeFragment);

      // Hover effect for attracs suits
      //$(context).delegate(".node-suits.node-teaser, .node-employee", "hover", Drupal.base.animateCaption);
      $(".node-suits.node-teaser, .node-employee", context).hoverIntent({
        over : function() {
          $(this).find('.caption, .figcaption').slideDown('fast');
        },
        out : function() {
          $(this).find('.caption, .figcaption').slideUp('fast');
        },
        timeout : 0,
        sensitivity: 1,
        interval: 10
      });

      // Close button for messages
      new Drupal.base.message('.messages > ul > li', {
        duration: 400
      }, $(context).find('#messages'));

      // Close functionality for form validation errors
      $(context).delegate("label.error", "click", Drupal.base.message.close);

      // Enable touch and keyboard events for cycle slideshows
      for (var slideshow in Drupal.settings.viewsSlideshowCycle) {
        new Drupal.base.cycleEnhanced({
          slideshow: Drupal.settings.viewsSlideshowCycle[slideshow],
          keysEnable : false
        }, context);
      }

      // Recalculate slideshow on orientation change
      $(window).bind('orientationchange', function() {
        for (var slideshow in Drupal.settings.viewsSlideshowCycle) {
          var $slideshow = $(slideshow),
              $slider = $slideshow.children('ul'),
              $slide = $slideshow.find('li:visible .node'),
              width = $slide.width(),
              height = $slide.height();

          $slider.width(width)
            .height(height);

          var settings = Drupal.settings.viewsSlideshowCycle[slideshow];
          Drupal.settings.viewsSlideshowCycle[slideshow].loaded = false;
          //$(settings.targetId).cycle('destroy').cycle(settings.opts);
          Drupal.viewsSlideshowCycle.load(slideshow);

        }
      });

      // Close colorbox if the background is touched, UX
      $(context).delegate('#cboxOverlay', 'touchstart', Drupal.base.colorboxClose);

    }
  };

  Drupal.base.scrollFragment = function() {
    if (window.location.hash.substring(0,2) == '#.') {
      var id = window.location.hash.substring(2),
        offset = 200;

      $('html, body').animate({
        scrollTop: $("#"+ id).offset().top - offset
      }, 'slow');        
    }
  }
  
  Drupal.base.changeFragment = function(e) {
    var href = this.href.replace(/#([^\.]+)$/, "#.$1");
    if (href !== this.href) {
      this.href = href;
    }
  }

  Drupal.base.animateCaption = function(e) {
    e.stopPropagation();
    var $this = $(this);
    
    $this.find('.caption, .figcaption')
      .not(':animated')
      .slideToggle('fast');

    /*switch (e.type) {
      case 'mouseenter':
        $this.find('figcaption, .figcaption')
          .stop()
          .slideDown('fast');
        break;
      case 'mouseleave':
        $this.find('figcaption, .figcaption')
          .stop()
          .slideUp('fast');
        break;
    }*/
  }

  Drupal.base.colorbox = function(context) {
    $('#cboxContent', context).cycleEnhanced({
      'keyNext': null,
      'keyPrev': null,
      'swipe': true,
      'fnNext': function() {
        $.colorbox.next();
      },
      'fnPrev': function() {
        $.colorbox.prev();
      }
    });
  }

  Drupal.base.colorboxClose = function() {
    $.colorbox.close();
  };
  
  // Close button for Drupal messages
  Drupal.base.message = function(selector, settings, context) {
    var $button = $("<a>×</a>").attr({
      href : '#',
      title : Drupal.t('Close'),
      'class' : 'close'
    });

    $(selector, context).prepend($button);
    context.delegate(selector + " .close", "click", this.close);
  };

  // Remove the alert box
  Drupal.base.message.prototype.close = Drupal.base.message.close = function(e) {
    e.preventDefault();
    $this = $(this).hasClass('close') ? $(this).parent('li') : $(this);
    
    $this.animate({
      opacity: 0
    }, 400, function() {
      if ($this.siblings().length) {
        $this.remove();
      } else {
        $('#messages').remove();
      }
    });
  };

  // Enable cycleEnhanced and attach listeners
  Drupal.base.cycleEnhanced = function(options, context) {
    var $slideshow = $(options.slideshow.id_prefix + options.slideshow.slideshowId, context);

    // The slides contain multiple items, rearrange them so they fit in one row
    if ($slideshow.find('ul.slides > li:first').children().length > 0) {
      this.multipleItems(options.slideshow, $slideshow);
    }

    $slideshow.cycleEnhanced({
      'keyNext': options.keysEnable ? 'right' : null,
      'keyPrev': options.keysEnable ? 'left' : null,
      'swipe': true,
      'min_move_x' : 10,
      'fnNext': function(e) {
        if ($slideshow.children().filter(':animated').length === 0) {
          Drupal.viewsSlideshow.action({
            'action' : "nextSlide",
            'slideshowID' : options.slideshow.slideshowId
          });
        }
      },
      'fnPrev': function(e) {
        if ($slideshow.children().filter(':animated').length === 0) {
          Drupal.viewsSlideshow.action({
            'action' : "previousSlide",
            'slideshowID' : options.slideshow.slideshowId
          });
        }
      },
      'preventDefaultEvents' : false
    });
  };

  Drupal.base.cycleEnhanced.prototype.multipleItems = function(options, context) {
    var $slides = $('ul.slides > li', context),
        $items = $slides.eq(0).children(),

        slide_width = $slides.eq(0).width();
    
    // The items fit
    if (slide_width - ($items.eq(0).width() * $items.length) >= 0) {
      return;
    }
    
    // Loop through all slides live
    for (var idx = 0, $this; ($this = $('ul.slides > li').eq(idx)) && $this.length; idx++) {
      var $items = $this.children(),
          item_width = $items.eq(0).width(),
          item_count = $items.length,
          difference = slide_width - (item_width * item_count);

      // The items do not fit within the slide
      if (difference < 0) {
        var remove_count = Math.ceil(Math.abs(difference) / item_width),
            $next_slide = $slides.eq(idx + 1);

        // The next slide doesn't exist, create it
        if (!$next_slide.length) {
            $('ul.slides').append(
                $("<li/>").attr('id', options.div_prefix.slice(1) + options.slideshowId + '_' + (idx + 1))
            );
            $next_slide = $('ul.slides > li').eq(idx + 1);
        }

        // Move the items that wont fit to the next slide
        $items.filter(':gt(' + (item_count - remove_count - 1) + ')')
            .prependTo($next_slide);
      }
    }
  }

  // Attach touch events when a new colorbox has been bound
  $(document).bind('cbox_complete', function() {
    Drupal.base.colorbox($('#cboxWrapper'));
  });
})(jQuery);


;

