$(document).ready(function()
{
	/* Outbound Tracking */
	$("a[href^=http]").each(function(){
      if(this.href.indexOf(location.hostname) == -1) {
        $(this).attr('target', '_blank');
		$(this).bind('click', function(){
		  _gaq.push(['_trackEvent', 'outgoing', 'click', '/outgoing/' + $(this).attr('href')]);
		});
      }
    });

	
	/* See More Buttons Recipes/Tutorials */
	if ($('.recipeList').length > 0) {
		$('.recipeList').each(function() {
		  $(this).has('.seeMore').append('<li class="toggleRecipes"><a onClick="_gaq.push([\'_trackEvent\', \'Interaction\', \'See More/Less\']);return false;" >See More</a></li>');  
		});
		
		$('.toggleRecipes').bind('click', function(){
		  $(this).parents('ul').children('.seeMore').slideToggle();
		  if (!$(this).children('a').hasClass('active')) { 
			$(this).children('a').addClass('active');
			$(this).children('a').text('See Less');
		  } else {
			$(this).children('a').removeClass('active');
			$(this).children('a').text('See More');
		  }
		});
	}
	
	/* Image Borders and Pinterst Button */
	if ($('.post,.default').length > 0) { 
	
	  /* Add IMG Border */
	  $('a .size-full,a .size-medium,a .size-large,a .size-full').unwrap();
	  $('.size-full,.size-medium,.size-large,.size-full').each(function (){
		  $(this).wrap('<div class="imageBorder" />');
		  $(this).after('<div onClick="_gaq.push([\'_trackEvent\', \'Interaction\', \'Pin It\']);return false;" class="pinButton"><a href="http://pinterest.com/pin/create/button/?url='+window.location.href+'&media='+$(this).attr('src')+'" class="pin-it-button" count-layout="vertical">Pin It</a></div>');
	  });
	  
		$('.imageBorder').bind({
		  mouseenter: function() {
			$(this).children('.pinButton').fadeIn('fast');
		  },
		  mouseleave: function() {
			$(this).children('.pinButton').fadeOut('fast'); 
		  }
		});
	  
		// Add Pinterest Code
		window.PinIt = window.PinIt || { loaded:false };
		if (window.PinIt.loaded) return;
		window.PinIt.loaded = true;
		function async_load(){
			var s = document.createElement("script");
			s.type = "text/javascript";
			s.async = true;
			s.src = "http://assets.pinterest.com/js/pinit.js";
			var x = document.getElementsByTagName("script")[0];
			x.parentNode.insertBefore(s, x);
		}
		if (window.attachEvent)
			window.attachEvent("onload", async_load);
		else
			window.addEventListener("load", async_load, false);
		}
	
	// Enables SOTW Badge Selection
	if ($('.badgeWrap').length > 0) {
	  sotwBadge();
	}
	
	// Load Showcase
	$("#showcase").awShowcase(
	{
		content_width:			932,
		content_height:			400,
		fit_to_parent:			false,
		auto:					true,
		interval:				5000,
		continuous:				true,
		loading:				true,
		arrows:					true,
		buttons:				false,
		btn_numbers:			true,
		keybord_keys:			true,
		mousetrace:				false, /* Trace x and y coordinates for the mouse */
		pauseonover:			true,	
		stoponclick:			false,
		transition:				'fade', /* hslide/vslide/fade */
		transition_delay:		0,
		transition_speed:		1000,
		show_caption:			'onload', /* onload/onhover/show */
		thumbnails:				true,
		thumbnails_position:	'outside-last', /* outside-last/outside-first/inside-last/inside-first */
		thumbnails_direction:	'horizontal', /* vertical/horizontal */
		thumbnails_slidex:		1, /* 0 = auto / 1 = slide one thumbnail / 2 = slide two thumbnails / etc. */
		dynamic_height:			false, /* For dynamic height to work in webkit you need to set the width and height of images in the source. Usually works to only set the dimension of the first slide in the showcase. */
		speed_change:			true, /* Set to true to prevent users from swithing more then one slide at once. */
		viewline:				false, /* If set to true content_width, thumbnails, transition and dynamic_height will be disabled. As for dynamic height you need to set the width and height of images in the source. */
		custom_function:		infoPop /* Define a custom function that runs on content change */	});

	/* Allow click to load post */
	$(".showcase-content-container").live('click', function() {
		var posturl = $(this).find("a[href]").attr('href');
		window.location = posturl
	});
	
	/* Track Click Interaction */
    var next_post = "_gaq.push([\'_trackEvent\', \'Interaction\', \'Next Post\']);return false;";
	var prev_post = "_gaq.push([\'_trackEvent\', \'Interaction\', \'Prev Post\']);return false;";
    // create a function from the "js" string
    var nextclick = new Function(next_post);
	var prevclick = new Function(prev_post);
	
    // clears onclick then sets click using jQuery
    $(".showcase-arrow-previous").attr('onclick', '').click(nextclick);
	$(".showcase-arrow-next").attr('onclick', '').click(prevclick);
	
	// Something Sweet Timer
	setTimeout(function() {
	  $('.somethingSweet').slideToggle();
	}, 90000); // 20 Second Delay
	
	/* Create A Subscription timer with cookie function 
	setTimeout(function() {
		$.getScript('/wp-content/themes/sweetopia_two/js/jquery.cookie.min.js', function(){
			if ($.cookie('subscription_offer') != '1') {
					$('.activate_sub_box').click();
				$.cookie('subscription_offer', '1', { expires: 20 });
			}
		});
	}, 20000); // 20 Second Delay*/
	
	// Subscribe Box Drop Down
	$('.activate_sub_box').bind('click', function(){

		function removeSubBox() {
			$('#subscribeBox').fadeOut('fast', function(){
				$('#subscribeOverlay').fadeOut('fast');
			});
		}

		$('#subscriptionBox').load('/wp-content/themes/sweetopia_two/includes/subscribe.html', function() {
			
			// Animate Subscribe Box and Overlay
			$('#subscribeOverlay').fadeIn('fast',function(){
				$('#subscribeBox').centerScreen();
				$('#subscribeBox').fadeIn('fast');
			});

			// Bind Click Close & Click Off to exit
			$('#subscribeClose,#subscribeOverlay').bind('click', function() {
				removeSubBox();
				$('#subscribeClose,#subscribeOverlay').unbind('click', false); // Unbind After Box is gone
			});
			
			// Bind Escape Key to exit
			$(document).bind('keyup', function(e) {
				if (e.keyCode == 27) { 
					removeSubBox();
				} 
				$(document).unbind('click', false);
			});
			
			$('.activate_sub_box').unbind('click',false);
		});
	});

	// Toggle Trackbacks & Pingbacks
	$('#toggleTrackback').bind('click', function(){
	  $('.pingbacklist').slideToggle("slow");
	  if (!$(this).hasClass('active')) {
		$(this).text('Hide Pingbacks & Trackbacks');
		$(this).addClass('active');
	  } else {
		$(this).text('Show Pingbacks & Trackbacks');
		$(this).removeClass('active');
	  }
	});

if ($('#sidebar').length != 0) { 

	// Wait until the last item in the sidebar becomes invisible
	// Change position of certain content items to fill blank space
	$(window).bind('scroll', function(){
	  if(isVis($('#sidebar').last())) {
		$('.stickyItem').css('position', 'static');
	  } else {
		$('.stickyItem').css('position', 'fixed');
		$('.stickyItem').css('top', 15);
	}
	});
	
	if ($("#decoratorInfo").length != 0) { 
	  $('#decoratorInfo').masonry();
	}
}

if( $('#sotwFaq').length > 0 ) {
	  sotwFaq();
	}
});

/****************
 * End DOM ready
 ***************/
 
// SOTW Badge Selection
  function sotwBadge() {
	$('.badgeItem').bind({
	  click: function() {
	    if ($('.badgeItem').hasClass('active')) {
		  return false;
		} else {
		var badge_url = 'http://sweetopia.net/wp-content/themes/sweetopia_two/images/sotw/';
		var badge_id = $(this).attr('rel');
		$('.badgeWrap').append('<div id="sotwBadgeCode">&nbsp;Copy &amp; Paste this HTML to your website <br /><textarea class="sotwCodeBox" rows="7" cols="35"><a href="http://sweetopia.net/sweet-of-the-week" title="I won Sweetopia\'s Sweet of the Week"><img alt="Sweet of the Week Winner" src="'+badge_url+badge_id+'.jpg"</a></textarea></div>');
		$('.badgeWrap').append('<a href="javascript:void(0);" id="sotwCancel">Go Back</a>');
		$('.badgeItem').not(this).animate({width: 'toggle'}, function(){
		  $('#sotwCancel,#sotwBadgeCode').fadeIn('slow');
		});
		$(this).addClass('active');
		$('#sotwCancel').click(function(){
		  $('.badgeItem').not('.active').animate({width: 'toggle'});
		  $('#sotwBadgeCode').fadeOut('fast', function(){$(this).remove();})
		  $(this).fadeOut('fast', function(){$(this).remove();})
		  $('.active').fadeTo('fast', 0.65, function(){
		  	$(this).removeClass('active');
		  });
		});
		} // End If
	  },
	  mouseenter: function() {
		$(this).not('.active').fadeTo('fast', 1);
	  },
	  mouseleave: function() {
		$(this).not('.active').fadeTo('fast', 0.65); 
	  }
	});
  } 
 
// Center the Sub Box
jQuery.fn.centerScreen = function(loaded) { 
	var obj = this; 
	if(!loaded) { 
			obj.css('top', $(window).height()/2-this.height()/2); 
			obj.css('left', $(window).width()/2-this.width()/2);
			$(window).resize(function() { obj.centerScreen(!loaded); }); 
	} else { 
			obj.stop(); 
			obj.animate({ top: $(window).height()/2-this.height()/2, left: $(window).width()/2-this.width()/2}, 200, 'linear'); 
	} 
}

// Check if an element is in view
function isVis(elem) {
    var docViewTop = $(window).scrollTop(),
        docViewBottom = docViewTop + $(window).height(),
        elemTop = $(elem).offset().top,
     	elemBottom = elemTop + $(elem).height();
   //Is more than half of the element visible
   return ((elemBottom >= docViewTop) && (elemTop <= docViewBottom));
}

/* Animate post info bar */
var lastId
function infoPop(id) {
	if (!lastId) {lastId = id}
	$('#showcase-content-'+lastId+' .postInfoWrap').fadeOut(250);
	$('#showcase-content-'+id+' .postInfoWrap').slideDown(1000);
	lastId = id;
}	

/* SOTW Badge Selection */
function sotwBadge() {
	$('.badgeItem').bind({
	  click: function() {
	    if ($('.badgeItem').hasClass('active')) {
		  return false;
		} else {
		var badge_url = 'http://sweetopia.net/wp-content/themes/sweetopia_two/images/sotw/';
		var badge_id = $(this).attr('rel');
		$('.badgeWrap').append('<div id="sotwBadgeCode">&nbsp;Copy &amp; Paste this HTML to your website <br /><textarea class="sotwCodeBox" rows="7" cols="35"><a href="http://sweetopia.net/sweet-of-the-week/#winners" title="I won Sweetopia\'s Sweet of the Week"><img alt="Sweet of the Week Winner" src="'+badge_url+badge_id+'.jpg"</a></textarea></div>');
		$('.badgeWrap').append('<a href="javascript:void(0);" id="sotwCancel">Go Back</a>');
		$('.badgeItem').not(this).animate({width: 'toggle'}, function(){
		  $('#sotwCancel,#sotwBadgeCode').fadeIn('slow');
		});
		$(this).addClass('active');
		$('#sotwCancel').click(function(){
		  $('.badgeItem').not('.active').animate({width: 'toggle'});
		  $('#sotwBadgeCode').fadeOut('fast', function(){$(this).remove();})
		  $(this).fadeOut('fast', function(){$(this).remove();})
		  $('.active').fadeTo('fast', 0.65, function(){
		  	$(this).removeClass('active');
		  });
		});
		} // End If
	  },
	  mouseenter: function() {
		$(this).not('.active').fadeTo('fast', 1);
	  },
	  mouseleave: function() {
		$(this).not('.active').fadeTo('fast', 0.65); 
	  }
	});
  }
  
// SOTW FAQ Toggler
function sotwFaq() {
  $('.sotwQ').bind('click', function(){
	if ($(this).next('.sotwA').hasClass('active')) return false;
	$('.active').removeClass('active').slideToggle();
	$(this).next('.sotwA').addClass('active').slideToggle('fast');
  })
}
