var is_ipad = navigator.userAgent.match(/iPad/i) != null;

$(document).ready(function() {
	
	/**
	 * Menu hover states
	 */
	$('#nav > LI').mouseenter(function() {
		$('#nav > LI A.nav_hover').removeClass('nav_hover');
		$('#nav > LI.menu_hover').removeClass('menu_hover');
		$(this).children('a').addClass('nav_hover');
		$(this).addClass('menu_hover');
		$('.blocker').hide();
		// Don't show is body is full width and menu item is empty
		if ( ( ! $('BODY').hasClass('full_width')) || ( ! $(this).hasClass('empty'))) {
			$(this).children('.blocker').show();
		}
	});
	$('#nav > LI').mouseleave(function() {
		$(this).children('a').removeClass('nav_hover');
		$(this).removeClass('menu_hover');
		$(this).children('.blocker').hide();
	});

	/**
	 * Share box
	 */
	var share_form_default = $('#share_form').html();
	var timeout = false;
	$('#share_link').mouseenter(function() {

		/* Close the other one */
		$('#favorites_link').removeClass('favorites_hover');
		$('#favorites').hide();
		
		/* Reset contents (if form has been previously submitted, we want all our fields back) */
		$('#share_form').html(share_form_default);
		
		/* Re-bind events after creating new html */
		$('#share_form_submit').click(share_form_submit);
		$('.default_text').each(set_default_text);
		
		$('#share').show();
		$(this).addClass('share_hover');
	});
	$('#share_wrapper').mouseenter(function() {
		// cancel timeout function ;
		clearTimeout(timeout);
	});
	$('#share_wrapper').mouseleave(function() {
		//$('#share_link').removeClass('share_hover');
		//$('#share').hide();
		timeout = setTimeout("$('#share_link').removeClass('share_hover');$('#share').fadeOut();",3000);
	});
	$('#share_close').click(function() {
		$('#share_link').removeClass('share_hover');
		$('#share').hide();
	});
	
	
	/**
	 * Share form submit
	 */
	$('#share_form_submit').click(share_form_submit);
	
	

	/**
	 * Favorites box
	 */
	$('#favorites_link').mouseenter(function() {
		/* Close the other one */
		$('#share_link').removeClass('share_hover');
		$('#share').hide();
		$('#favorites').show();
		$(this).addClass('favorites_hover');
	});
	$('#favorites_wrapper').mouseenter(function() {
		// cancel timeout function ;
		clearTimeout(timeout);
	});
	$('#favorites_wrapper').mouseleave(function() {
		//$('#favorites_link').removeClass('favorites_hover');
		//$('#favorites').hide();
		timeout = setTimeout("$('#favorites_link').removeClass('favorites_hover');$('#favorites').fadeOut();",3000);
	});
	$('#favorites_close').click(function() {
		$('#favorites_link').removeClass('favorites_hover');
		$('#favorites').hide();
	});
	
	
	/**
	 * Close share/favs if page is clicked anywhere
	 */
	$(document).click(function() {
		$('#share_link').removeClass('share_hover');
		$('#share').fadeOut();
   		$('#favorites_link').removeClass('favorites_hover');
   		$('#favorites').fadeOut();
	});
	$("#share_wrapper").click(function() {
	    return false;
	});
	$("#favorites_wrapper").click(function() {
	    return false;
	});

	
		
	/**
	 * Search form
	 */
	$('#search_form .search_box').focus(function() {
		$(this).addClass('search_box_focus');
		$('#search_form').removeClass('search_box_hover');
	});
	$('#search_form .search_box').blur(function() {
		$(this).removeClass('search_box_focus');
		$('#search_form').addClass('search_box_hover');
	});
	$('#search_form').mouseenter(function() {
		if ( ! $(this).find('.search_box').hasClass('search_box_focus')) {
			$(this).addClass('search_box_hover');
		}
	});
	$('#search_form').mouseleave(function() {
		$(this).removeClass('search_box_hover');
	});	
	$('.submit_button').mouseenter(function() {
		$(this).attr('src', '/assets/img/search_box_bg_hover.png');
	});
	$('.submit_button').mouseleave(function() {
		$(this).attr('src', '/assets/img/search_box_bg.png');
	});


	//search results form
	$('#search_results_form .search_box').focus(function() {
		$(this).addClass('search_box_focus');
		$('#search_results_form').removeClass('search_box_hover');
	});
	$('#search_results_form .search_box').blur(function() {
		$(this).removeClass('search_box_focus');
		$('#search_results_form').addClass('search_box_hover');
	});
	$('#search_results_form').mouseenter(function() {
		if ( ! $(this).find('.search_box').hasClass('search_box_focus')) {
			$(this).addClass('search_box_hover');
		}
	});
	$('#search_results_form').mouseleave(function() {
		$(this).removeClass('search_box_hover');
	});	
	

	/**
	 * Sub Menu hover states
	 */
	$('.subnav > LI').mouseenter(function() {
		$('#my_tooltip').hide();
		$(this).addClass('subnav_hover');
	});
	$('.subnav > LI').mouseleave(function() {
		$(this).removeClass('subnav_hover');
	});
	

	/**
	 * Alpha jump menus
	 */
	 $('.letter_nav').each(function() {

		// Letter navigation
		 $('.letter_nav LI').click(function() {
		 
		 	var letter 		= $(this).find('A').attr('letter');
		 	var locations	= $('DIV[alpha="'+letter+'"]');
		 	
		 	if (locations.length) {
				$.scrollTo(locations[0], 500,{offset: {top:-40} });
		 	} else {
		 		// No listings, go to the previous letter
				$(this).prev().click();
		 	}
	
		 	return false;
		 });
		 
		 // Show/hide back to top nav
		 $(window).scroll(function() {
		
			var threshold  = 550;
			var scrolltop  = $(window).scrollTop();
			var scroll_div = '<div id="to_the_top"><a href="#">To The Top</a></div>';
			
			if (scrolltop > threshold) {
				if ($('#to_the_top').length === 0) {
					$('#content').append(scroll_div);
					$('#to_the_top').fadeIn();
					
					$('#to_the_top').click(function() {
						$.scrollTo(0,500);
						return false;
					});
				}
			} else {
				if ($('#to_the_top').length) {
					$('#to_the_top').fadeOut('fast', function() {
						$('#to_the_top').remove();
					});
				}
			}
		});
		
		

	 });
	 
	 
	if (!is_ipad) {
	
		/**
		 * Show/hide tooltip
		 */
		$('.tooltip_trigger').mouseenter(function(e) {
		
			console.log('mouseenter');
		
			$(this).children('.tooltip').fadeIn('fast');
			
			/* Set top to: parent top position - child height - 0px; */
			$('.tooltip').css('top', ($(this).position().top - 
				$(this).children('.tooltip').outerHeight() - 0) + 'px');
				
			/* Set left to: parent left pos + half parent width - half child width */
			$('.tooltip').css('left', ($(this).position().left) + ($(this).outerWidth()/2) - 
				($(this).children('.tooltip').outerWidth()/2) + 'px');
				
			/* Add the arrow (if it doesnt already exist) */
			if ( ! $(this).children('.tooltip').children('.arrow').length > 0) {
				$(this).children('.tooltip').append('<span class="arrow"></span>');
			}
			
			/* Show tootip */
			$(this).children('.tooltip').fadeIn('fast');
			
		});
		$('.tooltip_trigger').mouseleave(function() {
			$(this).children('.tooltip').delay(100).fadeOut('slow');
		});	
		
	
		/** 
		 * Altered version of the tooltip function for the image carousel images
		 * This creates tooltip outside current element, and uses alt text for tooltip text
		 */

		$('.tooltip_trigger_carousel').mouseenter(function(e) {
			
			// Remove tooltip div if there's one already there somewhere
			$('#my_tooltip').remove();
		
			// Get alt tag text for tooltip
			var my_text = $(this).find('img').attr('alt');
			
			// Create tooltip element
			$(this).parents('.image_carousel').append(
				'<span class="tooltip" id="my_tooltip">'+my_text+'<span class="arrow"></span></span>'
			);
			
			// Set top position to image_carousel top + 20 px
			$('#my_tooltip').css('top', 
				($(this).parents('.image_carousel').position().top)-25);
			
			// set position to:
			// absolute img pos, minus half tooltip size, plus 33 (half thumb size)
			$('#my_tooltip').css('left', 
				($(this).offset().left) - ($('#my_tooltip').outerWidth() / 2) + 33
			);
				
			// Show tooltip
			$('#my_tooltip').fadeIn('fast');				
		});
		
		/* Hide image carousel tooltip */	
		$('.tooltip_trigger_carousel').mouseleave(function() {
			
			// Fade out slowly after short delay (0.3s)
			$('#my_tooltip').delay(300).fadeOut('slow');
		});	
	
	} /* End if (!is_ipad) {...} */


	
	/** 
	 * Welcome screen image changer 
	 */
	$('#welcome #welcome_nav A').click(function() {	
		
		// Stop cycling through
		if (typeof(interval_id) != 'undefined') {
			clearInterval(interval_id);
		}
		
		// Don't do anything if it's currently visible
		if ($(this).hasClass('active')) return false;

		// Remove all hover classes
		$('#welcome #welcome_nav A.active').removeClass('active');
		// Add hover class to link
		$(this).addClass('active');
		
		var pos = $(this).attr('position');

		// Show this slide if not already visible
		if ((slide = $('#welcome #welcome_slides #welcome_slide_'+pos))) {
		
			$('#welcome #welcome_slides LI:visible').fadeOut();
			$(slide).fadeIn();
		}
		
		// Restart timer
		interval_id = setInterval('slide_cycle()', 6500);

		return false;
	});	

	

	/**
	 * The following two functions control the left/right links for 
	 * the image carousel
	 */
	$('.left_link').click(left_link);
	$('.right_link').click(right_link);
	
	
	
	/**
	 * This functions sets and updated the # or # label for the video carousel
	 */
	function update_pagination_links(carousel, shift_width) {
	
		// We're actually being passed one of the links, so let's get the carousel element
		carousel = carousel.parents('.image_carousel');
		
		// now we need outside width, inside width and offset
		var outside_width = carousel.find('.outside').width(); // width of outside box (910)
		var content_width = carousel.find('.inside').width(); // width of content (2301)
		var content_position = carousel.find('.inside').position().left // position of content (0/-864/864/etc)
		
		// calculate how many pages in total
		var total_pages = Math.ceil((content_width)/(outside_width+50)); // extra space?
			// ecah LI elemtn is adding 3 px extra space
		
		// calculate current page
		var final_position = ((-1 * content_position) + shift_width);
		var current_page = Math.floor((final_position / (outside_width+20))+1);
		
		/*
		alert(
			'outside_width: ' + outside_width + '\n' +
			'content_width: ' + content_width + '\n' +
			'final_position: ' + final_position
		);
		*/
		$('#videos_current_page').html(current_page);
		$('#videos_total_pages').html(total_pages);
	}
	
	
	// Run this on page load for each image carousels 
	$('.image_carousel').each(function() {
		update_pagination_links($(this).find('.inside'), 0);
	});
		
		
	// Run this on page load for each image carousels - will disable necessary links	
	$('.image_carousel').each(function() {
		disable_carousel_links($(this).find('.inside'));
	});
		
	
	/**
	 * For each image carousel on the page, see if supplied number of 
	 * images are smaller than space allocation. If so, remove the left
	 * and right links
	 */
	$('.image_carousel').each(function() {
		
		// get margin
		if ($(this).hasClass('videos')) {
			var margin = 26;
		} else {
			var margin = 10;
		}

		var inside = ($(this).find('.inside').width() - margin); // Subtract 10 for margin
		var outside = $(this).find('.outside').width() ;
		
		if (inside < outside) {
			$(this).find('.left_link').remove();
			$(this).find('.right_link').remove();
		}
	});
	
		

	
	
	/**
	 * Calendar popup
	 */
	$('.popup_link').click(function() {
		
		var event 	= $(this).parents('LI');
		var details	= event.children('.popup_details');	
		var popup	= $('#popup');
		
		// No details, continue to href
		if (!details) return true;
		
		// No popup, continue but it should really just create DOM element
		if (!popup) return true;
		
		var title 	= details.find('.popup_details_title').html();
		var content = details.find('.popup_details_content').html();
		
		$('#popup_header_title').html(title);
		$('#popup_content').html(content);	

		// Use scroll position, window height and lightbox height to center lightbox on page
		var window_height 	= $(window).height();
		var scroll_top 		= $(window).scrollTop();
		var popupHeight 	= $('#popup').height();
		
		// Position is: scroll offset plus half the difference between popup size and window height		
		var top_pos 		= (scroll_top + ((window_height - popupHeight ) / 2 ));
		
		// Make sure popup is not off-screen
		if (top_pos <= 1) {
			top_pos = 1;
		}
		
		$('#popup').css('top', top_pos + 'px');	

		// Show popup
		$('#popup').fadeIn();
				
		return false;
	});
	$('#popup_close').click(function() {
		// Hide popup
		$('#popup').fadeOut();
		return false;
	});
	
	
	/**
	 * For all default values in inputs
	 */
	$('.default_text').each(set_default_text);
	

	/**
	 * Mailing list form submit
	 */
	/*
	$('#mailing_list_submit').click(function () {
		
		// Submit form
		$.ajax({
		    type: "post", 
		    url: $('#mailing_list').attr('action'),
		    data: $('#mailing_list').serialize(), 
		    complete: function (data, text) {
		       $('#mailing_list').html('Thanks! You have been added to the mailing list.');
		    }
		});

		return false;
	});
	*/
	
	
	/**
	 * Control subnav tabset
	 */
	$('.subnav_tabset').each(function() {
		
		var tabset 		= $(this);
		var tab_navs 	= $(this).find('.subnav LI');
		var tab_content	= $(this).find('.subnav_tabs .tab');

		$(tab_navs).click(function() {

			var pos = $(this).parent().children().index($(this));
			
			$(tab_navs).find('.active').removeClass('active');
			$(this).find('A').addClass('active');
			
			$(tab_content).hide();
			$(tab_content[pos]).show();
			
			return false;
		});
	});
	
	// Adjust home promo sizes
	var max_home_promo = 0;
	$('.home_promo_wrapper').each(function() {
		if ($(this).height() > max_home_promo) {
			max_home_promo = $(this).height();
		}
	});
	$('.home_promo_wrapper').css('height',(max_home_promo+15) + 'px');
	
	
	// Adjust video thumb sizes
	var max_videos_li = 0;
	$('.videos LI').each(function() {
		if ($(this).height() > max_videos_li) {
			max_videos_li = $(this).height();
		}
	});
	$('.videos LI').css('height',(max_videos_li+15) + 'px');
	


	// Cycle through slideshow
	var path = location.pathname;
	var filename = path.substr(path.lastIndexOf("/")+1,path.length);
	
	if (filename == '') {
		var interval_id = setInterval('slide_cycle()', 4000);
	}
	

	
});


/**
 * Function to cycle through slides
 */
function slide_cycle() {
	
	// Get position of currently visible slide
	var pos = parseInt($('#welcome_nav LI A.active').attr('position'));

	// If less than total slide count increment by 1, otherwise reset to 1
	if (pos < $('#welcome_nav LI A').size()) {
		pos += 1;
	} else {
		pos = 1;
	}
	
	// Run the change_slide function
	change_slide(pos);
}


/**
 * Function to change slide and active states
 */
function change_slide(pos) {
	
	// Remove all hover classes
	$('#welcome_nav A.active').removeClass('active');
		
	// Add hover class to link
	$('#welcome_nav A[position="'+pos+'"]').addClass('active');

	// Show this slide if not already visible
	if ((slide = $('#welcome #welcome_slides #welcome_slide_'+pos))) {
		
		$('#welcome #welcome_slides LI:visible').fadeOut();
		$(slide).fadeIn();
	}
}





function share_form_submit() {
	
	var errors = [];
	var errors_text = '';
	var share_form = $('#share_form');
	
	if (share_form.find('INPUT[name=friend_name]').val() == "Friend's Name") {
		errors.push("Please enter your friend's name");
	}
	if (share_form.find('INPUT[name=friend_email]').val() == "Friend's E-mail") {
		errors.push("Please enter your friend's email");
	}
	if (share_form.find('INPUT[name=your_name]').val() == "Your Name") {
		errors.push("Please enter your name");
	}
	if (share_form.find('INPUT[name=your_email]').val() == "Your E-mail") {
		errors.push("Please enter your email");
	}
	
	if (errors.length > 0) {	
		for (var i in errors) {
			errors_text = errors_text + '\n - ' + errors[i];
		}
		alert('Please correct the following errors:\n ' + errors_text);
		return false;
	} else {
	
		share_form.find('INPUT[name=path]').val(document.location.href);
		
		$.ajax({
		    type: "post", 
		    url: share_form.attr('action'),
		    data: share_form.serialize(),
		    success: function (data, text) {
		       $('#share_form').html('Thanks! Your message has been sent.');
		    },
		    error: function (request, status, error) {
		       $('#share_form').html('Error.');
		    }
		});

		
		/*
		var form_values = '';
		$('#share_form').find('input').each(function(){
			form_values += '\n' + $(this).val();
		});
		form_values += '\n' + $('#share_form textarea').val() ;
		alert('submitting values: ' + form_values);
		*/
	}
}




function set_default_text() {
    var default_value = this.value;
    $(this).focus(function() {
        if(this.value == default_value) {
            this.value = '';
            $(this).addClass('active');
        }
    });
    $(this).blur(function() {
        if(this.value == '') {
            this.value = default_value;
            $(this).removeClass('active');
        }
    });
}


function left_link() {
	
	// If the link has been, just return false
	if ($(this).hasClass('disabled')) {
		return false;
	}
	
	// Temporarily disable link so it can't be clicked while animation is occuring
	// (note the class will be removed by the 'disable carousel links' callback function)
	$(this).addClass('disabled');
	
	// Set default shift width and duration based size of image carousel
	if ($(this).parents('.image_carousel.width_100').length != 0) {
		var shift_width = 864;
		var duration = 1000;
	} else if ($(this).parents('.image_carousel.width_lb').length != 0) {
		var shift_width = 720;
		var duration = 750;
	} else if ($(this).parents('.image_carousel.width_75').length != 0) {
		var shift_width = 744;
		var duration = 750;
	} else if ($(this).parents('.image_carousel.width_50').length != 0) {
		var shift_width = 432;
		var duration = 500;
	} else {
		var shift_width = 215;
		var duration = 250;
	}

	var content_position = $(this).parents('.image_carousel').find('.inside').position().left;
	
	// Invert value to be used in calculations 
	content_position = (content_position * -1);
	
	// skip this if video (as it affects page controls
	if ( ! $(this).parents('.image_carousel.videos').length>0) {
		
		// If current content position is less than shift_width, change shift_width to this value 
		// (so we don't move past the end of content) otherwise use default value
		if (content_position < shift_width) {
			shift_width = content_position;
		}
	}
	
	// Move the content
	$(this).parents('.image_carousel').find('.inside').animate(
		{left: '+='+shift_width}, 
		duration,
		function() {
				disable_carousel_links($(this));
		}
	);
	
	// If video, update pagination links
	if ($(this).parents('.image_carousel.videos').length) {	
		update_pagination_links($(this), (-1 * shift_width));
	}
	
	return false;
}



function right_link() {
		
	// If the link has been, just return false
	if ($(this).hasClass('disabled')) {
		return false;
	}
	
	// Temporarily disable link so it can't be clicked while animation is occuring
	// (note the class will be removed by the 'disable carousel links' callback function)
	$(this).addClass('disabled');
	
	// Set default shift width and duration based size of image carousel
	if ($(this).parents('.image_carousel.width_100').length != 0) {
		var shift_width = 864;
		var duration = 1000;
	} else if ($(this).parents('.image_carousel.width_lb').length != 0) {
		var shift_width = 720;
		var duration = 750;
	} else if ($(this).parents('.image_carousel.width_75').length != 0) {
		var shift_width = 744;
		var duration = 750;
	} else if ($(this).parents('.image_carousel.width_50').length != 0) {
		var shift_width = 432;
		var duration = 500;
	} else {
		var shift_width = 215;
		var duration = 250;
	}
	
	var outside_width = $(this).parents('.image_carousel').find('.outside').width(); // width of outside box (910)
	var content_width = $(this).parents('.image_carousel').find('.inside').width(); // width of content (2301)
	var content_position = $(this).parents('.image_carousel').find('.inside').position().left // position of content (0/-864/864/etc)
	
	
	// Get margin based on image_carousel class
	if ($(this).parents('.image_carousel.videos').length) {
		var margin = 26;
	} else {
		var margin = 10;
	}
	
	// Take into account the margin on the final element
	content_width -= margin;
		
	// Calculate the size of the unseen portion (content_position + content_width - outside_width)
	var unseen_portion = (content_position + content_width - outside_width);
	
	// skip this if video (as it affects page controls
	if ( ! $(this).parents('.image_carousel.videos').length > 0) {

		// If unseen portion is smaller than movement width, use that, otherwise use default
		if (unseen_portion < shift_width) {
			shift_width = unseen_portion;
		}
	}
	
	// Animate images
	$(this).parents('.image_carousel').find('.inside').animate(
		{left: '-='+shift_width}, 
		duration, 
		function() {
				disable_carousel_links($(this));
		}
	);
	
	// If video, update pagination links
	if ($(this).parents('.image_carousel.videos').length) {	
		update_pagination_links($(this), shift_width);
	}
	
	return false;
}



/**
 * This function is called after the page loads and after image 
 * carousel content is moved to see whether the left/right links 
 * should be disabled
 */
function disable_carousel_links(carousel)
{
	// Check left link	
	// Disable if position is greater than or equal to zero
	if (carousel.position().left >= 0) {
		carousel.parents('.image_carousel').find('.left_link').addClass('disabled');
	} else {
		carousel.parents('.image_carousel').find('.left_link').removeClass('disabled');
	}
	
	// Check right link
	var outside_width = carousel.parent('.outside').width(); 
	var content_width = carousel.width();
	var content_position = carousel.position().left;

	/*console.log('outside_width' + outside_width); 
	console.log('content_width' + content_width);
	console.log('content_position' + content_position);*/

	// get margin
	if (carousel.parents('.image_carousel.videos').length) {
		var margin = 26;
	} else {
		var margin = 10;
	}
	
	// Disable if content width minus content position (a negative number) is less than or equal 
	// to outside box width. 10 is formula below takes into account 10px margin
	if ((content_width + content_position - margin) <= outside_width) {
		carousel.parents('.image_carousel').find('.right_link').addClass('disabled');
	} else {
		carousel.parents('.image_carousel').find('.right_link').removeClass('disabled');
	}	
}




/**
 * This function sets the current active menu item
 */
function set_nav_active_state(nav_id) {
	$('#'+nav_id).find('a').addClass('nav_active');
}


/** 
 * Add item to favorites
 */
function add_to_favorites(page_id) {
		
	// Get details with ajax
	// (Replace with real page - index.html used so it doesn't return error)
	$.post('index.html', {'page_id' : page_id},
		
		function(data) {
			// Success
			
			// Update favorites menu
			// replace with data sent back from from 'data' 
			// Just inserting prototype here
			
			$('#favorites').find('UL').prepend(
				'<li id="favorites_'+page_id+'">'+
					'<img src="//dummyimage.com/60x60/8b0000/ebebeb/" />'+
					'<a href="#" class="title">New Title</a>'+
					'<span>Deccription</span>'+
					'<a href="#" class="remove" onclick="remove_from_favorites(\''+page_id+'\');return false;">Remove</a>'+
				'</li>'
			);
			
			// Increase count
			var favorites_count = $('#favorites_count > SPAN').html();
			favorites_count = parseInt(favorites_count);
			favorites_count += 1;
			$('#favorites_count > SPAN').html(favorites_count);
		}
	);
	
	// Flash and change icon to blue
	$('#favorites_link_'+page_id).addClass('added');
	$('#favorites_link').fadeOut(200).fadeIn(200).fadeOut(200).fadeIn(200);

	return false;
}



/** 
 * Remove item from favorites
 */
function remove_from_favorites(page_id) {
	
	// Send Ajax removal request
	$.post('index.html', {'page_id' : page_id},
		function(data) {
			// Success
			
			// Remove from faves list
			$('#favorites_'+page_id).remove();
			
			// Change icon back to brown
			$('#favorites_link_'+page_id).removeClass('added');

			// Decrease count
			var favorites_count = $('#favorites_count > SPAN').html();
			favorites_count = parseInt(favorites_count);
			favorites_count -= 1;
			$('#favorites_count > SPAN').html(favorites_count);
		}
	);
	
	return false;
}




function addToFavoritesWithId(id) {
	alert("added: " + id + " to favorites");
}

function shareWithId(id) {
	alert("sharing: " + id );
}

function collapse() {
	//$('#header').animate({top: -89}, 225, 'linear');
	$('#header').hide();
}

function expand() {
	//$('#header').animate({top: 0}, 150, 'linear');
	$('#header').show();
}



// Display header and share box
PageFunctions = {
	open_share : function() {
		$('#header').show();
		$('#share').show();
		$('#share_link').addClass('share_hover');
	}
	
}
	
	
// Usage: PageFunctions.open_share();







var LightboxClass = function() {

	var _lightbox_link  = '.lightbox_link';
	var _lightbox_img   = '#lightbox_img';
	var _lightbox_close = '#lightbox_close';
	var _cloak          = '#cloak';
	var _initial_load;
	
	var lightbox             = $('#lightbox');
	var lightbox_img         = $('#lightbox_img');
	var lightbox_video       = $('#lightbox_video');
	var lightbox_loading     = $('#lightbox_loading');
	var lightbox_img_wrapper = $('#lightbox_img_wrapper');
	var text_box             = $('#text_box');
	var cloak                = $('#cloak');
	
	var caption = '';
	
	
	/** 
	 * Constructor
	 */
	var _init = function() {
		$(_lightbox_link).click(_loadLightbox);
		$(_lightbox_img).load(_imageLoaded);
		$(_lightbox_close).click(_close);
		$(_cloak).click(_close);
		_initial_load = true;
	}
		
	
	/** 
	 * Load the lightbox
	 */
	var _loadLightbox = function(e) {
		
		e.preventDefault();
		target = $(this);
		
		//console.log('running load_lightbox');
		
		// If cloak is not already visible, fade in
		if (cloak.is(':hidden')) {
			cloak.css('height', $(document).height());
			cloak.fadeIn();
		}
		
		// Freeze image wrapper and lightbox size
		//console.log(lightbox_img_wrapper.height());
		lightbox_img_wrapper.css('height', lightbox_img_wrapper.height() + 'px');
		lightbox.css('height', lightbox.height());
		lightbox.css('width', lightbox.width());

		// Show loader
		lightbox_loading.fadeIn();
		
		// If lightbox doesn't have carousel, add it
		if (_initial_load === true) {
			
			$('.lightbox_target').clone().insertAfter($('#lightbox_close'));
			
			// change width
			$('.image_carousel', lightbox).removeClass('width_100').addClass('width_lb');
			
			// add event listeners again... ?
			$(_lightbox_link).click(_loadLightbox);
			$('.right_link').click(right_link);
			$('.left_link').click(left_link);
		}
		
		// get caption
		if (target.parent('LI').length) {
			caption = target.parent('LI').find('SPAN').html();
		} else {
			caption = $('.lightbox_img_link').find('SPAN').html();
		}

		// Add caption
		text_box.fadeOut(function() {
			text_box.html(html_entity_decode(caption));
		});
		
		
		
		// Section for Vimeo videos
		var vimeo_id = target.attr('vimeo_id');
		
		if (vimeo_id) {
			lightbox_video.show().html(
				'<iframe src="http://player.vimeo.com/video/' + vimeo_id + 
				'?title=0&amp;byline=0&amp;portrait=0&amp;autoplay=1" ' +
				'width="640" height="480" frameborder="0"></iframe>');
			_imageLoaded(true);
		} else {
			lightbox_video.hide();
		}
 		// End Vimeo
 		
 		
 		
		// Fade out image
		lightbox_img.fadeOut('fast', function() {
			
			// Set image (This will fire load() listener)
			$('#lightbox_img').attr('src', target.attr('href'));
					
		});

		_initial_load = false;
		
	};
	
	

	/** 
	 * Run when new image has loaded
	 */
	var _imageLoaded = function(is_video) {
		
		//console.log('image loaded');

		var window_height   = 0;
		var scroll_top      = 0;
		var lightbox_height = 0;
		var top_pos         = 0;
		var window_width    = 0;
		var lightbox_width  = 0;
		var left_pos        = 0;
		var carousel_width  = 0;
		
		// Remove loading
		lightbox_loading.fadeOut();
		
		if (lightbox.is(':hidden')) {
			lightbox.fadeIn();
		}
		if (text_box.is(':hidden')) {
			text_box.fadeIn();
		}
		
		// run disable links on new image carousel
		if ($('.image_carousel', lightbox).length) {
	 		disable_carousel_links($('.image_carousel', lightbox).find('.inside'));
		}
			
		// get image size and set size and location of lightbox
		// Use scroll position, window height and lightbox height to center lightbox on page
		window_height = $(window).height();
		scroll_top = $(window).scrollTop();	
		lightbox_height = (lightbox_img.height() + 70);
			
		// if lightbox img is less than img wrapper
		if (lightbox_height < lightbox_img_wrapper.height()) {	
			lightbox_height = (lightbox_img_wrapper.height() + 70);
		}
		
		// If Vimeo video
		if (is_video === true) {
			lightbox_height = (lightbox_video.height() + 70);
			lightbox_width = lightbox_video.width();
		}
		
		// if there is an image carousel
		lightbox_height += $('.image_carousel', lightbox).outerHeight();
		
		// if there is a text box
		lightbox_height += text_box.outerHeight();
		
		// Position is: scroll offset plus half the difference between lightbox size and window height
		top_pos = (scroll_top + ((window_height - (lightbox_height) ) / 2 ));
		if (top_pos < 10) { top_pos = 10; }
		
		window_width = $(window).width();
		lightbox_width = lightbox_img.width();
		
		//console.log('carousel width: ' + $('.image_carousel').width());
		carousel_width = ($('.image_carousel', lightbox).width());
		if (lightbox_width < carousel_width) {
			lightbox_width = carousel_width;
		}
		
		left_pos = ((window_width - (lightbox_width + 70) ) / 2 );
		
		if (lightbox_img.is(':visible')) {
			
			lightbox.css('left', left_pos + 'px');
			lightbox.css('top', top_pos + 'px');
			lightbox.css('width', lightbox_width + 'px');
			lightbox_img_wrapper.css('height', 'auto');
			lightbox.css('height','auto');
			
		} else {
			
			//lightbox.css('left', left_pos + 'px');
			//lightbox.css('width', lightbox_width + 'px');
			lightbox.animate({
					left : left_pos,
					top : top_pos,
					width : lightbox_width
				},
				function() {
					lightbox_img_wrapper.css('height', 'auto');
					lightbox.css('height','auto');
					lightbox_img.fadeIn('fast');
					
				}
			);
		}
		
		
		/*
		console.log(lightbox_video.width());
		console.log(lightbox_video.height());
		
		console.log(lightbox_img.width());
		console.log(lightbox_img.height());
		console.log('window_height ' + window_height);
		console.log('scroll_top ' + scroll_top);
		console.log('lightbox_height ' + lightbox_height);
		console.log('top_pos ' + top_pos);
		console.log('window_width ' + window_width);
		console.log('lightbox_width ' + lightbox_width);
		console.log('left_pos ' + left_pos);
		console.log(' ');
		*/
	};
	

	
	/** 
	 * Close lightbox
	 */
	var _close = function() {
		
		lightbox.fadeOut();
		cloak.fadeOut();
		lightbox_loading.fadeOut();
		
		return false;
	}
		
	_init();
	
};


$(document).ready(function() {
	var myLightbox = new LightboxClass();
});

scrollAlpha = function(l, button) {

		var menu 		= $('.subnav_alpha');
		var menu_items	= $('.subnav_alpha A');
		var list 		= $('.artist_list UL');

		if (!l) return;
	
		var letters = l.split(',');
		var scrollto	= false;
				
		// Loop through all letters to find first matching header. Sometimes one is missing.
		while((scrollto == false) && (letters.length > 0)) {
			var letter = letters.shift();
			if ((heading = $('#subnav_alpha_'+letter))) {
				scrollto = heading;
			}
		};			
					
		if (scrollto) {
			menu_items.removeClass('current');
			$(button).addClass('current');
			list.scrollTo(heading, 800);
		}				

}


function html_entity_decode(str) {
	str = str.replace(/&lt;/gi, '<');
	str = str.replace(/&gt;/gi, '>');
	return str;
}

