/**
 * Airbus JS scope declaration
 * Must be kept outside the closure
 */
//var Airbus = Airbus || {};
if (typeof Airbus === 'undefined') {
  var Airbus = {};
}    

(function($, Airbus){
var imagesPath = 'images/',
//var imagesPath = '/dotcom/www/images/',
is_mobile = false,
is_ipad = false,
is_touchable = false;

/**
 * Set the variable that indicates if JavaScript behaviors should be applied
 */
Airbus.jsEnabled = document.getElementsByTagName && document.createElement && document.createTextNode && document.documentElement && document.getElementById;
if (Airbus.jsEnabled) { document.body.className = document.body.className.replace("no-js","js"); }

/**
 * Main initialisation
 */
Airbus.init = function() {
  this.initDecodeLink(); // [!] must be first
  this.isTouchable();
  this.initWhatsNewCycle();
  this.initLocalScroll();
  this.initMegaMenu();
  this.initGotoButton();
  this.initUnitSwitcher();
  this.initBoxToggler();
  this.initMkSlider();
  this.initShareBox();
  this.initTertiaryNavActiveTrail();
  this.initOpenCloseBlock();
  this.initDLDrawer();
  this.initIconRollOver();
  this.initGlossaryTabs();
  this.initLocatorUI();
  this.initPhotoGallery();
  this.initLightBox();
};

/**
 * Touchable devices detection
 */
Airbus.isTouchable = function() {
  is_mobile = ($('.invisible', '#header-container').css('text-transform') == 'capitalize' || $('body').hasClass('ie')) ? false : true;
  is_ipad = (navigator.platform.indexOf('iPad') !== -1) ? true : false;
  is_iphone = (navigator.platform.indexOf('iPhone') !== -1) ? true : false;
  is_ipod = (navigator.platform.indexOf('iPod') !== -1) ? true : false;
  //is_touchable = is_mobile || is_ipad || is_iphone || is_ipod;
  is_touchable = is_ipad || is_iphone || is_ipod;
};

/**
 * Parse a JSON response.
 *
 * The result is either the JSON object, or an object with 'status' 0 and 'data' an error message.
 */
Airbus.parseJson = function(data) {
  if ((data.substring(0, 1) !== '{') && (data.substring(0, 1) !== '[')) {
    return { status: 0, data: data.length ? data : 'Unspecified error' };
  }
  return eval('('+data+')');
};

/**
 * jQuery UI & own M icons rollover
 */
Airbus.initIconRollOver = function() {
  $('.ui-state-default').hover(
    function() { $(this).addClass('ui-state-hover'); }, 
    function() { $(this).removeClass('ui-state-hover'); }
  );
  $('.m-icon').hover(
    function() { $(this).addClass('m-icon-hover'); }, 
    function() { $(this).removeClass('m-icon-hover'); }
  );
};

/**
 * Tertiary nav active trail
 */
Airbus.initTertiaryNavActiveTrail = function() {
  try {
    var nt = $('#nav-tertiary');
    if (nt.length > 0) {
      nt.css({position:'relative'});
      var r = parseInt(nt.parent().css('padding-right'),10),
          ao = $('.active', '#nav-tertiary').offset(),
          no = nt.offset(),
          t = parseInt(ao.top-no.top,10);
      $('<span id="nav-tertiary-active-trail" class="m-icon m-icon-active-trail"></span>').
        css({
          margin: '4px 0 0 0',
          position: 'absolute',
          right: '-'+r+'px',
          top: t+'px'
        }).
        hide().
        appendTo('#nav-tertiary').
        fadeIn(2000);
      $('#nav-tertiary li a').hover(
        function() {
          var co = $(this).offset(),
              tt = parseInt(co.top-no.top,10);
          $('#nav-tertiary-active-trail').stop().animate({top: tt+'px'}, 300);
        },
        function() {
          $('#nav-tertiary-active-trail').stop().animate({top: t+'px'}, 300);
        }
      );
    }
  }
  catch(err) {}
  finally {}
};

/**
 * LocalScroll initialisation
 */
Airbus.initLocalScroll = function() {
  if ($.localScroll) {
    $.localScroll.defaults.easing = 'easeOutQuad';
    $.localScroll.hash({
        target: 'body',
        queue: true,
        duration: 500
      });
    $.localScroll({
      target: 'body',
      queue: true,
      duration: 500,
      hash: true,
      onBefore:function(e, anchor, $target){},
      onAfter:function(anchor, settings){}
    });
  }
};

/**
 * MegaMenu initialisation
 */
Airbus.initMegaMenu = function() {
  if ($.fn.megaMenu) {
    $('#primary-nav-a, #primary-nav-b').megaMenu({'openEvent':(!is_touchable ? 'mouseenter' : 'touch')});
    $('.mega-item-switcher li:first-child a:first-child').addClass('active');
    $('.mega-item-switcher').localScroll({
      target: '.panels',
      queue: true,
      duration: 500,
      hash: false,
      event: 'mouseover',
      onBefore:function(e, anchor, $target){
        $('.mega-item-switcher li a').removeClass('active');
        $(e.currentTarget).addClass('active');
      },
      onAfter:function(anchor, settings){}
    });
    $('.mega-item-switcher li a').unbind('click').bind('click', function(e) {
      e.preventDefault();
      if (!is_touchable) {
        if (this.rel) {
          window.location = this.rel;
        } else {
          switch (this.hash) {
            case '#passengeraircraft':
              window.location = '/aircraftfamilies/passengeraircraft/';
              break;
            case '#corporate':
              window.location = '/aircraftfamilies/corporate/';
              break;
            case '#freighter':
              window.location = '/aircraftfamilies/freighter/';
              break;
            case '#military_aircraft':
              window.location = '/aircraftfamilies/military-aircraft/';
              break;
            case '#out_of_production':
              window.location = '/aircraftfamilies/out-of-production/';
              break;
          } 
        }
      }
      return false;
    });
  }
};

/**
 * MkSlider initialisation
 */
Airbus.initMkSlider = function() {
  if ($.fn.mkSlider) {
    $('#hp-focusbox').mkSlider();
  }
};

/**
 * UnitSwitcher initialisation
 */
Airbus.initUnitSwitcher = function() {
  if ($.fn.unitSwitcher) {
    $('#key-figures, #details', '#technical-specifications').unitSwitcher();
  }
};

/**
 * Goto button UI initialisation
 */
Airbus.initGotoButton = function() {
  if ($.fn.button) {
    $('.goto.top').button({
      icons: { primary: "ui-icon-arrowthickstop-1-n" }
    });
    $('.goto.bottom').button({
      icons: { primary: "ui-icon-arrowthickstop-1-s" }
    });
  }
};

/**
 * Glossary tabs UI initialisation
 */
Airbus.initGlossaryTabs = function() {
  if ($.fn.tabs) {
    $("#tabs-glossary").tabs();
    var tpl = '<form class="tab-switcher-buttons" id="tab-switcher-buttons-glossary" action="" method="get">'
             +'<span><input type="radio" id="sw-list-glossary" name="sw-glossary[]" value="list" />'
             +'<label for="sw-list-glossary">All</label>'
             +'<input type="radio" id="sw-tab-glossary" name="sw-glossary[]" value="tab" checked="checked" />'
             +'<label for="sw-tab-glossary">By letter tab</label></span>'
             +'</form>';
    $(tpl).prependTo('#tabs-glossary');
    $('#tab-switcher-buttons-glossary input[type=radio]').click(function(e) {
      $(this).parent().submit();
    });
    $('#tab-switcher-buttons-glossary').submit(function(){
      var res = $(this).serializeArray();
      $.each(res, function(i, field){
        if (field.value === 'list') {
          $("#tabs-glossary").tabs('destroy');
        } else if (field.value === 'tab') {
          $("#tabs-glossary").tabs();
        }
      });
      return false;
    });
    if ($.fn.buttonset) {
      $('#tab-switcher-buttons-glossary span').buttonset();
      $('#tab-switcher-buttons-glossary').css({
        position: 'absolute',
        top: '-35px',
        right: '0'
      });
    }
    $(".letter:first", "#tabs-glossary").css("margin-right", 0);
    $(".goto:last", "#tabs-glossary").css("display", "none");  
  }
};

/**
 * Toggler initialisation
 */
Airbus.initBoxToggler = function() {
  if ($.fn.boxToggler) {
    $('#hp-newsbox').boxToggler();
  }
};

/**
 * What's new cycle initialisation
 */
Airbus.initWhatsNewCycle = function() {
  if ($.fn.cycle) {
    $('#hp-whatsnewbox .content ul').cycle({
        fx: 'fade',
        timeout: 5000,
        easing:'easeInOutQuart',
        pauseOnPagerHover: true
    })
    .hover(
      function() { 
        $(this).cycle('pause'); 
      }, 
      function() { 
        $(this).cycle('resume'); 
      }
    );
  }
};

/**
 * Share box initialisation
 */
Airbus.initShareBox = function() {
  if ($.fn.shareBox) {
    var s = $('a.share');
    if (s.length > 0) {
      //this.initFB();
      //this.initTW();
      s.shareBox();
    }
  }
};

/**
 * Lightbox initialisation
 */
Airbus.initLightBox = function() {
  if ($.fn.colorbox) {
    
    $(".lightbox").colorbox({
      initialWidth:100,
      initialHeight:100,
      rel:'nofollow',
      slideshow:false,
      opacity:"0.85",
      innerHeight:function(){},
      close:"close"
    });

    $(".slideshow").colorbox({
      initialWidth:100,
      initialHeight:100,
      current:"Image {current} of {total}",
      slideshow:true,
      arrowKey:true,
      rel:'slideshow',
      opacity:"0.85",
      transition:"elastic",
      speed:350,
      previous:"previous",
      next:"next",
      close:"close"
    });
    
    $(".slideshow-inline").colorbox({
      slideshowSpeed:10000,
      initialWidth:100,
      initialHeight:100,
      current:"Image {current} of {total}",
      slideshow:true,
      arrowKey:true,
      rel:'slideshow-inline',
      inline: true,
      href:function(){ return '#'+$(this).attr('rev'); },
      innerWidth:function(){ $('#'+$(this).attr('rev')).width(); },
      innerHeight:function(){ $('#'+$(this).attr('rev')).height(); },
      title:function(){ return '<span style="display:none;">'+$('#'+$(this).attr('title'))+'</span>'; },
      opacity:"0.85",
      transition:"elastic",
      speed:350,
      previous:"previous",
      next:"next",
      close:"close"
    });
    
  }
};

/**
 * open/close block
 */
Airbus.initOpenCloseBlock = function() {
  var openCloseBlock = {
    init : function() {
      $(".togglable.section .header").addClass('ui-state-focus');
      $(".togglable .content").each(function(){
        var $togglable = ($(this).next().is('.footer') ?
                         $(this).add($(this).next())
                         : $(this)),
            $header = $(".header", $togglable.parent());
        if (!$(this).hasClass('closed')) {
          $togglable.wrapAll('<div class="opened"></div>');
          $header.append('<span class="ui-icon ui-icon-squaresmall-minus"></span>');
        } else {
          $togglable.wrapAll('<div class="closed"></div>').removeClass('closed');
          $header.append('<span class="ui-icon ui-icon-squaresmall-plus"></span>');
        }
        $header.css('position', 'relative').find('.ui-icon').css({
          position: 'absolute',
          top: '10px',
          right: '10px',
          marginRight: 0,
          paddingRight: 0
        });
      });
      openCloseBlock.bindClick();
    },
    toggleIcon : function(ctx) {
      var $this = $('.ui-icon', ctx);
      if ($this.hasClass('ui-icon-squaresmall-plus')) {
        $this.
          removeClass('ui-icon-squaresmall-plus').
          addClass('ui-icon-squaresmall-minus');
      } else {
        $this.
          removeClass('ui-icon-squaresmall-minus').
          addClass('ui-icon-squaresmall-plus');
      }
    },
    bindClick : function() {
      $( ".togglable .header" ).css({cursor:'pointer'}).click(function(){
        var $togglable = $('.content', $(this).parent()).parent();
        if ($togglable.hasClass('opened')) {
          $togglable.slideUp('fast', 'linear', function(){
            openCloseBlock.toggleIcon($(this).parent());
            $(this).
              removeClass('opened').
              addClass('closed');
          });
        } else {
          $togglable.slideDown('fast', 'linear', function(){
            openCloseBlock.toggleIcon($(this).parent());
            $(this).
              removeClass('closed').
              addClass('opened');
          });
        }
        return false;  
      });
    }
  };
  openCloseBlock.init();
};

/**
 * Make downloads items collapsible
 */
Airbus.initDLDrawer = function() {
  $('#page-safety_lib0 .ddl_title a, #page-presskits .ddl_title a').prepend('<span class="ui-icon ui-icon-squaresmall-plus"></span>').click(function(e){
    e.preventDefault();
    $(this).parent().next().children('.ddl_file_description, .ddl_file_list').slideToggle('fast', function() {
      $(this).is(':hidden') ? 
        $(this).parent().parent().find('.ui-icon').removeClass('ui-icon-squaresmall-minus').addClass('ui-icon-squaresmall-plus')
        : $(this).parent().parent().find('.ui-icon').removeClass('ui-icon-squaresmall-plus').addClass('ui-icon-squaresmall-minus');
    });
  });
};

/**
 * Facebook js SDK loading
 */
Airbus.initFB = function() {
  var AFB = {
    init: function() {
      $('body').append('<div id="fb-root"/>');
      var lang = AFB.getLang();
      (function() {
        var e = document.createElement('script'); e.async = true;
        e.src = document.location.protocol + '//connect.facebook.net/'+lang+'/all.js#xfbml=1';
        document.getElementById('fb-root').appendChild(e);
      }());
      window.fbAsyncInit = function() {
        FB.init({appId: '178026238881308', status: true, cookie: true, xfbml: true});
      };
    },
    getLang: function() {
       var lang = navigator.language /* Mozilla */ || navigator.userLanguage /* IE */ || 'en_US' /* fallback */;
       if (lang.length < 5) {
         switch (lang) {
           case 'fr':
             lang = 'fr_FR';
             break;
           default:
             lang = 'en_US';
         }
       }
      return lang;
    }
  };
  if (typeof(FB) === 'undefined') { AFB.init(); }
};

/**
 * Twitter js API loading
 */
Airbus.initTW = function() {
  var ATW = {
    init: function() {
      $('body').append('<div id="tw-root"/>');
      (function() {
        var e = document.createElement('script');
        e.src = 'http://platform.twitter.com/widgets.js';
        document.getElementById('tw-root').appendChild(e);
      }());
    }
  };
  if (typeof(twttr) === 'undefined') { ATW.init(); }
};

/**
 * Locator map buttonset initialisation
 */
Airbus.initLocatorUI = function() {
  var 
    locatorButton = $('#primary-nav-item-worldwide a.menu-item-link, a.open-worldwide'),
    locatorLoader = '<div class="loader" style="display: none;text-align:center;width:500px;padding-top:100px;margin:0 auto;"><h2><img src="'+imagesPath+'loader-4f5f75.gif" alt="" style="vertical-align:middle;" />&nbsp;&nbsp;loading map&hellip;</h2></div>',
    locatorMethods = {
      init: function() {
        if ($("#tx_locatorairbus_drawer").length > 0) {
          this.onReady();
        } else {
          this.mkContainer();
          this.bindOpening();
        }
      },
      bindOpening: function() {
        locatorButton.
          unbind().
          bind('click', function(e){
            e.preventDefault();
            locatorButton.addClass('active');
            $("#live").slideDown('fast', function(){
              $('.loader', this).fadeIn('fast', function(){
                locatorMethods.bindClosing();
              });
              locatorMethods.performQuery();
            });
            $("#splash-assets").fadeOut('fast');
        });
      },
      bindClosing: function() {
        locatorButton.
          add('.ui-icon-circle-close', '#live').
          unbind().
          bind('click', function(e){
            e.preventDefault();
            $("#live").slideUp('slow', function(){
              $("#live-container .content").html(locatorLoader);
              locatorMethods.bindOpening();
              locatorButton.removeClass('active');
              $("#splash-assets").fadeIn('fast');
            });
        });
      },
      mkContainer: function() {
        $('#header').
          after('<div id="live" style="display:none;z-index:243;margin-top:'+($('#breadcrumb').height()||0)+'px;"><div id="live-container" class="-c24 clearfix" style="height:557px;position:relative;background-color:#fff;"><div class="content" style="padding: 30px 40px;">'+locatorLoader+'</div><span class="ui-icon ui-icon-circle-close" style="position: absolute; bottom:1em;right:1em;">Close</span></div></div>');
      },
      performQuery: function() {
        $.ajax({
          url: locatorButton.attr('href'),
          cache: true,
          dataType: "html",
          data: "type=300",
          success: function(html){
            $("#live-container .content").html(html);
            locatorMethods.onReady();
          }
        });
      },
      onReady: function() {
        $("#tx_locatorairbus_drawer").
          find('.header').button({
            icons: {
              primary: "ui-icon-gear"
            }
          }).
          end().
          bind('mouseenter', function(){
            $('.tx_locatorairbus_categoriesarbo').slideDown('fast');
          }).
          bind('mouseleave', function(){
            $('.tx_locatorairbus_categoriesarbo').slideUp();
          });
      }
    };
  locatorMethods.init();
};

/**
 * Encrypted links parsing initialisation
 */
Airbus.initDecodeLink = function() {
  if ($.fn.decodeLink) {
    $('.conciergerie').decodeLink();
  }
}

/**
 * Photo gallery class
 */
Airbus.initPhotoGallery = function() {
  
  var APG = {

    init: function(){
      if ($('#gallery-wrapper').length == 0) {
        return;
      } else {
        $('body').addClass('wide');
        $('#page').addClass('soft');
        if ($('#gallery-item-placeholder').length == 0) {
          $('<div />', {'id':'gallery-item-overlay'}).css({
            'position': 'fixed',
            'left': 0,
            'top': 0,
            'width':'100%',
            'height':'100%',
            'overflow': 'hidden',
            'z-index': 13996
          }).hide().appendTo('body');
          $('<div />', {'id':'gallery-item-placeholder'}).css({
            'position': 'fixed',
            'left': 0,
            'top': 0,
            'width':'100%',
            'height':'100%',
            'background-color': 'transparent',
            'overflow': 'hidden',
            'z-index': 13997
          }).hide().appendTo('body');
          $('<div />', {'id':'gallery-item-placeholder-container', 'class':'black'}).css({
            'position': 'absolute',
            'left': 0,
            'top': 0,
            'overflow': 'hidden'
          }).appendTo('#gallery-item-placeholder');
        }
        APG.depagify();
        APG.process();
        APG.openFromUrl();
      }
    },
    
    openFromUrl: function() {
      if (Airbus.openItem) {
        var elementToOpen = $('a:[href*="'+Airbus.openItem+'"]', '#gallery-wrapper').eq(0);
        if (elementToOpen.length > 0) {
          elementToOpen.trigger('click');
          delete Airbus.openItem, elementToOpen;
        } else {
          $(document).scrollTo('#footer');
        }
      }
    },

    depagify: function(){
      if ($.fn.depagify && $('.pagination .next').length > 0 && 1==1) {
        var a=1, t=false;
        $('ul.list:first', '#gallery-wrapper')
          .before('<div id="page-1" class="page-separator clearfix"><h2>Page '+a+'</h2></div>')
          .wrap('<div />');
        $('.pagination:first a.next', '#gallery-wrapper').depagify({
          container: '#gallery-wrapper',
          filter: 'ul.list',
          trigger: function(e) {
            var w = $(window),
            progress = w.scrollTop() + w.height(),
            threshold = $('#footer').offset().top;
            return (progress >= threshold && (t || a==1)) ? true : false;
          },
          request: function(options) {
            var m = this.get(0).search.match(/\d+/g);
            a = m ? m[0] : (a+1);
            t=false;
            $(options.container).append('<div id="page-'+a+'" class="page-separator loader clearfix"><strong>Loading page '+a+'&hellip;</strong></div>');
          },
          success: function(event, options) {
            $('.loader', options.container)
              .removeClass('loader')
              .find('strong').remove().end()
              .html('<h2>Page '+a+'</h2>&nbsp;<a href="javascript:" onclick="document.location.hash=\'#page\'" class="ui-state-default ui-corner-all"><span class="ui-icon ui-icon-arrowthickstop-1-n"></span></a><a href="javascript:" onclick="document.location.hash=\'#page-'+(a-1)+'\'" class="ui-state-default ui-corner-all"><span class="ui-icon ui-icon-arrowthick-1-n"></span></a>');
            Airbus.initLocalScroll();
            APG.process();
            APG.openFromUrl();
          },
          effect: function() {
            var $this = $(this),
            $lis = $this.find('ul.list li');
            $lis.hide();
            $this.slideDown('slow', function(){
              (function showNext(jq){
                jq.eq(0).fadeIn("fast", function(){
                  (jq=jq.slice(1)).length && showNext(jq);
                  if (jq.length==0) {t=true;}
                });
              })($lis);
            });
          }
        });
        $('.pagination').remove();
      }
    },
    
    process: function() {
      APG.overFx();
      APG.bindItemOpening();
      //APG.enlargeThumbs();
      APG.onWindowResize();
    },
    
    overFx: function() {
      if ($.fn.hoverIntent) {
        $('ul.list li:not(.overed) .item-container .thumb-link', '#gallery-wrapper').hover(
          function(){ 
            $(this).addClass('dropshadow');
          },
          function(){
            $(this).removeClass('dropshadow');
          }
        ).closest('li').addClass('overed');
      }
    },
    
    enlargeThumbs: function() {
      var actions = {
        over: function() {
          //log('OVER', this, arguments);
          var $this = $(this),
          $this_large = $this.find('.item-container-large'),
          initialLeft = parseInt($this_large.css("left"),10),
          initialTop = parseInt($this_large.css("top"),10);
          
          //$this.css({'overflow': 'visible'}).removeClass('dropshadow');
          $this.removeClass('dropshadow');
          
          $this_large.css('display', 'block').animate(
            {
              width: ($this.width()+20),
              height: ($this.height()+20),
              top: '-10px',
              left: '-10px'
            }, 
            { 
              duration: 100, 
              easing: 'linear', 
              complete: function(){
                //log('COMPLETE', this, arguments);
                //$('.description-link', this).slideDown('fast');
              },
              step: function(now, fx){
                if (fx.prop == "height") {
                  //$('.description-link', this).css('top', $(this).height()+'px');
                }
              }
            }
          )
          .find('.thumb-link img').animate(
            {
              'margin-top': 0,
              'margin-left': 0
            },
            { 
              duration: 100, 
              easing: 'linear'
            }
          );
          
        },
        out: function() {
          //log('OUT', this, arguments);
          var $this = $(this),
          $this_large = $this.find('.item-container-large');
          
          //$('.description-link', $this_large).slideUp('fast', function(){
            
            $this_large.animate({
              width: $this.width(),
              height: $this.height(),
              top: '0',
              left: '0'
            }, 200, 'easeInQuart', function(){ 
              //$(this).css('display','none');
              $(this).fadeOut('fast');
              //$this.css({'overflow': 'hidden'});
            })
            .find('.thumb-link img').animate(
              {
                'margin-top': '-10px',
                'margin-left': '-10px'
              },
              { 
                duration: 200, 
                easing: 'easeInQuart'
              }
            );  
            
          //});
          
        }
      },
      hoverFn = 'hover',
      args = [actions.over, actions.out],
      e = $('ul.list li:not(.enlarged)', '#gallery-wrapper');
      
      e.css({
        'position': 'relative'
      })
      .each(function(){
        $('.item-container', this).css({
          'position': 'relative'
        }).clone()
          .css({
            'display': 'none',
            'position': 'absolute',
            'top': 0,
            'left': 0,
            'z-index': 2,
            'width': $('.item-container', this).width(),
            'height': $('.item-container', this).height()
          })
          .addClass('item-container-large')
          .removeClass('item-container')
          .appendTo($('.item-container', this));
          
        //log(this, arguments);
        //$(this).append($('<div />', {'class': 'large-thumb dropshadow2'})
        //.css({
        //  //'display': 'none',
        //  'position': 'absolute',
        //  'top': 0,
        //  'left': 0,
        //  'z-index': 2,
        //  'width': $(this).width(),
        //  'height': $(this).height(),
        //  'background-color':'red'
        //})
        //.html($(this).html()));
        //find('.description-link').addClass('dropshadow2 ui-corner-bl ui-corner-br').css('display','none');
      })
      .addClass('enlarged');

      if ($.fn.hoverIntent) {
        hoverFn = 'hoverIntent';
        args = [{
          over: actions.over,
          timeout: 500,
          out: actions.out,
          sensitivity: 7,
          interval: 300
        }];
      }
      $('.item-container', e)[hoverFn].apply($('.item-container', e), args);
      
    },

    onWindowResize: function() {

      $(window).resize(function(){

        if (APG.opened) { 
          
          var $tmpimg, $fragment, mode, mode_param, endW, endH, imgW, imgH, fw, tw, docW;
          
          $placeholder_container = $('#gallery-item-placeholder-container');
          $tmpimg = $('#tmpbigimg', $placeholder_container);
          $fragment = $('.main-section', $placeholder_container);
          docW = document.documentElement.clientWidth;
          
          //$('body').css('width', '100%');
                $('body').css('width', docW);
          
          mode = 'fit'; 
          mode_param = null;
          //mode = 'fix';
          //mode_param = {'height': 623, 'width': 880};
          //mode = 'percent';
          //mode_param = 90;
          
          imgW = $tmpimg.width();
          imgH = $tmpimg.height();
          
          if (mode==='fit') {
            endW = imgW;
            endH = imgH;
          }
          if (mode==='fix') {
            endW = mode_param.width;
            endH = mode_param.height;
          }
          if (mode==='percent') {
            endW = Math.round(docW*mode_param/100);
            endH = Math.round(docW*mode_param/100);
          }
          endX = Math.round((docW - endW)/2);
          endY = Math.round((docW - endH)/2);
          
          fw = endW;
          tw = endW;
          
          if (docW > 1300) {
            tw = Math.round(docW*90/100);
            if (docW > 1500) {
              tw = Math.round(docW*83/100);
            }
            if (docW > 1700) {
              tw = Math.round(docW*75/100);
            }
            fw = tw-endW-((parseInt($fragment.css('padding-left'), 10)+parseInt($fragment.css('padding-right'), 10)));
            if (fw > 500-((parseInt($fragment.css('padding-left'), 10)+parseInt($fragment.css('padding-right'), 10)))) {
              fw = 500-((parseInt($fragment.css('padding-left'), 10)+parseInt($fragment.css('padding-right'), 10)));
              //tw = tw-(fw-500);
              tw = imgW + 500;
              //log('1 limit fragment width : ', fw, tw);
            }
            $fragment.removeClass('black').css({'float': 'left', 'display': 'inline', 'width': fw, 'position': 'relative', 'left': 'auto', 'right': 'auto', 'top': 'auto', 'bottom': 'auto'});
            $tmpimg.css({'float': 'left'});
          } 
          else {
            fw = endW-((parseInt($fragment.css('padding-left'), 10)+parseInt($fragment.css('padding-right'), 10)));
            $fragment.addClass('black').css({'width': fw, 'position': 'absolute', 'left': 0, 'bottom': 0});
          }
          
          $('#gallery-item-placeholder-container').clearQueue();

          APG.positionPlaceholder(tw, $fragment, endW);
          
          // update coordinates
          var itemData, $item_container, top, left, gapX, gapY, startX, startY;

          itemData = $('#gallery-item-placeholder-container').data('itemData');
          $item_container = itemData.current;
          top = $(window).scrollTop(),
          left = $(window).scrollLeft(),
          gapY = top>0 ? top : 0;
          gapX = left>0 ? left : 0;
          startX = Math.round($item_container.find('.thumb-link img').offset().left-gapX);
          startY = Math.round($item_container.find('.thumb-link img').offset().top-gapY);
          
          itemData.CSSorigin.top = startY;
          itemData.CSSorigin.left = startX;
          itemData.scrollX = left;
          itemData.scrollY = top;
          
          $('#gallery-item-placeholder-container').data('itemData', itemData);

        } else {
          return false;          
        }
      });
      
    },

    opened: false,
    isOpening: false,
    currentHref: '',
    
    positionPlaceholder: function(tw, $fragment, endW) {
      
      var docW = document.documentElement.clientWidth, 
      $parent = $('#gallery-item-placeholder-toggler', '#gallery-item-placeholder-container'), 
      parentH, 
      toggled = false;

      if (docW < 1300) {

        $fragment.removeClass('black').css({
          'position':'static',
          'left':'auto',
          'top':'auto',
          'right':'auto',
          'bottom':'auto',
          'text-align':'left'
        });

        if ($parent.length == 0) {
          $parent = $('<div />', {'id': 'gallery-item-placeholder-toggler', 'class':'black'}).css({
            'width':'100%',
            'position':'absolute',
            'bottom':0,
            'left':0,
            'text-align':'center',
            'overflow':'hidden'
          });
          $fragment.wrap($parent);
        }
        $parent = $('#gallery-item-placeholder-toggler', '#gallery-item-placeholder-container');

        parentH = $fragment.height() + ((parseInt($fragment.css('padding-top'), 10)+parseInt($fragment.css('padding-bottom'), 10)));

        if ($parent.children('.toggler').size()==0) {
          $parent.prepend('<a class="toggler" style="display:inline;"><span class="ui-icon ui-icon-carat-1-n"></span></a>');
        }

        $parent.bind('mouseenter', function(){
          if (!toggled) {
            toggled=true;
            $(this).animate({height:parentH}, 'fast', 'linear', function(){
              $('.toggler span', this).removeClass('ui-icon-carat-1-n').addClass('ui-icon-carat-1-s');
              $fragment.fadeIn('slow', function(){
                //toggled=true;
              });
            });
          }
        });
        $fragment.bind('mouseleave', function(){
          if (toggled) {
            toggled=false;
            $fragment.fadeOut('slow', function(){
              $(this).parent().animate({height: '20px'}, 'fast', 'linear', function(){
                //toggled=false;
                $('.toggler span', $(this).parent()).removeClass('ui-icon-carat-1-s').addClass('ui-icon-carat-1-n');
              });
            });
          }
        });
      } else {
        if ($parent.length > 0) {
          $('.toggler', $parent).remove();
          $fragment.unwrap().unbind();
        }
      }
      $('.ui-icon', $fragment).parent().parent().addClass('fresh');
      
      
      $('#gallery-item-placeholder-container').animate({
        width:tw
      },
      {
        duration: 400,
        easing: 'linear',
        complete: function() {
          $fragment.fadeIn('slow', function() {
            if (docW < 1300) {
              toggled=true;
              $fragment.delay(600).trigger('mouseleave');
            }
          });
        },
        step: function(now, fx) {
          if (fx.prop === "width") {
            var l = Math.round((docW-now)/2);
            l = l < 0 ? 0 : l;
            $(this).css('left', l);
          }
        }
      });
      
      
    },

    openItem: function($item_container, $tmpimg, $fragment, $pager) {
      var endW, endH, endX, endY, imgW, imgH,
      itemData = $('#gallery-item-placeholder-container').data('itemData'),
      startW = itemData.CSSorigin.width,
      startH = itemData.CSSorigin.height,
      $prev, $next; 

      $tmpimg = $('#tmpbigimg');

      imgW = $tmpimg.removeAttr('width').width();
      imgH = $tmpimg.removeAttr('height').height();

      $("<img/>") // Make in memory copy of image to avoid css issues
      .attr("src", $tmpimg.attr("src"))
      .load(function() {
        imgW = this.width;   // Note: $(this).width() will not
        imgH = this.height; // work for in memory images.

        //log('tpmimg w ', imgW, ' h ', imgH, $tmpimg);

        $tmpimg.detach().css({'width':startW, 'height':startH, 'visibility': 'visible'});

        var mode, mode_param;
        mode = 'fit'; 
        mode_param = null;
        //mode = 'fix';
        //mode_param = {'height': 623, 'width': 880};
        //mode = 'percent';
        //mode_param = 90;
        if (mode==='fit') {
          endW = imgW;
          endH = imgH;
        }
        if (mode==='fix') {
          endW = mode_param.width;
          endH = mode_param.height;
        }
        if (mode==='percent') {
          endW = Math.round(document.documentElement.clientWidth*mode_param/100);
          endH = Math.round(document.documentElement.clientHeight*mode_param/100);
        }
        endX = Math.round((document.documentElement.clientWidth - endW)/2);
        endY = Math.round((document.documentElement.clientHeight - endH)/2);
      
        // Previous
        $pager_prev = $pager.filter('a.page-previous');
        $prev = itemData.previous;
        if ($prev.length > 0) {
          $pager_prev.bind('click', {'a':$prev.find('a.thumb-link')}, APG.bindPreviousTransition);
          $pager_prev.attr('href', $prev.find('a.thumb-link').attr('href'));
        } else {
          $pager_prev.remove();
        }
      
        // Next
        $pager_next = $pager.filter('a.page-next');
        $next = itemData.next;
        if ($next.length > 0) {
          $pager_next.bind('click', {'a':$next.find('a.thumb-link')}, APG.bindNextTransition);
          $pager_next.attr('href', $next.find('a.thumb-link').attr('href'));
        } else {
          $pager_next.remove();
        }
        
        $('a.download, a.permalink', $fragment).bind('click', function(e){
          e.preventDefault();
          window.location = this.href;
        });
      
        // Up
        $pager_up = $pager.filter('a.page-up');
        if ($pager_up.length > 0) {
          $pager_up.bind('click', APG.closeItem)
          .html('<span class="ui-icon ui-icon-circle-close"></span>&nbsp;Close');
        }
        //log('$pager : ', $pager, ' $pager_prev : ', $pager_prev, '$pager_next : ', $pager_next);

        //
        $('#gallery-item-placeholder-container').append($tmpimg).append($fragment);
        var fw = 300, tw = endW;
        if (document.documentElement.clientWidth > 1300) {
          tw = Math.round(document.documentElement.clientWidth*90/100);
          if (document.documentElement.clientWidth > 1500) {
            tw = Math.round(document.documentElement.clientWidth*83/100);
          }
          if (document.documentElement.clientWidth > 1700) {
            tw = Math.round(document.documentElement.clientWidth*75/100);
          }
          fw = tw-endW-((parseInt($fragment.css('padding-left'), 10)+parseInt($fragment.css('padding-right'), 10)));
          if (fw > 500-((parseInt($fragment.css('padding-left'), 10)+parseInt($fragment.css('padding-right'), 10)))) {
            fw = 500-((parseInt($fragment.css('padding-left'), 10)+parseInt($fragment.css('padding-right'), 10)));
            //tw = tw-(fw-500);
            tw = imgW + 500;
            //log('2 limit fragment width : ', fw, tw);
          }
          $fragment.css({'float': 'left', 'display': 'inline', 'width': fw});
          $tmpimg.css({'float': 'left'});
        } else {
          fw = endW-((parseInt($fragment.css('padding-left'), 10)+parseInt($fragment.css('padding-right'), 10)));
          $fragment.addClass('black').css({'width': fw, 'position': 'absolute', 'left': 0, 'bottom': 0});
        }
        $fragment.hide();
        
        var itemData2 = {
          'CSSimgZoomOnly': {
            'width': endW,
            'height': endH,
            'top': endY,
            'left': endX
          },
          'CSStotalZoom': {
            'width': tw,
            'height': endH
          },
        };
        $.extend($('#gallery-item-placeholder-container').data('itemData'), itemData2);

        $('.loader', $item_container).fadeOut('fast', function() {
        
          $(this).remove();
        
          $('img', $item_container).fadeTo('fast', 1, function() {
          
            $('#gallery-item-placeholder').fadeIn('fast', function() {
            
              $tmpimg.animate({
                  width: endW,
                  height: endH
                }, 600, 'easeInOutQuart', function() {}
              );
            
              $('#gallery-item-placeholder-container').animate({
                  width: endW,
                  height: endH,
                  top: endY,
                  left: endX
                }, 600, 'easeInOutQuart', function() { 
                  $('#gallery-item-overlay').fadeTo('slow', 0.9);
                  APG.positionPlaceholder(tw, $fragment, endW);
                  Airbus.initShareBox();
                  APG.opened = true;
                }
              );
            });
          });
        });
      
      }); // end img.load
      
    },
    
    closeItem: function() {
      var callback = arguments[0] || null;
      if (APG.opened) {
        var itemData = $('#gallery-item-placeholder-container').data('itemData');
        //log(itemData);
        $('#gallery-item-overlay').fadeOut('fast');
        $('#gallery-item-placeholder-container, #gallery-item-placeholder-container img').animate(itemData.CSSorigin, 600, 'easeInOutQuart', function(){ 
            $('html').css('width', '100%').css('overflow', 'auto').scrollTop(itemData.scrollY).scrollLeft(itemData.scrollX);
            $('body').css('width', '100%');
            $('#gallery-item-placeholder').fadeOut('slow', function(){
              $('#gallery-item-placeholder').hide();
              $('#gallery-item-placeholder-container').empty();
              APG.opened = false;
              document.location.hash = '';
              $('html').scrollTop(itemData.scrollY).scrollLeft(itemData.scrollX);
              //var location = new String(document.location);
              //document.location = location.slice(0, location.lastIndexOf('#'));
              APG.currentHref = '';
              if (callback) {
                if (typeof APG[callback] === 'function' && (callback === 'openPrevious' || callback === 'openNext')) {
                  APG[callback].apply();
                }
              }
            });
          }
        );
        
      }
      delete callback;
      return false;
    },
    
    bindPreviousTransition: function() {
      APG.closeItem('openPrevious');
      return false;
    },
    
    bindNextTransition: function() {
      APG.closeItem('openNext');
      return false;
    },

    openPrevious: function() {
      var $previous = $('#gallery-item-placeholder-container').data('itemData').previous.find('a.thumb-link').eq(0);
      //log('previous', $previous);
      $previous.trigger('click', ['openPrevious']);
      delete $previous;
      return false;
    },    

    openNext: function() {
      var $next = $('#gallery-item-placeholder-container').data('itemData').next.find('a.thumb-link').eq(0);
      //log('next', $next);
      $next.trigger('click', ['openNext']);
      delete $next;
      return false;
    },
    
    bindItemOpening: function() {
      
      $(document).bind('keypress', function(e) {
        // Enable close with esc
        if (e.keyCode == 27) {
          APG.closeItem();
        }
      });
      
      $('#gallery-item-placeholder:not(.processed)').bind('click', APG.closeItem).addClass('processed');
      $('#gallery-item-placeholder-container').unbind('click').bind('click', function(e){ e.preventDefault(); return false; });
      
      $("a.thumb-link, a.description-link, a.zoom-in", '#gallery-wrapper').unbind('click').live('click', function(e, ctx) {
        
        e.preventDefault();
        
        if (APG.opened || APG.isOpening) { 
          return false; 
        }
        
        if (ctx && (ctx==='openPrevious' || ctx==='openNext')) {
          e.stopPropagation();
        }
        
        var $this = $(this), 
        itemData = {'CSSorigin':{}, 'previous':{}, 'next':{}},
        previous, next,
        $item_container = $this.closest('.item-container'),
        $url = $this.attr('href'),
        startW = $item_container.find('.thumb-link img').width(), 
        startH = $item_container.find('.thumb-link img').height(),
        startX, startY, gapX, gapY,
        top = $(window).scrollTop(),
        left = $(window).scrollLeft(),
        docW = document.documentElement.clientWidth,
        imgW, imgH;
        
        $.ajax({
          type: 'GET',
          url: $url,
          cache: true,
          //data: ({xhr: 1}),
          dataType: 'html',
          async: true,
          beforeSend: function() {
            
            $('body').css('width', docW);
            $('html').css('overflow', 'hidden').scrollTop(top).scrollLeft(left);
            
            $item_container.css('position', 'relative').find('img').fadeTo('slow', 0.25);
            
            if ($('.loader', $item_container).length==0) {
              (function(){
                $('<span/>', { 
                  'class': 'loader', 
                  'style': 'display: block; position: absolute; top: '+($item_container.find('.thumb-link').height()-startH)+'px; left: 0; width: 100%; height: '+startH+'px; background-position: center center;'
                }).hide().prependTo($item_container).fadeIn('slow');
              })(); 
            }
            
            gapY = top>0 ? top : 0;
            gapX = left>0 ? left : 0;
            startX = Math.round($item_container.find('.thumb-link img').offset().left-gapX);
            startY = Math.round($item_container.find('.thumb-link img').offset().top-gapY);
            previous = $item_container.parent().prev('li');
            next = $item_container.parent().next('li');
            
            itemData = {
              'CSSorigin': {
                'width': startW,
                'height': startH,
                'top': startY,
                'left': startX
              },
              'scrollX': left,
              'scrollY': top,
              'current': $item_container,
              'previous': previous,
              'next': next
            };
            $('#gallery-item-placeholder-container').css(itemData.CSSorigin).removeData('itemData').data('itemData', itemData);
            
            APG.isOpening = true;
          },
          success: function(data) {
            
            var 
            $fragment = $(data).find('#main-section'),
            $bigimg = $fragment.find('.photo').detach(), 
            $tmpimg = $bigimg.find('img').clone(),
            $pager = $('a.page-previous, a.page-next, a.page-up', $fragment);

            imgW = null;
            imgH = null;
            $tmpimg.css('visibility', 'hidden').appendTo('body').attr('id', 'tmpbigimg');
            
            $fragment.attr('id', null).addClass('main-section');
            $fragment.find('#content-tools').attr('id', null).addClass('content-tools');
            
            APG.isOpening = false;
            APG.currentHref = this.url;
            document.location.hash = 'open='+encodeURIComponent(APG.currentHref);
            APG.openItem($item_container, $tmpimg, $fragment, $pager);

          } // end success
        });
        
        return false;
        
      });

    }, // end bindItemOpening
    
  };
  
  APG.init();
  
};

window.log = function(){
  log.history = log.history || [];   // store logs to an array for reference
  log.history.push(arguments);
  if(this.console){
    console.log( Array.prototype.slice.call(arguments) );
  }
};

googlize = function(){
	var listA;
	listA = $('.googlize');
	if (listA.length>0)
	{
		for (var i=0; i<listA.length; i++)
		{
			var tmplien = $(listA[i]).html();
			if (tmplien.indexOf('<img')>-1)
			{
				tmplien = $(listA[i+1]).html();
			}
			var type = tmplien.substr( (tmplien.lastIndexOf('.') +1) );
			$(listA[i]).bind('click', {t:type, l:tmplien}, function(event){
			recordOutboundLink(this, event.data.t, event.data.l);return false;})
		}
	}
}; 

recordOutboundLink = function(link, category, opt_label) {
  try {
	_gaq.push(['_trackEvent', category, 'download', opt_label]);
    setTimeout('document.location = "' + link.href + '"', 100)
  }catch(err){}
};

/**
 * Run scripts
 */
$(document).ready(function(){
  if (Airbus.jsEnabled) {
    Airbus.init();
    googlize();
  }
});

})(jQuery, Airbus);

