jQuery(document).ready(function($) {
	
	$('#contact-name').focus(function() {
	    $('#name-error').css('display','none');
	  }).blur(function() {
	    $('#name-error').fadeOut('medium');
	  });	
	
// On form submit fade out form fields and replace with success message
$('#contactForm').ajaxForm(function() { 
	$('.form-before').fadeOut('slow', function() {
		$('.form-after').fadeIn(250, function() {
		});
	});
});

// Fade in elements on page load
$('#main header').delay(500).fadeIn(250, function() {
  $('#app-icon').fadeIn(250, function() {
    $('#intro').fadeIn(250, function() {
    });
  });
});

// Prepare modal
$('#modal').dialog({
  width: 800,
  modal: true,
  autoOpen: false,
  closeText: '',
  show: 'fade',
  hide: 'fade',
  closeOnEscape: true,
  open: function() {
    $('.ui-widget-overlay').hide().fadeIn();
    $('#modal .content').addClass('normal');
    $('#interested_contact_name').blur();
  }
});

$('#modal .close').click(function() {
  $('#modal').fadeOut();
  $('.ui-widget-overlay').fadeOut(500, function() {
    $('#modal').dialog('close');
    $('#modal .content').removeClass('normal');
  });
});

$('#contact').dialog({
  width: 800,
  modal: true,
  autoOpen: false,
  closeText: '',
  show: 'fade',
  hide: 'fade',
  closeOnEscape: true,
  open: function() {
    $('.ui-widget-overlay').hide().fadeIn();
    $('#contact .content').addClass('normal');
    $('#contact input').blur();
  }
});

$('.link-contact').click(function() {
  $('#contact').dialog('open');
	  $('.form-after').hide();
	  $('form').resetForm();
			$('.form-before').fadeIn(50, function() {
			});
  return false;
});

$('#contact .close').click(function() {
  $('#contact').fadeOut();
  $('.ui-widget-overlay').fadeOut(500, function() {
    $('#contact').dialog('close');
    $('#contact .content').removeClass('normal');
  });
});

$('#contactForm').validate({
  messages: { 
    "name": {
      required: "Go on, tell us your name.", 
      minlength: "That's a very short name."
    },
    "email": {
      required: "We need your email address.", 
      email: "Check your email address again."
    },
    "message": {
      required: "You can't send a blank message."
    }
  }
});

$("a#fancyYoutube").click(function() {
  $.fancybox({
	'overlayShow'	: true,
	'transitionIn'	: 'elastic',
	'transitionOut'	: 'elastic',
	'width' : 674,
	'height' : 405,
	'href' : this.href.replace(new RegExp("watch\\?v=", "i"), 'v/'),
	'type' : 'swf',
	'swf' : {
	'wmode' : 'transparent',
	'allowfullsceen' : 'true'
	}
});
return false;
});

// Twitter hovercards
twttr.anywhere(function(twitter) {
twitter("a.hovercard").hovercards({
username: function(node) {
return node.title;}	});
});

// Open any #anchor locations
var hash = false; 

function checkHash(){ 
    if(window.location.hash != hash) { 
        hash = window.location.hash; 
        processHash(hash); 
    } t=setTimeout( checkHash,5000); 
}

function processHash(hash){
    if(hash == "#contact") {
      $('#contact').dialog('open');
    }
}

// Animated sports icons

$('.soccer').click(function () {
  $(this).stop().effect("bounce", { times:3 }, 250);
});
$('.rugby').click(function () {
  $(this).stop().effect("bounce", { times:2, distance:20 }, 250);
});
$('.gaa').click(function () {
  $(this).stop().effect("bounce", { times:3 }, 250);
});
$('.basketball').click(function () {
  $(this).stop().effect("bounce", { times:5, direction:'up', distance:70 }, 250);
});
$('.cricket').click(function () {
  $(this).stop().effect("bounce", { times:2, distance:15 }, 200);
});


$(function() {
    $('.hockey').click(function(event) {
        $(this).stop(true, true)
            .animate(
                { right: 140 }, {
                    duration: 'slow',
                    easing: 'easeOutBack'
                })
            .animate(
                { right: 0 }, {
                    duration: 'slow',
                    easing: 'easeOutBack'
                });
    });
});

$(function(){

  // Overview mask

  var overview = $("#overview"),
      overviewMaskId = "overview-mask";
  $("<div/>", { id: overviewMaskId }).insertBefore(overview);
  var overviewMask = $("#" + overviewMaskId),
      mainContent = $("#main"),
      contentHeight = mainContent.css("height"),
      maskSlideTimingFunction = "cubic-bezier(.550, .085, .680, .530)",
      maskSlideDuration = 4000;

  overviewMask.css({
    "-webkit-transition": "-webkit-transform " + maskSlideDuration +
                          "ms " + maskSlideTimingFunction,
    "-moz-transition": "-moz-transform " + maskSlideDuration +
                       "ms " + maskSlideTimingFunction,
    "-webkit-transform": "translateY(" + contentHeight + ")",
    "-moz-transform": "translateY(" + contentHeight + ")"
  });
  setTimeout(function(){
    overviewMask.remove();
  }, maskSlideDuration);

  // Header gallery

  var gallery = $("#gallery"),
      galleryFigures = gallery.find("figure"),
      galleryNav = $("<nav/>").append($("<ul/>")),
      wallpaper = $("<span/>", {id: "wallpaper"}),
      glare = $("<span/>", {id: "glare"});

  for (var i=1; i <= galleryFigures.length; i++) {
    galleryNav.children().append($("<li/>").append($("<a/>", {
      href: "#fig" + i,
      text: "Picture " + i
    })));
    galleryFigures.eq(i-1).attr("id", "fig" + i);
  };

  gallery
    .prepend(wallpaper)
    .prepend(glare)
    .prepend(galleryNav);

  var galleryDots = galleryNav.find("a"),
      activeClass = "active";

  galleryDots
    .click(function(e){
      if(!animating) {
        galleryDots.removeClass(activeClass);
        $(this).addClass(activeClass);
        switch_to($(this).attr("href").substr(4),null);
      }
      e.preventDefault();
    })
    .eq(0)
    .addClass(activeClass);

  var pics = galleryFigures.children("div"),
      captions = galleryFigures.children("figcaption");

  pics
    .click(function(e){
      var fig = this.parentNode.id.substr(3);
      click_on(fig);
    });

  captions.eq(0).addClass(activeClass);

  var css_transforms = {
    1 : "translateX(0) scale(0.6)",
    2 : "translateX(310px) scale(0.51)",
    3 : "translateX(430px) scale(0.4)",
    4 : "translateX(-430px) scale(0.4)",
    5 : "translateX(-310px) scale(0.51)"
  };

  function css_transforms_for(pos) {
    return css_transforms[pos];
  }

  function z_index_for(pos) {
    return ((pos == 1) ? 2 : ((pos == 2 || pos == 5) ? -1 : -2));
  }

  function format_fig_pos(pos) {
    while(pos < 1)
      pos += 5;
    while(pos > 5)
      pos -= 5;
    return pos;
  }

  function create_css_animation_from_to_direction(from,to,direction) {
    var steps = format_fig_pos((to - from) * direction);
    var animation_name = "anim"+from+"to"+to+"steps"+steps;
    var animation = "@-webkit-keyframes " + animation_name + " {";
    var step;
    var percent = 100 / steps;
    var pos = from;
    var previous_pos;
    for(step=0;step<=steps;step++) {
      previous_pos = pos;
      pos = format_fig_pos(from + step * direction);
      inter = 0;
      if(pos == 4 && previous_pos == 3)
        inter = 1;
      else if(pos == 3 && previous_pos == 4) 
        inter = -1;
      if(inter != 0) {
        var middle = 0.2;
        animation += " " + ((step - 0.5 - middle / 2) * percent) + "% { ";
        animation += "-webkit-transform:translateX("+(480*inter)+"px) scale(0.3);\n";
        animation += "z-index:-3;\n"
        animation += "opacity:0;\n";
        animation += " }";
        animation += " " + ((step - 0.5 - middle / 2 + 0.05) * percent) + "% { ";
        animation += "-webkit-transform:translateX("+(480*inter)+"px) scale(0.3);\n";
        animation += "opacity:0;\n";
        animation += " }";
        animation += " " + ((step - 0.5 + middle / 2 - 0.05) * percent) + "% { ";
        animation += "-webkit-transform:translateX("+(-480*inter)+"px) scale(0.3);\n";
        animation += "opacity:0;\n";
        animation += " }";
        animation += " " + ((step - 0.5 + middle / 2) * percent) + "% { ";
        animation += "-webkit-transform:translateX("+(-480*inter)+"px) scale(0.3);\n";
        animation += "z-index:-3;\n";
        animation += "opacity:0;\n";
        animation += " }";
      }
      animation += " " + (step * percent) + "% { ";
      animation += "-webkit-transform:"+css_transforms_for(pos)+";\n";
      animation += "z-index:"+(z_index_for(pos))+";\n";
      animation += "opacity:1;\n";
      animation += " }";
    }
    animation += "}";
    var last_sheet = document.styleSheets[document.styleSheets.length - 1];
    last_sheet.insertRule(animation, last_sheet.cssRules.length);
    return animation_name;
  }

  var current_fig = 1,
      animating = false;

  $($("#fig"+current_fig+" > div")[0]).addClass("current");

  function click_on(fig) {
    if(animating)
      return;
    var direction = (format_fig_pos(current_fig + 1) == fig || format_fig_pos(current_fig + 2) == fig) ? -1 : 1;
    galleryDots.removeClass(activeClass);
    var dot = galleryDots.filter("[href='#fig"+fig+"']");
    $(dot).addClass(activeClass);
    switch_to(fig,direction);
  }

  function switch_to(fig,dir) {
    if(animating)
      return;
    if(fig == current_fig)
      return;
    if($.browser.webkit) {
      animating = true;
      var dur1 = 0.4;
      glare.addClass("resized");
      wallpaper.addClass("resized");
      var pic = $($("#fig"+current_fig+" > div")[0]);
      pic.removeClass("current");
      pic.css("-webkit-transition","-webkit-transform 0.3s cubic-bezier(0.3,0,0,1)");
      pic.css("-webkit-transform","scale(0.6)");
      $("#fig"+current_fig+ " figcaption").removeClass("active");
      $("#fig"+fig+ " figcaption").addClass("active");
      setTimeout(function() {
        gallery.addClass("animated");
        wallpaper.css("z-index","-3");
        var i,
            to,
            animation_name,
            pic,
            pos,
            direction = ((dir != null) ? dir : ((fig < current_fig) ? 1 : -1)),
            steps;
        for(i=1;i<=5;i++) {
          pos = format_fig_pos(i - current_fig + 1);
          to = format_fig_pos(pos - (fig - current_fig));
          steps = format_fig_pos((to - pos) * direction);
          animation_name = create_css_animation_from_to_direction(pos,to,direction);
          pic = $($("#fig"+i+" > div")[0]);
          pic.css("-webkit-transition","none");
          pic.css("-webkit-animation-name",animation_name);
          pic.css("-webkit-animation-timing-function","cubic-bezier(0.3,0,0,1)");
          pic.css("-webkit-animation-duration",(steps * dur1)+"s");
          pic.css("-webkit-transform",css_transforms_for(to));
          pic.css("z-index",z_index_for(to));
        }
        current_fig = parseInt(fig);

        setTimeout(function() {
          wallpaper.css("z-index","");
          gallery.removeClass("animated");
          glare.removeClass("resized");
          wallpaper.removeClass("resized");
          var pic = $($("#fig"+current_fig+" > div")[0]);
          pic.css("-webkit-animation-name","none");
          pic.css("-webkit-transition","-webkit-transform 0.3s cubic-bezier(0.3,0,0,1)");
          pic.css("-webkit-transform","scale(1)");
          pic.addClass("current");
          setTimeout(function() {
            animating = false;
          },300);
        },steps*dur1*1000+300);
      },300); 
    }
    else {
      animating = true;
      var new_pic = $($("#fig"+fig+" > div")[0]);
      var old_pic = $($("#fig"+current_fig+" > div")[0]);
      function hide_pic(pic,transform) {
        pic.css("-moz-transition","all 0.3s cubic-bezier(0.3,0,0,1)");
        pic.css("-o-transition","all 0.3s cubic-bezier(0.3,0,0,1)");
        pic.css("opacity","0");
        pic.css("-moz-transform",transform+ " translateY(20px)");
        pic.css("-o-transform",transform+ " translateY(20px)");
      }
      function show_pic(pic,transform,z_index) {
        pic.css("-moz-transition","none");
        pic.css("-moz-transform",transform + " translateY(20px)");
        pic.css("-o-transition","none");
        pic.css("-o-transform",transform + " translateY(20px)");
        pic.css("z-index",z_index);

        setTimeout(function() {
          pic.css("-moz-transition","all 0.3s cubic-bezier(0.3,0,0,1)");
          pic.css("-moz-transform",transform);
          pic.css("-o-transition","all 0.3s cubic-bezier(0.3,0,0,1)");
          pic.css("-o-transform",transform);
          pic.css("opacity","1");
        },50);
      }
      var old_pos = new_pic.attr("data-pos");
      if(!old_pos)
        old_pos = fig;
      old_pic.removeClass("current");
      hide_pic(new_pic,css_transforms_for(old_pos));
      hide_pic(old_pic,"scale(1)");
      $("#fig"+current_fig+ " figcaption").removeClass("active");
      $("#fig"+fig+ " figcaption").addClass("active");
      setTimeout(function() {
        show_pic(new_pic,"scale(1)",z_index_for(1));
        show_pic(old_pic,css_transforms_for(old_pos),z_index_for(old_pos));
        new_pic.attr("data-pos","1");
        old_pic.attr("data-pos",old_pos);
        new_pic.addClass("current");
        setTimeout(function() {
          animating = false;
        },300);
      },300)
      current_fig = parseInt(fig);
    }
  }

  $("head").append('<style></style>');

  $(window).bind("keyup",function(e) {
    if(e.keyCode == 39)
      click_on(format_fig_pos(current_fig + 1));
    else if(e.keyCode == 37)
      click_on(format_fig_pos(current_fig - 1));
  });

  var touchstart_x = -1;
  var touchend_x = -1;
  gallery.bind("touchstart",function(e) {
    touchstart_x = e.originalEvent.targetTouches[0].pageX;
  });
  gallery.bind("touchmove",function(e) {
    touchend_x = e.originalEvent.targetTouches[0].pageX;
  });
  gallery.bind("touchend",function(e) {
    if(touchend_x > touchstart_x + 100)
      click_on(format_fig_pos(current_fig - 1));
    else if(touchend_x < touchstart_x - 100)
      click_on(format_fig_pos(current_fig + 1));
  });


  // Overview moving windows

  var movingWindowsId = "movingWindows",
      movingWindowPics = overview.children().eq(1).children("img"),
      movingWindowPicsPath = "img/front/home/overview/moving-windows/",
      unfocusedWindowAltNotice = " (unfocus)",
      reactiveClass = "reactive"
      goBackClass = "goBack",
      goFrontClass = "goFront";

  movingWindowPics.wrapAll($("<div/>", {id: movingWindowsId}));
  movingWindowPics.each(function(i){
    var $this = $(this);
    if(i == 0) {
      var windowType = "main";
      $this
        .wrap(
          $("<span/>")
            .addClass(windowType)
            .addClass(goFrontClass)
        )
        .parent()
        .append($("<img/>", {
          alt: $this.attr("alt") + unfocusedWindowAltNotice,
          src: movingWindowPicsPath + windowType + "/back.png"
        }));
    }
    else {
      var windowType = "chat";
      $this
        .wrap(
          $("<span/>")
            .addClass(windowType)
            .addClass(reactiveClass)
            .addClass(goBackClass)
        )
        .parent()
        .prepend($("<img/>", {
          alt: $this.attr("alt").replace(unfocusedWindowAltNotice, ""),
          src: movingWindowPicsPath + windowType + "/front.png"
        }));
    }
  });

  var movingWindow = $("#" + movingWindowsId),
      movingWindowWraps = movingWindow.children(),
      idleSpanClass = "idle";

  setTimeout(function(){
    movingWindowWraps.addClass(idleSpanClass);
  }, 1000);

  movingWindowWraps
    .click(function(){
      var $this = $(this);
      $this
        .removeClass(reactiveClass)
        .removeClass(goBackClass)
        .addClass(goFrontClass);
      movingWindowWraps
        .removeClass(idleSpanClass)
        .not($this)
        .addClass(reactiveClass)
        .removeClass(goFrontClass)
        .addClass(goBackClass);
      movingWindow.removeClass();
      setTimeout(function(){
        movingWindowWraps.addClass(idleSpanClass);
      }, 1000);
    });
    
    if(!((navigator.platform.indexOf("iPad") != -1) || (navigator.platform.indexOf("iPod") != -1) || (navigator.platform.indexOf("iPhone") != -1))) {
      movingWindowWraps.hover(
        function(){
          var $this = $(this);
          if ($this.is("." + reactiveClass)) {
            movingWindow.addClass("reactiveHovered");
          }
        },
        function(){
          movingWindow.removeClass();
        }
      );
    }

});



$("#download-csv").bind("mouseenter", function() {
    $(this).stop().animate({opacity: 1}, 'slow'); 
});
$("#download-csv").bind("mouseleave", function() {
    $(this).stop().animate({opacity: 0}, 'slow');
});

$("a.single_image").fancybox({
		'transitionIn'	:	'elastic',
		'transitionOut'	:	'elastic'
});

checkHash();

});

