var tagImageToPreload = ['images/blog_tag.png'];
var topImagesToPreload = ['images/2011LOGO.png','images/hireme.png'];
var otherImagesToPreload = ['images/loading_bg.png', 'images/loading.gif'];

var emails = [];
emails[0] = {
	name: 'eddyho',
	domain: 'adventdesigners.com'
};


var firstLoad = true;

$(document).ready(function(){
	$('h1.never span').replaceWith('<img src="img/never_been_a_better_time.png" />');
	$('h1.never').css('background', 'none');
	$('h1.buy-now span').replaceWith('<img src="img/buy_now.png" />');
	$('h1.buy-now').css('background', 'none');
	
	smallScreens();
	
	//preload some essential images
	$.preloadImages(otherImagesToPreload);
	
	//Opening animations. Animations are run after images have loaded
	$.preloadImages(tagImageToPreload, {
		onComplete: function(){
			$('div.blog').animate({left: 0}, 700, 'easeOutBack');
		}
	});
	$.preloadImages(topImagesToPreload, {
		onComplete: function(){
			$('nav span.page-loading').remove();
			$('nav div').animate({top: 0}, 700, 'easeOutBack');
			$('div.lines').delay(500).animate({top: 0}, 2200);
			$('h1.buy-now').prepForFade();//damn IE!
			$('h1.buy-now').css('opacity', 0).delay(1300).animate({
				opacity: 1
			}, 700);
			firstLoad = false;
		}
	});
	
	$('nav a, a.button').click(function(){
		$(this).addClass('clicked');	
		var hashLink = $(this).attr('href');
		$('<span class="loading"><img src="files/images/loading.gif" /></span>').insertAfter('nav a[href='+hashLink+']');
	});
	
	$('nav, .buttons').localScroll({
		hash: true,
		//target: '#pages',
		axis: 'y',
		stop: true,
		onBefore: function(event, el, target) {
			var hashLink = $('a.clicked').attr('href');
			$('a.active').removeClass('active');
			$('nav a[href='+hashLink+']').addClass('active');
			$(document).attr('title', $('nav a[href='+hashLink+']').attr('title'));
			
			$('div.lines').css('top', -555);
			
			$('a.big-arrow img').css({
				position: 'relative',
				top: 272
			});
			
			$('.investment').css('opacity', 0);
		},
		onAfter: function() {
			if($('a.clicked').attr('href') == '#top' && !firstLoad) {
				$('div.lines').delay(500).animate({top: 0}, 2200);
				$('h1.buy-now').css('opacity', 0).delay(1300).animate({
					opacity: 1
				}, 700);
			}
			
			if($('a.clicked').attr('href') == '#why') {
				$('a.big-arrow img').delay(300).animate({
					top: 150	
				}, 800, 'easeOutElastic');
			}
			
			if($('a.clicked').attr('href') == '#what') {
				$('.investment').delay(300).animate({
					opacity: 1	
				}, 800);
			}
			
			$('a.clicked').removeClass('clicked');
			$('.loading').remove();
		}
	});
	scrollToHash();
	
	$.each(emails, function(i, person){
		$('.email.'+person.name).html('<a href="mailto:'+person.name+'@'+person.domain+'">'+person.name+'@'+person.domain+'</a>');
	});
	
	$('.fancybox').fancybox({
		'titleShow'     : false,
		'transitionIn'	: 'elastic',
		'transitionOut'	: 'elastic',
		'easingIn'      : 'easeOutBack',
		'easingOut'     : 'easeInBack'
	});
	
	$('form label').inFieldLabels({ fadeDuration:100 });
	
	$('input,textarea').focus(function(){
		$(this).siblings('label').first().addClass('focus');
		$(this).addClass('focus');	
	});
	
	$('input,textarea').blur(function(){
		$(this).siblings('label').first().removeClass('focus');
		$(this).removeClass('focus');	
	});
	
	$('a.text-button.what').click(function(e){
		e.preventDefault();
		$('nav a[href=#what]').trigger('click');
	});
	
	$('a.text-button.contact').click(function(e){
		e.preventDefault();
		$('nav a[href=#contact]').trigger('click');
	});
	
	/*$('.text-button').mouseover(function(){
		$(this).animate({
			'background-position': '0px 0px'	
		}, 200);	
	});
	
	$('.text-button').mouseout(function(){
		$(this).animate({
			'background-position': '-10px 0px'	
		}, 200);	
	});*/
	
	/*$('.page#contact form').submit(function(e){
		e.preventDefault();
		
		var error = false; 
		
		$('#fname, #email, #message').poshytip('destroy');
		
		if($('#fname').val() == '') {
			var error = true; 
			
			$('#fname').poshytip({
				className: 'tip-twitter',
				alignTo: 'target',
				alignX: 'left',
				alignY: 'center',
				offsetX: 10,
				allowTipHover: false,
				showOn: 'none'
			}).poshytip('show');
		} 
		
		var regex = /^([a-zA-Z0-9_\.\-\+])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
		
		if(!regex.test($('#email').val())) {
			var error = true; 
			
			$('#email').poshytip({
				className: 'tip-twitter',
				alignTo: 'target',
				alignX: 'left',
				alignY: 'center',
				offsetX: 10,
				allowTipHover: false,
				showOn: 'none'
			}).poshytip('show');
		} 
		
		if($('#message').val() == '') {
			var error = true; 
			
			$('#message').poshytip({
				className: 'tip-twitter',
				alignTo: 'target',
				alignX: 'left',
				alignY: 'center',
				offsetX: 10,
				allowTipHover: false,
				showOn: 'none'
			}).poshytip('show');
		}
		
		if(!error) {
			$(this).ajaxSubmit({
				success: contactResponse
			});
		}
		
		return false;
	});*/
});
	
$(window).resize(function() {
	//scrollToHash();
	smallScreens();
});

$(window).scroll(function () {
  var inview = $('.page:in-viewport:first').attr('id');
	$('a.active').removeClass('active');
	$('nav a[href=#'+inview+']').addClass('active');
	$(document).attr('title', $('nav a[href=#'+inview+']').attr('title'));
	
	/*if(inview == 'why') {
		$('a.big-arrow img').delay(400).animate({
			top: 150	
		}, 800, 'easeOutElastic');
	}*/
});

function scrollToHash() {
	if(window.location.hash != '' && $('nav a[href='+window.location.hash+']').length != 0) {
		$('nav a[href='+window.location.hash+']').trigger('click');
		//$('a.active').removeClass('active');
		//$('nav a[href='+window.location.hash+']').addClass('active');
		//$(document).attr('title', $('nav a[href='+window.location.hash+']').attr('title'));
		//$('#pages').scrollTo(window.location.hash, 500);
	}
}

//Preload images with optional callback
//Plugin by James West - Markitable New Zealand
(function($) {
  var cache = [];
  $.preloadImages = function(images, options) {
		var loaded = 0;
  	var defaults = {
  		onComplete: function(){},
  		onImageLoad: function() {
  			loaded++;
				if(loaded == images.length) {
					options.onComplete.call();
				}
  		},
  		onImageError: function() {
  			window.log('Image not found: '+$(this).attr('src'));
  			options.onImageLoad.call(this);
  		}
  	};
  	
  	options = $.extend({}, defaults, options);
  	
	  for (var i = images.length; i--;) {
	    var cacheImage = new Image();
	    $(cacheImage).load(function(){options.onImageLoad.call($(cacheImage))});
	    $(cacheImage).error(function(){options.onImageError.call($(cacheImage))});
	    $(cacheImage).attr('src', images[i]);
	    cache.push(cacheImage);
	  }
  }
})(jQuery);

// usage: log('inside coolFunc',this,arguments);
// paulirish.com/2009/log-a-lightweight-wrapper-for-consolelog/
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) );
  }
};

// Plugin - prepForFade()
// Author: Ryan Wheale <ryan.wheale [at] gmail.com>
// If you wish to fade an element containing a transparent PNG, call this on the element first
//    IMPORTANT: Once you are ready to fade, you MUST DO SO ON A PARENT!!!
//         - DO NOT ATTEMPT TO CHANGE THE OPACITY OR FADE THE ELEMENT CONTAINING THE PNG
$.fn.prepForFade = function() {
  if(!$.support.opacity) {
    this.each(function() {
      var $this = $(this);
      var bgi = $this.css('background-image');
      if(/^url\([^\)]*\.png(?:[\?][^\)]*)?\"?\)$/.test(bgi)) {
        bgi = bgi.substring(5, bgi.length-2);
        $this.css('filter', 'progid:DXImageTransform.Microsoft.AlphaImageLoader(src="' + bgi + '", sizingMethod="crop")').css('background-image', 'none');
      }
    });
  }
  return this;
}

function smallScreens() {
	var h1height = (($('body').height()-120)/2);
	if(h1height >= 256) {
		h1height = 256;
	}
	$('h1.never').css('height', h1height);
	$('h1.buy-now').css('height', h1height);
	$('h1.never img').css('height', h1height);
	$('h1.buy-now img').css('height', h1height);
		
	var bodyHeight = $('body').height();
		
	if($('body').height() <= 600) {
		$('#top div.buttons').addClass('small-screen');
	
		var buttonsHeight = $('#top div.buttons').height();
		var offsetTop = bodyHeight-buttonsHeight-198;
		
		$('#top div.buttons').css('bottom', 'auto');
		$('#top div.buttons').css('top', offsetTop);
		
	}
	
	if($('body').height() <= 635) {
		
		var redHeight = $('div.red').height();
		var offsetTop = bodyHeight-redHeight;
		
		$('div.red').css('display', 'block');
		$('div.red').css('top', offsetTop);
		
	}
	
	if($('body').height() > 635){
		
		$('#top div.buttons').removeClass('small-screen');
		
		$('#top div.buttons').css('bottom', 0);
		$('#top div.buttons').css('top', 'auto');
		
		$('div.red').css('display', 'none');
		$('div.red').css('top', 565);
	}
	
	var textareaHeight = $('body').height()/5;
	$('#message').css('height', textareaHeight);
}

function contactResponse(responseText, statusText, xhr, $form) {

	$('#response').remove();
	$('<div id="response"></div>').insertBefore($form);
	
	var json = eval('('+responseText+')');
	if(json.error) {
		$('#response').html('<div>There seems to have been a problem with your submission, please try again later.</div>');
	} else {
		$form.clearForm();
		if(json.result.message) {
			$('#response').html('<div>'+json.result.message+'</div>');
			$('#response').show();
				setTimeout(function() {
					$('#response').fadeOut('slow', function() {
						$(this).remove();
					});
				}, 5000);
		} 
		else
		{
			$('#response').html('<div>There seems to have been a problem with your submission, please try again later.</div>');
		}
	}
	
	
	$('.spinner').hide();
}
