function pop(e) {
  e.stopPropagation();
  e.preventDefault();
  window.open(this.href);
}
function vimeoVideo(video) {
  document.getElementById('video-stage').innerHTML = window.unescape(video.html);
}
function inlineVimeoVideo(video) {
  var links = document.getElementsByTagName('a'),
      container = document.createElement('div'),
      id, match;
  for (var i = 0; i < links.length; i++) {
    if(links[i].href.indexOf('vimeo') > 0) {
      match = links[i].href.match(/vimeo.com\/(\d+)/);
      if(match[1] == video.video_id) {
        $(links[i]).insertBefore(container);
        $(container).css('width', video.width+'px');
        $(container).css('height', video.height+'px');
        container.innerHTML = window.unescape(video.html);
        $(container).insertBefore(links[i]);
        $(links[i]).remove();
      }
    }
  }
}

$(function(){

  var state,
      state2,
      home = {
        series: {
          evolution: 0,
          inspiration: 1,
          one: 2,
          classic: 3,
          lara: 4
        },
        current: 'one',
        currentSeries: 'one',
        nextSeries: null
      };

  $('body').addClass('js-active');

  $('a.share').click(pop);

  function resizeBG() {
    if($('#bg').length) {
      $('#bg').css({'width':$(window).width(),'height':$(document).height()});  
    }
    if($.browser.msie && $(document).width() < 1016 
        || !$.browser.msie && $(document).width() < 995) {
      $('#left,#right').hide();
    } else {
      $('#left,#right').show().css({
        'height': $(document).height(),
        'width': $.browser.msie ? ($(document).width()-1016)/2 : ($(document).width()-995)/2,
        'display': 'block'
      });
    }
    $('ul.preview li').css({
      'right': 0-(($(document).width()-995)/2),
      'width': ($(document).width()-995)/2
    });
    $('ul.preview li.left').css({
      'left': 0-(($(document).width()-995)/2),
      'width': ($(document).width()-995)/2
    });
  }

  /** 
  * Adjust the news items to a 2-column layout
  */
  // var toCols = $('body.home #content article');
  // if(toCols.length) {
  //   var els = [];
  //   for (var i=0; i < toCols.length; i++) {
  //     els.push(toCols[i].cloneNode(true));
  //   };
  //   $('#content article').remove();
  //   $('#content').append('<div></div><div></div><div class="last"></div>');
  //   $('#content').addClass('cols');
  //   var cols = $('#content div'),
  //       col = 0;
  //   for (var i=0; i < els.length; i++) {
  //     $(cols[col]).append(els[i]);
  //     col++;
  //     if(col > 2) {
  //       col = 0;
  //     }
  //   };
  // }

  /**
  * All Pages
  */
  if($.browser.msie && $.browser.version < 8) { $('body').addClass('ie'); }

  /**
  * Company
  */

  if($('body').hasClass('company')) {

    $('.company.js-active #wrapper article').hide();
    var headlines = $('.company.js-active #wrapper article h1');
    var menu = $('#wrapper').append('<ul id="secondary"></ul>');
    for (var i=0; i < headlines.length; i++) {
      $('#secondary').append('<li class="'+$(headlines[i]).parents('article').get(0).id+'">'+$(headlines[i]).html()+'</li>');
    };

    $('#secondary li').click(function(e) {
      var el = $('#'+$(this).attr('class'));
      if($(el).is(':visible')) {
        $(el).hide().removeClass('active');
      } else {
        $('.company.js-active #wrapper article').removeClass('selected');
        $(el).show().addClass('selected active');
      }
    });

    if($('body').hasClass('newsletter')) {
      $('#newsletter').addClass('selected').show();
    }

    /*
    * Add close button
    */
    $('article').append('<a href="#" class="close">Close</a>');
    $('article .close').click(function(e) {
      $(this).parent().hide();
    });

    /*
    * Set default content on hashtag
    */
    if(window.location.hash && window.location.hash.length > 1) {
      var article = $('#'+window.location.hash.slice(1));
      if(article.length) {
        $(article).addClass('selected active').show();
      }
    }

    /**
    * Make company articles draggable
    */
    $('.company.js-active #wrapper article').draggable({
      start: function() {
        // $.cookie('wiggled', 'yes', { expires: 365, path: '/' });
        // $(this).wiggle('stop');
        // $(this).data('wiggled', true);
      }
    });
    $('.company.js-active #wrapper article').mouseover(function(e) {
      // if(!$(this).data('wiggled') && $.cookie('wiggled') != 'yes') {
      //   $(this).wiggle('start');
      // }
    });
    $('.company.js-active #wrapper article').mouseout(function(e) {
      // if($(this).wiggle('isWiggling')) {
      //   $(this).wiggle('stop');
      // }
    });
    $('.company.js-active #wrapper article').mousedown(function(e) {
      $('.company.js-active #wrapper article').removeClass('selected');
      $(this).addClass('selected');
    });

    /**
    * Pagination in company videos
    */
    $('.company.js-active #wrapper #videos #pages a').click(function(e) {
      e.preventDefault();
      e.stopPropagation();
      $('#videos ul').addClass('hidden');
      $('#'+$(this).attr('href').slice(1)).removeClass('hidden');
    });


    /**
    * Pop-ups in distributor list
    */
    $('#distributors h2, #distributors h3').click(function(e) {
      if($('#pop').length) {
        $('#pop').remove();
      } else {
        var data = $(this).parent().html(),
            pos = $(this).parent().offset();
        $('#distributors').append('<div id="pop">'+data+'</div>');
        $('#pop').offset({left: pos.left+100, top: pos.top});
      }
    });

  }

  /**
  * Team
  */

  if($('body').hasClass('team')) {

    $('a.website').click(pop);

    $('ul.overview a').mouseover(function(e) {
      var sid = $(this).parent().attr('class');

      $('body').removeClass('girls');
      $('body').removeClass('boys');

      if($(this).parent().hasClass('girls')) {
        $('body').addClass('girls');
        sid = sid.slice(0, -6);
      } else {
        $('body').addClass('boys');
      }

      $('.team ul.preview li.'+sid).css('display', 'block');

    });

    $('ul.overview a').mouseout(function(e) {
      $('.team ul.preview li').css('display', 'none');
      $('body').removeClass('girls');
      $('body').removeClass('boys');
    });

    if($('#content').hasClass('person')) {
      $('.image').css('backgroundImage', 'url('+$('.image img').get(0).src+')');
      $('.image img').get(0).src = '/assets/i/team/mask.png';
      $('.image').click(function(e) {
        $('#gallery a').lightBox({
          fixedNavigation:true,
          imageLoading: '/assets/i/lb/loading.gif',
          imageBtnClose: '/assets/i/lb/close.gif',
          imageBtnPrev: '/assets/i/lb/prev.gif',
          imageBtnNext: '/assets/i/lb/next.gif'
        });
        $('#gallery').draggable();
        $('#gallery').addClass('active');
        $('#gallery ul img').css('display', 'none');
        $('#gallery ul a').each(function(e) {
          var img = $(this).find('img').get(0).src;
          $(this).css('backgroundImage', 'url('+img+')');
          $(this).css('backgroundPosition', 'center center');
        });
        $('#gallery').append('<a href="#" class="close">Close</a>');
        $('#gallery .close').click(function(e) {
          $('#gallery').removeClass('active');
        });
      });
    }

  }

  /**
  * Technology
  */

  if($('body').hasClass('technology')) {

    // if($.browser.msie && $.browser.version < 8) { $('body').removeClass('js-active'); }

    var orig = $('#content').css('backgroundImage');

    /**
    * Outsoles (background-image) clickable
    */
    $('.technology.js-active #content.outsoles').click(function(e) {
      if(orig != $('#content').css('backgroundImage')) {
        return;
      }
      var pos = $(this).offset(),
          left = e.pageX - pos.left,
          top = e.pageY - pos.top; 
      if(left >= 220 && left <= 680 && top >= 100 && top <= 555) {
        if(left <= 335) {
          $('.technology.js-active #content article.conquest').trigger('click');
        } else if(left <= 450    ) {
          $('.technology.js-active #content article.vibram').trigger('click');
        } else if(left <= 565) {
          $('.technology.js-active #content article.conweb').trigger('click');
        } else {
          $('.technology.js-active #content article.fishbone').trigger('click');
        }
      }
    });

    /**
    * Make tech details draggable
    */
    $('.technology.js-active #content article').click(function(e) {

      $('#content .clone').remove();

      var img = $(this).find('img');
      $('.technology.js-active #content article').removeClass('selected');
      $('#content article.clone').remove();
      $('#content').css('backgroundImage', state);

      state = $('#content').css('backgroundImage');
      $('#content').css('backgroundImage', 'url('+img[0].src+')');

      $('.technology.js-active #container').append('<div class="article"></div>');
      var clone = $('#container div.article');
      $(clone).attr('class', $(this).attr('class')+' article');
      $(this).children().each(function(e) {
        $(clone).append($(this).clone(true));
      });

      $(clone).addClass('active clone');
      $(clone).data('sid', $(this).attr('class'));
      $(clone).draggable({
        // start: function() {
        //   // $.cookie('wiggled', 'yes', { expires: 365, path: '/' });
        //   // $(this).wiggle('stop');
        //   // $(this).data('wiggled', true);
        // }
      });

      // $(clone).mouseover(function(e) {
      //   // if(!$(this).data('wiggled') && $.cookie('wiggled') != 'yes') {
      //   //   $(this).wiggle('start');
      //   // }
      // });
      // $(clone).mouseout(function(e) {
      //   // if($(this).wiggle('isWiggling')) {
      //   //   $(this).wiggle('stop');
      //   // }
      // });

      $(clone).find('.close').click(function(e) {
        e.stopPropagation();
        $('#content').css('backgroundImage', state);
        $('#content .clone').remove();
      });

      $(clone).find('.video a').click(function(e) {
        e.preventDefault();
        if($('#video').length == 0) {
          $('#content').append('<div id="video" class="article clone" style="position: absolute; left: 100px"><iframe src="'+$(this).attr('href')+'" type="text/html" width="600" height="338" frameborder="0"></iframe><a class="close"></a></div>');
          $('#video').draggable();
          $(clone).addClass('disabled');
          $('#video').addClass('active');

          $('#video').find('.close').click(function(e) {
            e.stopPropagation();
            $(clone).removeClass('disabled');
            $('#video').remove();
          });
        }
      });

      $('ul.small h2').click(function(e) {
        if($('#pop').length) {
          $('#pop').remove();
          if($(clone).data('category') == 4) {
            $('#content').css('backgroundImage', state2);
          }
        } else {
          var data = $(this).parent().html(),
              pos = $(this).parent().offset();
          $(clone).append('<div id="pop">'+data+'</div>');
          $('#pop').offset({left: pos.left+40, top: pos.top-20});
          if($(clone).data('category') == 4) {
            state2 = $('#content').css('backgroundImage');
            $('#content').css('backgroundImage', 'url(/assets/i/'+$(clone).data('sid')+'/'+$(this).parent().attr('class')+'.jpg)');
          }
        }
      });

    });

  }


  /**
  * Home
  */

  if($('body').hasClass('home')) {

    home.current = $('#splash article.selected').get(0).id;
    home.currentSeries = $('#splash nav').attr('class');

    $('#splash article.selected').removeClass('selected').css('display', 'block');

    /**
    * Series "tab" Navigation
    */
    $('#splash nav ul.series a').click(function(e) {

      e.preventDefault();

      var id = this.href.slice(this.href.indexOf('#')+1),
          slideOut = 'right',
          slideIn = 'left';

      home.nextSeries = id;

      if(!home.series[home.current]) {
        $('#'+home.current)
            .stop()
            .fadeOut(500);
        $('body').attr('class', '').addClass($('html').attr('lang')+' home js-active series');
      }

      if(home.nextSeries == home.currentSeries) {
        $('#'+home.currentSeries)
            .stop()
            .fadeIn(500);
        home.current = home.nextSeries;
        home.nextSeries = null;
        return;
      }

      $('#splash nav').attr('class', '').addClass(id);

      if(home.series[home.currentSeries] > home.series[home.nextSeries]) {
        slideOut = 'left';
        slideIn = 'right';
      }

      var ul = $('#splash nav .boots');

      $(ul)
        .stop()
        .hide('slide', { direction: 'left', easing: false }, 1, function() {
          $('#splash nav .boots li').remove();
          $('#splash article.'+id).each(function(e) {
            $(ul).append('<li class="'+this.id+'"><a href="'+$(this).find('a').attr('href')+'">'+$(this).find('h1').html()+'</a></li>');
          });
        });

      $('#'+home.currentSeries).hide('slide', { direction: slideOut, easing: false }, 500);
      $('#'+home.nextSeries).show('slide', { direction: slideIn, easing: false }, 500, function(){
        $(ul).show('slide', { direction: 'right', easing: false }, 500);
      });

      home.currentSeries = home.nextSeries;
      home.current = home.nextSeries;
      home.nextSeries = null;


    });

  }


  /**
  * Boot navigation
  */
  $('#splash nav ul.boots a').live('click', function(e) {


    var next = $('#'+$(this.parentNode).attr('class'));

    if(next.length) {

      if(home.current) {
        $('#'+home.current)
            .stop(true, true)
            .fadeOut(500);
      }

      var id = $(next).get(0).id;

      $(next)
          .stop()
          .fadeIn(1000, function(e) {
            home.current = id;
            $('#splash nav ul.boots li').removeClass('selected');
            $('#splash nav ul.boots li.'+id).addClass('selected');
          });
      $('body').attr('class', '');
      $('body').addClass('home js-active '+id);
    }

    return false;

  });

  /**
  * Blog and also Deemons
  */
  if($('body').hasClass('blog') || $('body').hasClass('deemons')) {

    var links = $('#resultset a'),
        videos = [];

    for (var i = 0; i < links.length; i++) {
      if(links[i].href.indexOf('vimeo') > 0 || links[i].href.indexOf('youtube') > 0) {
        videos.push(links[i]);
      } else if($(links[i]).attr('href').slice(0, 4) == 'http' && !$(links[i]).hasClass('share')) {
        $(links[i]).click(pop);
      }
    }

    if(videos.length) {
      for (i = 0; i < videos.length; i++) {
        if(videos[i].href.indexOf('vimeo') > 0) {
          var url = 'http://www.vimeo.com/api/oembed.json?url=' + encodeURIComponent(videos[i].href) + '&callback=inlineVimeoVideo&width=580';
          var js = document.createElement('script');
          js.setAttribute('type', 'text/javascript');
          js.setAttribute('src', url);
          document.getElementsByTagName('head').item(0).appendChild(js);
        } else {
          var iframe = document.createElement('iframe');
          iframe.width = 580;
          iframe.height = 385;
          iframe.frameborder = 0;
          $(iframe).css('border', 'none');
          var match = videos[i].href.match(/youtube.com\/.*v=([a-zA-Z0-9\-\_]+)/);
          iframe.src = 'http://www.youtube.com/embed/'+match[1];
          $(iframe).insertBefore(videos[i]);
          videos[i].parentNode.removeChild(videos[i]);
        }
      }
    }
    
  }


  /**
  * Dealers (Google Maps)
  */
  if($('body').hasClass('dealers')) {

    var latlng,
        strLatLng = '47.5882510000 12.1642450000',
        uls = $('#content ul'),
        lis = $('#dealers-resultset li'),
        map = document.createElement('div'),
        bounds,
        markers = [],
        latlngs = [],
        infos = [];

    $('#shops h1').click(function(e) {
      if($(this).parent().hasClass('active')) {
        $(this).parent().find('ul').hide();
        $(this).parent().removeClass('active');
      } else {
        $(this).parent().find('ul').show();
        $(this).parent().addClass('active');
      }
    });

    // Split into columns
    if(lis.length > 3) {
      var clones = [];
      for (var i=0; i < lis.length; i++) {
        clones[i] = $(lis[i]).clone(true);
      };
      $('#dealers-resultset ul').remove();
      $('#dealers-resultset').append('<ul id="col-1"></ul><ul id="col-2"></ul><ul id="col-3"></ul>');
      for (var i=0; i < clones.length; i++) {
        if(i <= (clones.length / 3)) {
          $('#col-1').append(clones[i]);
        } else if(i <= (clones.length / 3) * 2) {
          $('#col-2').append(clones[i]);
        } else {
          $('#col-3').append(clones[i]);
        }
      };
      lis = $('#dealers-resultset li');
    }

    $(lis).css('cursor', 'pointer');

    map.id = 'map';

    $('#content').prepend(map);

    if($('#hq').length) {
      strLatLng = $('#hq').data('latlon');
    } else if(lis.length) {
      strLatLng = $(lis[0]).data('latlon');
    }

    if(window.google) {

      latlng = new google.maps.LatLng(strLatLng.slice(0, strLatLng.indexOf(' ')), strLatLng.slice(strLatLng.indexOf(' ')));
      bounds = new google.maps.LatLngBounds();

      var gMap = new google.maps.Map(map, {
        zoom: 8,
        center: latlng,
        mapTypeControl: false,
        mapTypeControlOptions: {
          mapTypeIds: ['Styled']
        },
        mapTypeId: 'Styled',
        scaleControl: true
      });

      var styledMapType = new google.maps.StyledMapType([
        {
          featureType: "landscape.man_made",
          elementType: "all",
          stylers: [
            { hue: "#ffffff" },
            { saturation: -100 },
            { lightness: 100 }
          ]
        },{
          featureType: "water",
          elementType: "all",
          stylers: [
            { hue: "#af022f" },
            { saturation: 97 },
            { lightness: -50 }
          ]
        },{
          featureType: "landscape.natural",
          elementType: "all",
          stylers: [
            { hue: "#ffffff" },
            { saturation: -100 },
            { lightness: 100 }
          ]
        },{
          featureType: "water",
          elementType: "labels",
          stylers: [
            { hue: "#000000" },
            { saturation: -100 },
            { invert_lightness: true },
            { lightness: -100 }
          ]
        },{
          featureType: "road.highway",
          elementType: "all",
          stylers: [
            { hue: "#ebc0cb" },
            { saturation: -48 },
            { lightness: 55 }
          ]
        },{
          featureType: "transit",
          elementType: "all",
          stylers: [
            { hue: "#ffffff" },
            { saturation: 0 },
            { lightness: 100 }
          ]
        },{
          featureType: "poi.park",
          elementType: "all",
          stylers: [
            { hue: "#cccccc" },
            { saturation: -100 },
            { lightness: 29 }
          ]
        },{
          featureType: "road.arterial",
          elementType: "all",
          stylers: [
            { hue: "#ebc0cb" },
            { saturation: -48 },
            { lightness: 29 }
          ]
        },{
          featureType: "road.local",
          elementType: "all",
          stylers: [
            { hue: "#ebc0cb" },
            { saturation: -48 },
            { lightness: -16 }
          ]
        }
      ], { name: 'Styled' });
      gMap.mapTypes.set('Styled', styledMapType);

      var popOpen = function() {
        for (var i = 0; i < markers.length; i++) {
          if(markers[i]) {
            markers[i].infoBox.close(gMap, markers[i]);
          }
        }
        this.infoBox.open(gMap, this);
      };

      for (var i = 0; i < lis.length; i++) {
        strLatLng = $(lis[i]).data('latlon');
        if(strLatLng) {
          infos[i] = new google.maps.InfoWindow({
              content: lis[i].innerHTML,
              maxWidth: 250
          });

          latlngs.push(new google.maps.LatLng(strLatLng.slice(0, strLatLng.indexOf(' ')), strLatLng.slice(strLatLng.indexOf(' '))));
          markers[i] = new google.maps.Marker({
              position: new google.maps.LatLng(strLatLng.slice(0, strLatLng.indexOf(' ')), strLatLng.slice(strLatLng.indexOf(' '))),
              icon: '/assets/i/marker.png',
              map: gMap,
              infoBox: infos[i],
              title: lis[i].getElementsByTagName('strong')[0].innerHTML
          });
          google.maps.event.addListener(markers[i], 'click', popOpen);
        } else {
          $(lis[i]).css('opacity', 0.5);
        }
      }

      // Center zoom to fit all markers
      for (var i=0; i < latlngs.length; i++) {
        bounds.extend(latlngs[i]);
      }
      gMap.fitBounds(bounds);

      $(lis).click(function(e) {
        for (var i = 0; i < markers.length; i++) {
          if(markers[i]) {
            markers[i].infoBox.close(gMap, markers[i]);
          }
        }
        for (i = 0; i < lis.length; i++) {
          if(lis[i] == this) {
            markers[i].infoBox.open(gMap, markers[i]);
          }
        }
      });  

    } // end if google.maps

  } // end if body.dealers

  /**
  * Boots Detail
  */
  if($('body').hasClass('boot')) {

    $video = $('#video');
    $sizes = $('#sizes');
    $tech = $('#technology');
    $threesixty = $('#threesixty');
    $intro = $('#content .intro');

    $intro.css('opacity', 0.95);

    /*
    * Blur all draggable windows
    */
    var blur = function(e) {
      $('.draggable').css('zIndex', 1);
      $('.draggable').css('opacity', 0.95);
      $('#video.draggable').css('opacity', 1);
      $('.draggable').removeClass('active');
      $('#close').css('display', 'none');
    };

    /*
    * Focus a mini-window
    */
    var focus = function(e) {

      if($.browser.msie && $.browser.version < 9 && $(this).hasClass('intro')) {
        $('#close').css('display', 'none');
      } else if($.browser.msie && $.browser.version < 9) {
        var os1 = $(this).offset(),
            os2 = $('#content').offset();

        $(this).css('zIndex', 1000);
        $(this).css('opacity', 0.95);
        $(this).addClass('active');
        $('#close').css({
          'display': 'block',
          'left': (os1.left - os2.left-20) + 'px',
          'top': (os1.top - os2.top-20) + 'px',
          'zIndex': 1001
        });
      }

      $(this).addClass('active');

      if($(this).hasClass('clone')) {
        $('#tech-mask').get(0).src = '/assets/i/tech-overlays/'+$(this).data('sid')+'.png';
        $('#tech-mask').css('visibility', 'visible');
        $('#tech-mask').data('current', $(this).data('sid'));
      }

    };

    /*
    * On mouse down (click or drag start), focus the article
    */
    $('.draggable').live('mousedown', function(e) {
      blur();
      focus.apply(this);
    });

    $('.draggable').live('drag', function(e) {
      if($.browser.msie && $.browser.version < 9 && $(this).hasClass('intro')) {
        $('#close').css('display', 'none');
      } else if($.browser.msie && $.browser.version < 9) {
        var os1 = $(this).offset(),
            os2 = $('#content').offset();
        $('#close').css({
          'display': 'block',
          'left': (os1.left - os2.left-20) + 'px',
          'top': (os1.top - os2.top-20) + 'px',
          'zIndex': 1001
        });
      }
    });

    $('#video,#sizes,#technology,#threesixty,#content .intro').addClass('draggable');
    $('#video,#sizes,#technology,#threesixty,#content .intro').draggable({
      // drag: function(e) {
      //   if($.browser.msie) {
      //     var os1 = $(this).offset(),
      //         os2 = $('#content').offset();
      //     $('#close').css({
      //       'display': 'block',
      //       'left': (os1.left - os2.left-20) + 'px',
      //       'top': (os1.top - os2.top-20) + 'px'
      //     });
      //   }
      // },
      start: function(e) {
        $('#technology').data('noclick', true);
        // $.cookie('wiggled', 'yes', { expires: 365, path: '/' });
        // $(this).wiggle('stop');
        // $(this).data('wiggled', true);
      }
    });

    // $('.draggable').live('mouseover', function(e) {
    //   // if(!$(this).data('wiggled') && $.cookie('wiggled') != 'yes') {
    //   //   $(this).wiggle('start');
    //   // }
    // });
    // $('.draggable').live('mouseout', function(e) {
    //   // if($(this).wiggle('isWiggling')) {
    //   //   $(this).wiggle('stop');
    //   // }
    // });

    if($video.length || $sizes.length || $tech.length || $threesixty.length) {

      $('#video,#sizes,#technology,#threesixty').css('display', 'none');

      if($.browser.msie && $.browser.version < 9) {
        $('#content').append('<a href="#" id="close">Close</a>');
        $('#close').css({
          'display': 'none',
          'left': '0px',
          'position': 'absolute',
          'top': '0px'
        });
      } else {
        $('#video,#sizes,#technology,#threesixty').append('<a href="#" class="close">Close</a>');
      }

      /*
      * Add play button to the video preview
      */
      if($('#content .intro .video-preview').length) {
        var img = $('#content .intro .video-preview img').get(0);
        $('#content .intro .video-preview').css('backgroundImage', 'url('+img.src+')');
        img.src = '/assets/i/play.png';
        $('#content .intro .video-preview').click(function(e){
          e.preventDefault();
          var $el = $('#video');
          $el.css('display', 'block');
          blur();
          focus.apply($el);
        });
      }

      /*
      * Add the sub-menu to the intro
      */
      var ul = $('#content .intro').prepend('<ul></ul>');

      if($video.length && !$('#content .intro .video-preview').length) {
        $('#content .intro ul').append('<li class="video"><a href="#video">'+$video.find('h1').html()+'</a></li>');
      }
      if($sizes.length) {
        $('#content .intro ul').append('<li class="sizes"><a href="#sizes">'+$sizes.find('h1').html()+'</a></li>');
      }
      if($tech.length) {
        $('#content .intro ul').append('<li class="tech"><a href="#technology">'+$tech.find('h1').html()+'</a></li>');
      }
      if($threesixty.length && (!$.browser.msie || ($.browser.msie && $.browser.version >= 9))) {
        $('#content .intro ul').append('<li class="threesixty"><a href="#threesixty">'+$threesixty.find('h1').html()+'</a></li>');
      }


      /*
      * Click on tech article H1, clone the element and display it
      */
      $('#technology').find('article h1').click(function(e) {
        e.preventDefault();

        if($('#technology').data('noclick') == true) {
          $('#technology').data('noclick', false);
          return;
        }

        var sid = $(this).parent().data('sid');
        if($('#content .clone.'+sid).length) {
          focus.apply($('#content .clone.'+sid));
          return;
        }

        $('#content').append('<div class="article clone draggable '+sid+'"></div>');
        var clone = $('#content div.article.'+sid);
        $(this).parent().children().each(function(e) {
          $(clone).append($(this).clone(true));
        });

        blur();
        if(!$.browser.msie || ($.browser.msie && $.browser.version >= 9)) {
          $(clone).append('<a class="close"></a>');
        }
        var os = $('#technology').offset();
        $(clone).offset({top: os.top-50, left: os.left-50 });
        $(clone).draggable();
        $(clone).data('sid', sid);
        focus.apply(clone);

        $('#tech-mask').get(0).src = '/assets/i/tech-overlays/'+sid+'.png';
        $('#tech-mask').css('visibility', 'visible');

      });

    }

    if($('#colors').length) {

      /*
      * Append default color to #colors
      */
      $('#colors').append('<li><img src="'+$('#detail').get(0).src+'" id="color-default" style="display: none"></li>');

      /*
      * Close an article, re-focus the intro
      */
      $('#colors img').click(function(e) {
        $('#detail').get(0).src = $(this).get(0).src;
        $('#colors img').css('display', 'block');
        $(this).css('display', 'none');
        if($('body').hasClass('stage')) {
          $('body').removeClass('white').removeClass('black');
          if(this.id == 'color-white') {
            $('body').addClass('white');
          } else {
            $('body').addClass('black');
          }
        }
      });

      /*
      * Set default image based on hashtag
      */
      if(window.location.hash && window.location.hash.length > 1) {
        var img = $('#color-'+window.location.hash.slice(1));
        if(img.length) {
          $('#detail').get(0).src = $(img).get(0).src;
          $('#colors img').css('display', 'block');
          $(img).css('display', 'none');
        }
      }

    }

    if($('#threesixty-img').length) {
      $('#threesixty-img').reel({
        footage: 24,
        delay: 0,
        speed: 0.5,
        frames: 24
        // images: [
        //   '/assets/i/c3/360/101098_0001.jpg',
        //   '/assets/i/c3/360/101098_0002.jpg',
        //   '/assets/i/c3/360/101098_0003.jpg',
        //   '/assets/i/c3/360/101098_0004.jpg',
        //   '/assets/i/c3/360/101098_0005.jpg',
        //   '/assets/i/c3/360/101098_0006.jpg',
        //   '/assets/i/c3/360/101098_0007.jpg',
        //   '/assets/i/c3/360/101098_0008.jpg',
        //   '/assets/i/c3/360/101098_0009.jpg',
        //   '/assets/i/c3/360/101098_0010.jpg',
        //   '/assets/i/c3/360/101098_0011.jpg',
        //   '/assets/i/c3/360/101098_0012.jpg',
        //   '/assets/i/c3/360/101098_0013.jpg',
        //   '/assets/i/c3/360/101098_0014.jpg',
        //   '/assets/i/c3/360/101098_0015.jpg',
        //   '/assets/i/c3/360/101098_0016.jpg',
        //   '/assets/i/c3/360/101098_0017.jpg',
        //   '/assets/i/c3/360/101098_0018.jpg',
        //   '/assets/i/c3/360/101098_0019.jpg',
        //   '/assets/i/c3/360/101098_0020.jpg',
        //   '/assets/i/c3/360/101098_0021.jpg',
        //   '/assets/i/c3/360/101098_0022.jpg',
        //   '/assets/i/c3/360/101098_0023.jpg',
        //   '/assets/i/c3/360/101098_0024.jpg'
        // ]
      });
    }

    /*
    * Create the tech-mask, position it over the detail image
    */
    $('#detail').after('<img src="about:blank" id="tech-mask">');
    $('#tech-mask').css('width', $('#detail').outerWidth());
    $('#tech-mask').css('height', $('#detail').outerHeight());
    $('#tech-mask').css('visibility', 'hidden');
    $('#tech-mask').css('opacity', 0.5);
    $('#tech-mask').data('current', '');

    /*
    * Add the Performance/Flex values on the black bars
    */
    $('.pflex li').each(function(e) {
      $(this).append('<em>'+$(this).data('value')+'</em>');
    });

    /*
    * Close an article, re-focus the intro
    */
    $('#content .close').live('click', function(e) {
      $(this).parent().css('display', 'none');
      blur();
      if($(this).parent().hasClass('clone')) {
        focus.apply($('#technology'));
        $(this).parent().remove();
        if($(this).data('sid') == $('#tech-mask').data('sid')) {
          $('#tech-mask').css('visibility', 'hidden');
        }
      } else if($(this).parent().get(0).id == 'video') {
        var iframe = $(this).parent().find('iframe');
        var data = {
          src: $(iframe).attr('src'),
          width: $(iframe).attr('width'),
          height: $(iframe).attr('height')
        };
        $(iframe).remove();
        $(this).parent().append('<iframe src="'+data.src+'" width="'+data.width+'" height="'+data.height+'" frameborder="0"></iframe>');
      } else {
        focus.apply($('#content .intro'));
      }
    });

    /*
    * IE Close an article, re-focus the intro
    */
    $('#close').live('click', function(e) {
      var el = $('#content .active');
      $(el).css('display', 'none');
      blur();
      if($(el).hasClass('clone')) {
        focus.apply($('#technology'));
        $(el).remove();
        if($(el).data('sid') == $('#tech-mask').data('sid')) {
          $('#tech-mask').css('visibility', 'hidden');
        }
      } else if($(el).get(0).id == 'video') {
        var iframe = $(el).find('iframe');
        var data = {
          src: $(iframe).attr('src'),
          width: $(iframe).attr('width'),
          height: $(iframe).attr('height')
        };
        $(iframe).remove();
        $(this).parent().append('<iframe src="'+data.src+'" width="'+data.width+'" height="'+data.height+'" frameborder="0"></iframe>');
      } else {
        focus.apply($('#content .intro'));
      }
    });

    /*
    * Open a main article, focus it
    */
    $('#content .intro ul a').click(function(e) {
      e.preventDefault();
      var $el = $('#'+this.href.slice(this.href.indexOf('#')+1));
      $el.css('display', 'block');
      blur();
      focus.apply($el);
    });

    $('#content .intro').prepend($('#content > h1').clone());

    $('#content .intro h1').css('visibility', 'visible');

  }

  resizeBG();
  $(window).resize(resizeBG);

  // $('#content a').click(function(e) {
  //   if($(this).hasClass('close') || $(this).hasClass('video')) {
  //     return;
  //   }
  //   e.preventDefault();
  //   if($(this).attr('href').slice(0, 4) == 'http') {
  //     window.open($(this).attr('href'));
  //   } else {
  //     window.location = $(this).attr('href');
  //   }
  // });
  
  if ($('body').hasClass('deemons')) {
      var raw = JSON.parse(riders);
      var map = {};
      for (var i=0; i < raw.length; i++) {
        map[raw[i].id]=raw[i];
      }
      var detail = $('#riderdetail');
      var updateDetail = function (id) {
        var rider = map[id];
        if(rider) {
          $('#deemonhover').remove();
          $('#rider_'+id).append('<div id="deemonhover"></div>');
          $('h2', detail).html(rider.name);
          $('.img', detail).css('background-image',"url('"+rider.image+"')");
          $('.age', detail).html("Age: "+rider.birthyear);
          $('.home', detail).html(rider.home);
          $('a', detail).attr("href",rider.link);
        }
      };
      var current = 0;
      var images = $('#riderselection a');
      
      var reg = /rider_(\d+)/;
      images.each(function() {
        var id = $(this).attr('id').match(reg)[1];
        $(this).hover(function() {
          updateDetail(id);
          
        },function() {
          updateDetail(currentRider+"");
        });
      });
      updateDetail(""+currentRider);
  }

});
