$.fn.imagesLoaded = function(callback){
  var elems = this.filter('img'),
      len = elems.length;
      
  elems.bind('load',function(){
      if (--len <= 0){ callback.call(elems,this); }
  }).each(function(){
     // cached images don't fire load sometimes, so we reset src.
     if (this.complete || this.complete === undefined){
        var src = this.src;
        // webkit hack from http://groups.google.com/group/jquery-dev/browse_thread/thread/eee6ab7b2da50e1f
        // data uri bypasses webkit log warning (thx doug jones)
        this.src = "data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///ywAAAAAAQABAAACAUwAOw==";
        this.src = src;
     }
  });

  return this;
};

$(document).ready(function() {
	// Tweets
	if($(".tweet").length > 0)
	{
		$(".tweet").tweet(
		{
			username: "WeGiveBooks",
			join_text: "auto",
			avatar_size: 32,
			count: 3,
			auto_join_text_default: "we said,",
			auto_join_text_ed: "we",
			auto_join_text_ing: "we were",
			auto_join_text_reply: "we replied to",
			auto_join_text_url: "we were checking out",
			loading_text: "loading tweets..."
		});
	}

	$('.reply_btn').click(function () {
		$(this).parent().next('.comment_reply').toggle();
		return false;
	});
	
	$('.show_nested_btn').click(function () {
		$(this).parent().parent().parent().next('.nested_comments').toggle();
		return false;
	});
	
	//Detail Windows, for share, and other things.
	$('.detail_window').click(function(){
		//get the id to reference the little window
		var window_name = $(this).attr('id');
		$('.share_overlay_wrapper').hide();
		//Now toggle the window.
		
		if ($(this).data('id')) {
		  $('#'+window_name+'_details_'+$(this).data('id')).toggle();
		} else {
		  $('#'+window_name+'_details').toggle();
		}
		
		return false;
	});
	
	$('.share_overlay_close').click(function(){
		$(this).parent().parent().fadeOut();
	});
	
	$('.book_cover').mouseenter(function(){
		$(this).addClass('hovering');
		var the_book = $(this).attr('id').split('_')[1];
		setTimeout('show_book_bubble('+the_book+');',500);

	});
	
	$('.book_cover').mouseleave(function(){
		$(this).removeClass('hovering');
		
	});
	$('.book_overlay_wrapper').mouseleave(function(){
		$(this).fadeOut('fast');
		$('.book_cover').removeClass('hover_window_open');
	});
	
	$('.book_overlay_close').click(function(){
		$(this).parent().parent().fadeOut('fast');
		$('.book_cover').removeClass('hover_window_open');
	});
	
	
	$('.ajax_action').click(function(){
		//we have hidden in the alt tag everything we need to do this post.
		var attrs = $(this).attr('alt');
		if(attrs != 'dont'){//we wont do anything, for example is somone has already pushed it, ect.
			attrs = attrs.split(',');
			$.post(
				"/entity_action_histories/log_action", 
				{slug:attrs[0], entity_id_on:attrs[1]}, 
				function(data){
					if (data != 'success'){
						alert("Sorry that action was not saved. Response: "+ data);
					}
				}
			);
			//set this to don't so people dont keep pushin the damn thing
			$(this).attr('alt', 'dont');
		}
		return false;
	});
	
	$('.remove_book').click(function(){
		var book_id = $(this).attr('id').split('_')[1];
		$(this).parent().parent().fadeOut();
		$.post(
			"/entity_action_histories/remove_action", 
			{slug:'library', entity_id_on: book_id }, 
			function(data){
				if (data != 'success'){
					alert("Sorry that action was not saved. Response: "+ data);
				}
			}
		);
		
	});
	
	
	//Switch tab on the entire site
	$(".tab").click(function(){
		$(".tab").removeClass("selected");
		$(this).addClass("selected");
		$("div.tab_content").hide();
		$("#" + $(this).attr("id") + "_tab_content").show();
	});
	
	//Switch tab_menu on the entire site
	$(".sub_tab").click(function(){
		$(".sub_tab").removeClass("selected");
		$(this).addClass("selected");
		$("div.sub_tab_content").hide();
		$("#" + $(this).attr("id") + "_sub_tab_content").show();
	});
	
	//Spotlights navigation on entire site
	$(".spotlight_list .spotlight_nav").click(function(){
		$(".spotlight_list .spotlight_nav").removeClass("selected");
		var page = $(this).addClass("selected").html();
		$(".spotlight_unit").hide();
		$("#spotlight_" + page).show();
	});
	
	//Fancy box
	$(".page-media-video").fancybox({
	    'titleShow'     : true,
	    'titlePosition' : 'inside',
        'transitionIn'  : 'elastic',
        'transitionOut' : 'elastic',
        'href' : this.href,
        'type'      :'swf',
	    'swf'       : {'wmode':'transparent','allowfullscreen':'true'}
	 });
	
	$(".page-media-image").fancybox({
		'titlePosition' : 'inside'
	});

	
	//Sliding of images, videos below the campaign main image
	var marginLeft = 0;
	
	$(".other_media_wrapper img.arrow").click(function(){
		var imageStripWrapper = $(this).siblings(".image_strip_wrapper"); 
		var numPic = imageStripWrapper.find(".image_strip_unit").length;
		var imageStripSlider = imageStripWrapper.find(".image_strip_slider");
		var numSlides = Math.ceil(numPic/8);
		
		var slidingDistance = 332;
		
		if (numPic > 8) {
			if ($(this).attr("rel") == 'next') {
				marginLeft -= slidingDistance;
			} else {
				marginLeft += slidingDistance;
			}
			
			if (marginLeft == -slidingDistance*numSlides){ marginLeft = 0;}
			if (marginLeft == slidingDistance){ marginLeft = -slidingDistance*(numSlides-1);}
		}
		imageStripSlider.animate({marginLeft:marginLeft}, 500);
	})
	
	//Banner navigation
	$(".banner_nav .spotlight_nav").click(function(){
		var i = $(this).text();
		$("div.banner_unit:visible").fadeOut('fast', function(){
			$("#banner-" + i).fadeIn('fast');
		});
		$('.banner_nav .spotlight_nav').removeClass('selected');
		$(this).addClass('selected');
		
	});
	//banner autorotation if there is one, with more than 1 image
	if ($('div.banner_unit').length > 1){
	   setTimeout("rotate_banner();", 7000);
	}
	//spotlight autorotation if there is one, with more than 1 image
	if ($('div.spotlight_unit').length > 1){
	   setTimeout("rotate_spotlight();", 7000);
	}
	//handle pauses, for spotlights
	$('#spotlight-play-pause a').click(function(){
		if (!$(this).parent().parent().parent().hasClass('paused')){//we need to pause it
			$(this).addClass('selected');
			$(this).html('<img src="/theme/wgb/img/play.png" />');
			$(this).parent().parent().parent().addClass('paused');
		}else{ //we need to play it
			$(this).removeClass('selected');
			$(this).html('<img src="/theme/wgb/img/pause.png" />');
			$(this).parent().parent().parent().removeClass('paused');
		}
		
	});
	
	$('#banner-play-pause a').click(function(){
		if (!$('.banner_list').hasClass('paused')){//we need to pause it
			$(this).addClass('selected');
			$(this).html('<img src="/theme/wgb/img/play.png" />');
			$('.banner_list').addClass('paused');
		}else{ //we need to play it
			$(this).removeClass('selected');
			$(this).html('<img src="/theme/wgb/img/pause.png" />');
			$('.banner_list').removeClass('paused');
		}
		
	});
	
	
	//Show profile overlay div (on the right of main nav bar) on mouse over
	var navProfileOverlay = $("#nav_profile_overlay");
	var navProfileUsername = $("#nav_profile_username"); 
	$("#nav_profile_overlay_wrapper").hover(
		function(){
			navProfileUsername.addClass("nav_profile_hover");
			navProfileOverlay.show();
			navProfileUsername.css("z-index", "302");
			navProfileOverlay.css("z-index", "301");
		}, 
		function(){
			navProfileUsername.removeClass("nav_profile_hover");
			navProfileOverlay.hide();
			navProfileUsername.css("z-index", "2");
			navProfileOverlay.css("z-index", "1");
		}
	);
	
	//flag button 
	$('.report-comment-btn').click(function(){
		var user_id = $(this).attr('alt').split('|')[0];
		var comment_id = $(this).attr('alt').split('|')[1];
		$.post("/comments/comments/flag", {comment_id: comment_id, user_id: user_id });
		$(this).text('Flagged!');
		$(this).css('color', 'red');
		$(this).css('font-weight', 'bold');
		
		return false;
		
	});

//This is new stuff now

        $('.campaign_unit .campaign_unit_content').mouseenter(function () {
        	
        
            $(this).children('.campaign_unit_image').fadeOut('fast', 
            	function(){
            		$(this).parent().children('.unit_info').fadeIn('fast')
        		}
    		);
            //console.log($(this).children('campaign_unit_image'));
            return false;

        });
        $('.campaign_unit .campaign_unit_content').mouseleave(function () {
        	
            $(this).children('.unit_info').fadeOut('fast', 
            	function(){
            		$(this).parent().children('.campaign_unit_image').fadeIn('fast')
            		
        		}
    		);
            return false;

        });
        $('.book_unit .book_unit_content').mouseenter(function () {
        	
        
            $(this).children('.book_unit_image').fadeOut('fast', 
            	function(){
            		$(this).parent().children('.unit_info').fadeIn('fast')
        		}
    		);
            //console.log($(this).children('campaign_unit_image'));
            return false;

        });
        $('.book_unit .book_unit_content').mouseleave(function () {
        	
            $(this).children('.unit_info').fadeOut('fast', 
            	function(){
            		$(this).parent().children('.book_unit_image').fadeIn('fast')
            		
        		}
    		);
            return false;

        });


});

function rotate_banner(){
	if(!$('.banner_list').hasClass('paused')){ //if its not paused
		//how many banners we got.?
		var total_banners = $('div.banner_unit').length;
		//what banner are we on?
		var current_banner = parseInt($("div.banner_unit:visible").attr('id').split('-')[1]);
		//whats the next one?
		if(current_banner == total_banners){
			var next_banner = 1;
		}else{
			var next_banner = current_banner + 1;
		}
		//what are you waiting for.. Lets go the next one.
		$("#banner-"+current_banner).fadeOut('fast', function(){
			$("#banner-" + next_banner).fadeIn('fast');
			//change the selected nav button too!
			$('.banner_nav .spotlight_nav').removeClass('selected');
			$('#banner-nav-'+next_banner+' a').addClass('selected');
		});
	
	}
	//do this again in 10 seconds
	setTimeout("rotate_banner();", 7000);
}

function rotate_spotlight(){
	if(!$('.spotlight_list').hasClass('paused')){ //if its not paused
		if($("div.spotlight_unit:visible").length > 0){ //if any are even visible
			//how many banners we got.?
			var total_banners = $('div.spotlight_unit').length;
			//what banner are we on?
			var current_banner = parseInt($("div.spotlight_unit:visible").attr('id').split('_')[1]);
			//whats the next one?
			if(current_banner == total_banners){
				var next_banner = 1;
			}else{
				var next_banner = current_banner + 1;
			}
			//what are you waiting for.. Lets go the next one.
			$("#spotlight_"+current_banner).fadeOut('fast', function(){
				$("#spotlight_" + next_banner).fadeIn('fast');
				//change the selected nav button too!
				$('.spotlight_list .spotlight_nav').removeClass('selected');
				$('#spotlight-link-'+next_banner+' a').addClass('selected');
			});
		}//end if any are visible
	}//end if its not paused
		//do this again in 10 seconds
	setTimeout("rotate_spotlight();", 7000);
}

function show_book_bubble(the_book){
	//check if the book is still being hovered
	if($('#book_'+the_book).hasClass('hovering')){
		
		if(!$('#book_'+the_book).hasClass('hover_window_open')){
			
			$('.book_cover').removeClass('hover_window_open');
			$('.book_overlay_wrapper').hide();
			$('#book_'+the_book).addClass('hover_window_open');
			$('#book_overlay_'+the_book).show();
			
			$(".book_wrapper").css("z-index", "1");
			$('#book-container_'+the_book).css("z-index", "300");
		}
	}

}


/*
//checking for placeholder
 jQuery(function() {
	jQuery.support.placeholder = false;
	test = document.createElement('input');
	if('placeholder' in test) jQuery.support.placeholder = true;
});


 $(function() {
	if(!$.support.placeholder) { 
		var active = document.activeElement;
		$(':text').focus(function () {
			if ($(this).attr('placeholder') != '' && $(this).val() == $(this).attr('placeholder')) {
				$(this).val('').removeClass('hasPlaceholder');
			}
		}).blur(function () {
			if ($(this).attr('placeholder') != '' && ($(this).val() == '' || $(this).val() == $(this).attr('placeholder'))) {
				$(this).val($(this).attr('placeholder')).addClass('hasPlaceholder');
			}
		});
		$(':text').blur();
		$(active).focus();
		$('form').submit(function () {
			$(this).find('.hasPlaceholder').each(function() { $(this).val(''); });
		});
	}
});*/
