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');

  function resizeBG() {
    if($('#bg').length) {
      $('#bg').css({'width':$(window).width(),'height':$(document).height()});  
    }
    $('#left,#right').css({
      'height': $(document).height(),
      'width': ($(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
  */
  // $('.languages').click(function(e) {
  //   if($(this).hasClass('active')) {
  //     $(this).find('ul').css('display', 'none');
  //     $(this).removeClass('active');
  //   } else {
  //     $(this).find('ul').css('display', 'inline');
  //     $(this).addClass('active');
  //   }
  // });
  // $('.languages ul').css('display', 'none');

  /**
  * Company
  */

  /**
  * Make company articles draggable
  */
  $('.company.js-active #wrapper article').draggable({
    start: function() {
      $.cookie('wiggled', true, { expires: 365 });
      $(this).wiggle('stop');
      $(this).data('wiggled', true);
    }
  });
  $('.company.js-active #wrapper article').mouseover(function(e) {
    if(!$(this).data('wiggled') && !$.cookie('wiggled')) {
      $(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')) {

    $('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').append('<a href="#" class="close">Close</a>');
        $('#gallery .close').click(function(e) {
          $('#gallery').removeClass('active');
        });
      });
    }

  }

  /**
  * Technology
  */

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

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

      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+')');

      var clone = $(this).clone();
      $('.technology.js-active #content div').append(clone);
      $(clone).addClass('active clone');
      $(clone).data('sid', $(this).attr('class'));
      $(clone).draggable();

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

      $(clone).find('.video a').click(function(e) {
        e.preventDefault();
        if($('#video').length == 0) {
          $('#content').append('<article id="video" class="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></article>');
          $('#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
  */

  $('#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;
    }
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', {  }, 1, function(){
      $(ul).show();
    });

    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
  */
  if($('body').hasClass('blog')) {

    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]);
      }
    }

    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'),
        markers = [],
        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(' ')));

      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
          });

          // var myIcon = new GIcon(G_DEFAULT_ICON);
          // myIcon.image = "/assets/i/marker.png";
          // var markerOptions = { icon:myIcon };
          // var marker = new GMarker(map.getCenter(), markerOptions);

          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);
        }
      }

      $(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')) {
    $('.liner').hide();
    $('#liners li').css('cursor', 'pointer').click(function(e) {
      e.preventDefault();
      if($('#'+$(this).attr('class')+'-liner').is(':visible')) {
        $('#'+$(this).attr('class')+'-liner').hide();
      } else {
        $('.liner').hide();
        $('#'+$(this).attr('class')+'-liner').show();
      }
    });
  }

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

});
