$( document ).ready( function() {

  var updateScrollFunc, updateSizeFunc, openProjectFunc, closeProjectFunc,
      transitionEndEventNames, transitionEndEvent, clickEvent, resizeFunc, 
      $html, $style,
      setupCheckboxLabelFunc, contactVisible, footerYPos, iOSLabelsFunc;

  transitionEndEventNames = {
      'WebkitTransition' : 'webkitTransitionEnd',
      'MozTransition'    : 'transitionend',
      'OTransition'      : 'oTransitionEnd',
      'msTransition'     : 'msTransitionEnd',
      'transition'       : 'transitionEnd'
  },
  transitionEndEvent = transitionEndEventNames[ Modernizr.prefixed('transition') ];
  
  $html = $('html');
  
  if( navigator.userAgent.match(/Mobile/i) != null ) {
    $html.addClass('mobile');
    transitionEndEvent = null;
  }
  else {
    $html.addClass('desktop');
  }
  
  if( Modernizr.touch ) {
    clickEvent = 'tapone';
  }
  else {
    clickEvent = 'click';
  }
  
  $style = $("<style/>").appendTo("head");
  
  contactVisible = false;
  
  openProjectFunc = function( that ) {
  
    // we can only open a project that is in the starting state "Project Closed"
    if( ! $( that ).hasClass('project-closed') ) {
      return;
    }
  
    $( that ).removeClass('project-closed').addClass('project-open').addClass('proj-anim-1');
  };
  
  closeProjectFunc = function( that ) {
  
    // we can only close a project that is in the the fully open state, 
    // after "Animation 2", the small device entering animation has finished
    if( ! Modernizr.touch && Modernizr.cssanimations && ! $( that ).hasClass('proj-anim-2-ended') ) {
      return;
    }
    
    if( ! Modernizr.touch && Modernizr.cssanimations ) {
      $( that ).addClass('project-closing')
               .removeClass('proj-anim-2-ended')
               .removeClass('project-open');
    }
    else {
      $( that ).addClass('project-closed')
               .removeClass('project-open')
               .removeClass('proj-anim-1');
    }
  };
  
  if( null !== transitionEndEvent ) {
  
    // end of first animation
    $( '.proj-anim-1' ).live(transitionEndEvent, function() {
      
      $(this).removeClass('proj-anim-1').addClass('proj-anim-1-ended')
             .removeClass('proj-anim-1-ended').addClass('proj-anim-2');
             
      $(this).find('img').each(function() {
        if( $(this).data('thumb') ) {
          $(this).attr('src', $(this).data('thumb') );
        }
      });
    });
    
    // end of second animation
    $( '.proj-anim-2' ).live(transitionEndEvent, function() {
      
        $(this).addClass('proj-anim-2-ended').removeClass('proj-anim-2');
    });
    
    // end of closing animation
    $( '.project-closing' ).live(transitionEndEvent, function() {
          
      $( this ).find('img').each(function() {
        if( $(this).data('full') ) {
          $(this).attr('src', $(this).data('full') );
        }
      });
    
      $(this).addClass('project-closed');
    });
    
    // end of closed animation
    $( '.project-closed' ).live(transitionEndEvent, function() {
      $(this).removeClass('project-closing');
    });
  }
  
  $( '.project' ).bind(clickEvent, function() {

    $('.project-open').not( this ).each(function() {
      closeProjectFunc( this );
    });
    
    if( ! $( this ).hasClass('project-open') ) {
      openProjectFunc( this );
    }
    else {
      closeProjectFunc( this );
    }
  });
  
  $( '.project a' ).bind(clickEvent, function(ev) {
    ev.stopPropagation();
    return true;
  });
  
  if( ! Modernizr.touch || ! Modernizr.input.placeholder) {
    $('input,textarea').removeAttr('placeholder');
    $("label.infield").inFieldLabels();
  }
  else {
    $('label.infield').remove();
  }
  
  if( ! Modernizr.touch ) {
    
    resizeFunc = function() {
      footerYPos = $(document).height() - $('footer').height() - $(window).height();
      
      if( $(window).width() < 1000 ) {
        $('.project-main img').each(function() {
          if( $(this).data('full') ) {
            $(this).attr('src', $(this).data('full') );
          }
        });
      }
    };
  
    updateScrollFunc = function() {
      var scrollTop = window.pageYOffset ? window.pageYOffset : 
  		                document.documentElement ? document.documentElement.scrollTop :
  		                document.body ? document.body.scrollTop : 0;
      
      if( scrollTop > $(window).height() * 2 ) {
        $( 'header' ).css({ 'z-index': '1' });
      }
      else {
        $( 'header' ).css({ 'z-index': '3' });
      }
      
      if( contactVisible && scrollTop >= footerYPos ) {
        $('a.contact-button').animate({
    			left: '-53px'
    		}, 300);
    		
    		contactVisible = false;
      }
      else if( ! contactVisible && scrollTop < footerYPos) {
        $('a.contact-button').animate({
    			left: '-3px'
    		}, 300);
    		
    		contactVisible = true;
      }
      
      $po = $('.project-open');
    
      // if the project is more than halfway off screen, hide it automatically
      if( $po.length && $po.offset().top + ( $po.outerHeight() / 2 ) < scrollTop ) {
        closeProjectFunc( $po );
      }
    
    };
    
    $( window ).resize( function() { resizeFunc(); })
               .scroll( function() { updateScrollFunc(); });
    
    resizeFunc();
    updateScrollFunc();
  }
  
  // custom checkbox
  setupCheckboxLabelFunc = function() {
    if ( $('input.label-check').length ) { 
      $('label.label-check').each(function(){ 
        $(this).removeClass('c-on');
      });
      $('input.label-check:checked').each(function(){ 
        $(this).closest('form')
               .find('label[for="' + $(this).attr('id') + '"]').addClass('c-on');
      });
    };
    if ( $('input.label-radio').length ) {
      $('label.label-radio').each(function(){ 
        $(this).removeClass('r-on');
      });
      $('input.label-radio:checked').each(function(){ 
        $(this).closest('form')
               .find('label[for="' + $(this).attr('id') + '"]').addClass('r-on');
      });                
    }
  };
  $('input.label-check, input.label-radio').click(function(){ 
    setupCheckboxLabelFunc();
  });
  setupCheckboxLabelFunc();
  
  $('#contact-form').submit(function(ev) {
  
    ev.preventDefault();
    
    if( '' == $.trim( $('#contact-name').val() ) || 
        '' == $.trim( $('#contact-details').val() ) ) {
      alert('Please fill in all fields.');
      return;
    }
  
    $.post( 
      $(this).attr('action'), 
      $(this).serialize(),
      function( data ) {
        $('#contact-form').html( 'Thank you!<br />Someone will be in touch with you shortly.' );
      }
    );  
    
    return false;
  });
  
  $.fn.preload = function() {
    this.each(function(){
      (new Image()).src = this;
    });
  }
  
  $('.ct img').each(function() { 
    if( $(this).data('thumb') ) {
      $(this).data('full', $(this).attr('src') );
    
      $([ $(this).data('thumb') ]).preload();
    }
  });
  
  $('a.top').click(function(ev) {
    ev.preventDefault();

    $('body,html').animate({
			scrollTop: 0
		}, 1000);
  });
  
  $('a.contact-button').click(function(ev) {
    ev.preventDefault();

    $('body,html').animate({
			scrollTop: $(document).height()
		}, 1000);
  });
  
  iOSLabelsFunc = function () {
    
  	function fix() {
  		var labels = document.getElementsByTagName('label'), 
  			target_id, 
  			el;
  		for (var i = 0; labels[i]; i++) {
  			if (labels[i].getAttribute('for')) {
  				labels[i].onclick = labelClick;
  			}
  		}
  	};
  
  	function labelClick() {
  		el = document.getElementById(this.getAttribute('for'));
  		if (['radio', 'checkbox'].indexOf(el.getAttribute('type')) != -1) {
  			el.setAttribute('selected', !el.getAttribute('selected'));
  		} else {
  			el.focus();
  		}
  	};
  
    return {
  		fix: fix
  	}
  
  }();
  
  if( navigator.userAgent.match(/iPhone/i) || 
      navigator.userAgent.match(/iPod/i) || 
      navigator.userAgent.match(/iPad/i) ) {
      
  	iOSLabelsFunc.fix();
  }
});
