jQuery(document).ready(function($) {
	$('div#wrapper').css('display','block');
	$("a[href^=http]").each( function(){
		if(this.href.indexOf(location.hostname) == -1) {
			$(this).attr('target', '_blank');
		}
	});
	
	var preloadloader = $('<img />').attr('src', '/wp-content/themes/chdirector/img/ajax-loader.gif');
	$('div.production-list h3 a').each(function() {
		$(this)
			.addClass('panel')
			.bind('click', function() {
				if( $(this).is('.open') ) {
					$(this)
						.removeClass('open')
						.addClass('closed')
						.parent()
						.next()
						.slideUp(500);
				} else if ( $(this).is('.closed') ) {
					$(this)
						.removeClass('closed')
						.addClass('open')
						.parent()
						.next()
						.slideDown(500);
				} else {
					var target = $(this).attr('href') + ' div.post_content';

					$(this)
						.addClass('loading')
						.parent()
						.after('\n\t\t\t\t\t\t\t<div class="ajax_post"></div>')
						.next()
						.load(target, function(responseText, textStatus, XMLHttpRequest){
							if( textStatus === 'success' ) {
								$(this)
									.prev()
									.children('a')
									.removeClass('loading')
									.addClass('open');
								$(this)
									.children('div.post_content')
									.slideDown(500)
									.children('img.album-preview').each(function(){
										$(this).linkgalleries(this);
									});
								$("a[href^=http]").each( function(){
										if(this.href.indexOf(location.hostname) == -1) {
											$(this).attr('target', '_blank');
										}
									});
								
							} else {
								window.location= $(this).prev().children('a').attr('href');
							}
						});
				}
				return false;
			});
	});
	
	var directoralbum = "http://hatheadstudios.net/wp-content/themes/chdirector/production-gallery.php?http://galleries.hatheadstudios.net/chdirector/images.php?album=";
	$('img.album-preview').each(function(){
		$(this).linkgalleries(this);
	});
});

jQuery.fn.extend({
	linkgalleries: function(target) {
		var directoralbum = "http://hatheadstudios.net/wp-content/themes/chdirector/production-gallery.php?http://galleries.hatheadstudios.net/chdirector/images.php?album=";
		var targetlink = directoralbum + jQuery(target).attr('id').replace('gallery-','');
		jQuery(target)
		.wrap("<div class='wp-caption alignright'></div>")
		.after("<p class='wp-caption-text'>Click the image to view this show's gallery.</p>")
		.wrap("<a class='iframe apigallery-link' href='" + targetlink + "'></a>")
		.parent()
		.fancybox({
			'padding' : 0,
			'frameWidth' : 900,
			'frameHeight' : 620,
			'overlayOpacity' : .6
		});
	}
});