$(document).ready(function () {

	var keyPair = {};
	var i = 0;
	var galleries = $(".photo_gallery_small_container");
	$(galleries).each(function(){
		var top = $(this).offset().top;
		var bot = top + $(this).height();
		keyPair["top" + i] = top;
		keyPair["bot" + i] = bot;
		i++;
	});
	
	var collapsePanels = $(".collapsible_panel");
	$(collapsePanels).each(function(){
		var pos = $(this).offset().top;
		for(var n=0; n<galleries.length; n++){
			if(pos > keyPair["top" + n] && pos < keyPair["bot" + n]){
				$(this).addClass("gallery_collide");
			}
		}
	});

	$(".collapsible_content").hide();
	$(".collapsible_panel > a").click(function () {
		var content_panel = $(this).siblings(".collapsible_content");
		var pos = $(this).parent().offset().top;
		if (content_panel.is(":visible")) {
			$(this).html("Read More");
			content_panel.hide();
			
			if($(this).parent().hasClass("was_colliding")){
				$(this).parent().removeClass("was_colliding");
				$(this).parent().addClass("gallery_collide");
			}
		}
		else {
			$(this).html("Collapse");
			content_panel.show();
			pos = $(this).offset().top;
			var overlapping = false;
			for(var n=0; n<galleries.length; n++){
				if(pos > keyPair["top" + n] && pos < keyPair["bot" + n]){
					overlapping = true;
				}
			}
			
			if(overlapping){
				$(this).parent().addClass("gallery_collide");
			}
			else{
				if($(this).parent().hasClass("gallery_collide")){
					$(this).parent().removeClass("gallery_collide");
					$(this).parent().addClass("was_colliding");
				}
			}
		}

		return false;
	});
});
