/* External Links Sitewide */ 
function setupExternalLinks() {
	$("a[href*=.pdf]").click(function(){
		window.open(this.href, "", "toolbar=0");
		return false;
	});
}
/* Pages With Forms */
function initializeOverlabelValidate() {
	// Overlabel
	$("#journalPg #respond label, #journalPg #search label").overlabel();

	// Validate
	jQuery.extend(jQuery.validator.messages, {
	  required: 'Required',
	  email: 'Invalid Email'
	});
	
	$('#page form').validate();

}
/* Cycle Boxes */
function initCycleBox() {
	var timeoutCallback = function() {return Math.floor(2000 + Math.random()*8000)}  // randomize timeout
	$('.cycleBox').cycle({
		fx: 'fade',
		speed: 300,
		timeoutFn: timeoutCallback
	});
}
function initBooksCycle(){
	var $slides = $('.booksCycleBox').children('img');

	// Define cycle options
	var cycleOpts = {
		speed : '400',
		timeout : 0,
		next: '.booksCycleBox img',
		pager: '.thumbNav',
		pagerAnchorBuilder: buildThumbs
	}
	// Builds thumbnails from slide images
	function buildThumbs(idx, slide) {
		return '<li><a href="#"><img src="' + slide.src + '" width="192" height="192" /></a></li>' 
	}
	$.fn.cycle.updateActivePagerLink = function(pager, currSlideIndex) { 
		$(pager).find('li').animate({'opacity' : .6}, 200).filter('li:eq('+currSlideIndex+')').animate({'opacity' : 1}, 200);
		$(pager).find('li').removeClass('activeSlide').filter('li:eq('+currSlideIndex+')').addClass('activeSlide');
	};
	// Inject pager and initialize cycle
	$('.booksCycleBox').before('<ul class="thumbNav">').cycle(cycleOpts);
}

/* Homepage Background Full Size */
(function($) {
  // Background
  $.fn.ssBg = function(options, defaults) {
    
    var defaults = {
      after : function(){}
    };
    var options = $.extend(defaults, options); 
    
    var bg = {};
    bg.e = $(this);
    
    var win = {};
    win.e = $(window);
    
    function size() {
      bg.x = bg.e.width();
      bg.y = bg.e.height();

      win.x = win.e.width();
      win.y = win.e.height();

      var ratio = {};
      ratio.x = win.x / bg.x;
      ratio.y = win.y / bg.y;
      
      var diff = {};
      diff.x = ratio.y * bg.x;
      diff.y = ratio.x * bg.y;
      
      if (diff.y > win.y) {
        
        bg.e.css({
          'height' : diff.y,
          'width' : win.x
        });
      } else {
        bg.e.css({
          'height' : win.y,
          'width' : diff.x
        });
      }
    }
    size();
    win.e.bind('resize', size);
    options.after.call();
  };
})(jQuery);

/* Homepage Fade Background */
function fadeBg(direction, duration) {
  var $bg = $('#homePg #background');
  if (duration === undefined){
    duration = 500;
  }
  if (direction === 'out' ) {
    $bg.fadeOut(duration);
    
  } else if (direction === 'in') { 
    setTimeout(function(){
      $bg.fadeTo(duration, 1);
    }, duration);      
     
  }
}

function form() {
  
	$('#contactForm').submit(function(event){
	  
	  event.preventDefault();
    
	  var errorFree = false;
	  var $this = $(this);
	  
	  $this.validate();
    
    if($this.valid() === true) {
      errorFree = true;
    }
    else{
      errorFree = false;
    }
    
		if (errorFree){
		  $this.css('opacity', 0.5);
			$('p.checkbox').css('opacity', 0.5);
		  $.ajax({
				type  : 'POST',
				cache : false,
				url		: $this.attr('action'),
				data	: $this.serialize(),
				dataType : 'html',
				success: function() {
					$('.contactFormBox form, h2').remove();
					$('.contactFormBox').append('<h2 class="cufon tyh2">Thank You</h2><img src="https://alabama.vaeplatform.com/VERB_HOSTED_IMAGE/9241"/>');
				  Cufon.replace('button', { hover: true, hover: { color: '#000'}, hoverables: { button: true } });
        	Cufon.replace('.cufon, span.moreInfo a', { fontFamily: 'TradeGothic', hover: true });
        	Cufon.now();
				}
			});
		}
	  
	  return errorFree;
	  
	});
}

function close() {
  $('.sidebars').removeClass('stayWhite').show();
}

/* Fancy Box */
function initFancyBox(){

	// Store View Size Chart
	$(".viewSizeChart a").fancybox({ 
		'padding' : 10,
		'hideOnContentClick' : true, 
		'showCloseButton' : true,
		'overlayColor' : '#ebeaea',
		'overlayOpacity' : '0.8',
		'autoDimensions' : false,
		'width' : 740,	
		'height' : 500,
		'scrolling' : 'no'
	});

	// Press Page
	function formatPressTitle(title, currentArray, currentIndex, currentOpts) {
		// the link for the article download is in the h3
		var downloadLink = $('#pressPg #page li h3 a, #archivePg li span.downloadLink a').attr('href');
	    //return '<a href="'+ downloadLink +'" class="overlayDownloadLink" target="_blank">Download PDF</a>';
	}
	var fancyOpts = {
		'padding' : 24,
		'hideOnContentClick' : false,
		'showCloseButton'	: true,
		'titlePosition' 	: 'inside',
		'titleFormat'		: formatPressTitle,
		'overlayColor' : '#ebeaea',
		'overlayOpacity' : '0.8'
	}
	$("#pressPg #page ul.lazyload li > a.fb").fancybox(fancyOpts);
	$("#archivePg a[rel=gallery]").fancybox(fancyOpts);
}
function setupHomepage(){
	$('#homePg #sidebarRight, #homePg #sidebarLeft').hide();
    $('#initialLogo').click(function (e) {
		  e.preventDefault();
  		duration = 500;
  		$(this).stop().fadeTo(500, 0).addClass('stayGone').siblings('div').fadeIn(duration);
    });

    $('#homePg .sidebars').hover(function () {
        $(this).addClass('whiteOn');
        }, function () {
        $(this).removeClass('whiteOn');
    });

	$('#homePg .sidebars').click( function() {
		$(this).addClass('stayWhite').siblings('div').fadeOut(500,0);
    });
	$('#homePg.studioStyle #sidebarRight').addClass('stayWhite').fadeIn(500);
}

function setupLazyLoad(){
	if(jQuery.fn.lazyload) {
		$("#page .lazyload img").lazyload({ 
			threshold : 0,
			placeholder: "lib/css/images/clear.gif",
			effect : "fadeIn"
		});
	}
}
/* Force iphone to show lazyload images */
function iphoneFix() {
	var agent = navigator.userAgent.toLowerCase();
	var is_iphone = (agent.indexOf('iphone')!=-1);
	if (is_iphone) { 
		$('#page .lazyload img').trigger("appear");
	 }
}

/* Document Ready */
$(document).ready(function(){
  
  $('.contactFtBtn a, .lightbox a').fancybox({
		'hideOnContentClick' : false,
		'showCloseButton' : true,
		'enableEscapeButton' : true,
		'type' : 'ajax',
		'overlayColor' : '#ebeaea',
		'overlayOpacity' : '0.8',
		'onComplete' : form,
		'onClosed' : close
    });
	
  // external links
	$('a[rel=external]').click(function(){
		window.open(this.href);
		return false;   
	});
	
	/* Store Page Single Item */
	$(".relatedItems li:nth-child(3n)").addClass('last'); // class to remove margin on every 3rd (last) thumbnail in the set

	/* Workshop Page */
	$(".DIYkits ul li:nth-child(3n)").addClass('last'); // class to remove margin on every 3rd (last) thumbnail in the set

	/* Journal page add class */
	$('#journalPg #page div.post:first-child').addClass('firstPost');
	
	/* Events Page */
	$('#eventsPg #page li:last-child').addClass('last');

	//setupHomepage();
	setupLazyLoad();
	initializeOverlabelValidate();
	setupExternalLinks();
	initCycleBox();
	initBooksCycle();
	initFancyBox();
	iphoneFix();
	
	
	// Same As
  $('.sameAs').click(function() {
    
      $('#shippingInfo input:not(#sameAs)', ':visible', document.body).each(function(i) { 
            $(this).val( $('#billingInfo input').eq(i).val() );
            //fetch select values
            var billCountry = $("#billing_country").val();
            var billState = $("#billing_state_US").val();
            //set select values
            $("#shipping_country").val(billCountry);
            $("#shipping_state_US").val(billState);  

          });
  });
}); 


/* Window Ready */
$(window).bind('load', function(){
  /* Background */
	$('#background').ssBg({
	  after : function(){
	    fadeBg('in', 800);                
	  }
	});
});
