var pathToImage = "app/webroot/img/loading_gallery.gif";
//imgLoader = document.createElement('img') ;
//imgLoader.src = pathToImage;
/*********** 
SUBROUTINES 
***********/

$.gallery_nav_scroll_setup = function()
{
 	var img_count = $('#gallery_nav_photos img').size();
alert(img_count);
	$('#gallery_nav_photos img')
		//loading the thumbs and scolling the gallery
		.each(function(i)
		{
			$this = $(this);
		//	alert(i + " vs. " + (img_count-1));
			$temp = $('<div class="preloading_image_container"></div>')
			$temp.image_with_callback($this.attr('src'),i,img_count);
		});	
}
$.gallery_nav_scroll	= function()
{
//	$('.preloading_image_container').remove();
	arguments[0]?id=arguments[0]:id=null;
	if(id)
	{
		$current_photo = $('#photo_'+id);
	}
	else
	{
		$current_photo = $('#gallery_nav_photos a.current').parent('li');
	}
//	alert(id);
//	alert($current_photo);
//	alert("gns empty " + $('#gallery_nav_photos a.current img').attr('src'));
//	alert("gns " + $current_photo.offset());

	var current_photo_position		=	$current_photo.offset();
	var current_photo_width			=	$current_photo.width();
	var current_photo_padLeft		=	parseInt($current_photo.css('paddingLeft'));
	var current_photo_padRight		=	parseInt($current_photo.css('paddingRight'));
	var current_photo_marginLeft	=	parseInt($current_photo.css('marginLeft'));
	var current_photo_marginRight	=	parseInt($current_photo.css('marginRight'));				
	var gallery_nav_width			=	$('#gallery_nav_photos').width();
	var gallery_nav_position		=	$('#gallery_nav_photos').offset();
	var gallery_nav_ul_position		=	$('#gallery_nav_photos ul').offset();

//	alert(current_photo_position.left);
	/* ----- GALLERY NAV SCROLLING ----- */
	if (current_photo_position.left > gallery_nav_width)
	{
		$('#gallery_nav_photos ul').animate(
			{
				'left': (gallery_nav_ul_position.left - ((current_photo_position.left - gallery_nav_width) + current_photo_width + current_photo_padLeft +current_photo_padRight + current_photo_marginLeft + current_photo_marginRight))+'px'
			},
			'slow');
	}
	if (current_photo_position.left < gallery_nav_position.left)
	{
		$('#gallery_nav_photos ul').animate(
			{
				'left': (gallery_nav_ul_position.left + (gallery_nav_position.left - current_photo_position.left - current_photo_width))+'px'
			},
			'slow');
	}
	current_photo_position		=	0;
	current_photo_width			=	0;
	current_photo_padLeft		= 	0;
	current_photo_padRight		=	0;
	current_photo_marginLeft	=	0;
	current_photo_marginRight	=	0;
	gallery_nav_width			=	0;
	gallery_nav_position		=	0;
	gallery_nav_ul_position		=	0;
}
$.gallery_thumbs_replace = function(gallery_id)
{
	$('#gallery_nav_container')
		$.ajax(
				{
		   			url: '/photography/index.php/galleries/related_photos/'+gallery_id,
		   			success: function(data,msg){
		     			$('#gallery_nav_container')
							.html(data)
							.find('#gallery_nav_photos')
								.hide();
		   			},
		   			complete: function(){
						$.thumbnails_setup();
					   $('#gallery_nav_photos').show();
						$.gallery_nav_scroll();
						$current_photo = $('#gallery_nav_photos a.current')
												.parent('li')
												.attr('id');
						var id = $current_photo.substring($current_photo.lastIndexOf('#photo_')+7);
						$.prev_next_buttons_setup(id);
		   			}
	});			
}
function goUp()
{
$('#gallery_nav').slideUp('fast');
}
function goDown()
{
$('#gallery_nav').slideDown('fast');
}
//PRELOADING IMAGES --- From http://letmehaveblog.blogspot.com/2006/08/simple-jquery-plugin-to-load-images.html
$.fn.image = function(src)
{ 
   return this.each(function()
	{ 
	
		//var i = new Image(); 
		//12/14/07 teresa hurley changed to:
		var i = document.createElement('img') 
		//see http://alvinwoon.com/blog/2007/08/29/safaris-javascript-image-object-bug/
		
		i.src = src; 
		this.appendChild(i);
	});
}
$.fn.image_with_callback = function(src, img_no, img_count)
{ 
   return this.each(function()
	{ 
	
		//var i = new Image(); 
		//12/14/07 teresa hurley changed to:
		var i = document.createElement('img') 
		//see http://alvinwoon.com/blog/2007/08/29/safaris-javascript-image-object-bug/
		
		i.src = src; 
		this.appendChild(i);
		//12/16/07 teresa hurley changed.
		//			i had to hard code my function in here
		//			instead of passing it 
		//			for some reason safari would never fire it
		//			when i passed it. ???
		i.onload = function()
		{
		//	alert(img_no + " vs " + (img_count-1));
		 	if(img_no == img_count - 1)
			{
				$.gallery_nav_scroll();
			}		 
		}

   }); 
}
$.main_content_replace = function(url)
{
//	alert("starting main_content_replace");

	$('#pre_load').fadeIn('slow');
	$('#content_for_layout').fadeTo('slow',0, function()
	{
//		alert("inside main_content_replace: " + url);
		$.ajax(
				{
		   			url: url,
		   			success: function(data,msg){
//						alert("inside main_content_replace success: " + url);
						if(url.indexOf('#photo_')<0 && url.indexOf('#gallery_')<0)
						{
//							alert('replacing content from w/in main_content_replace ')
							$('#content_for_layout').html(data);
						}
		   			},
		   			complete: function(){
						$('#pre_load').fadeOut('slow');
						$('#content_for_layout').fadeTo('slow',1, function()
						{
							tb_init('#content_for_layout a.thickbox');
//							alert("inside main_content_replace complete: " + url);
							if(url.indexOf('/photos/')>-1 || url.indexOf('#photo_')>-1)
							{

								var id = url.indexOf('/photos/')>-1 ? url.substring(url.lastIndexOf('/')+1):url.substring(url.lastIndexOf('#photo_')+7,url.lastIndexOf('_'));
//		alert("inside main_content_replace /photos/ or #photo_, id is : " + id);
								$.thumbnails_current(id);
		 						$.gallery_nav_scroll(id);
//	alert('calling pnb setup from inside main_content_replace /photos/ or #photo_');
								$.prev_next_buttons_setup(id);
							}
							else if(url.indexOf('/galleries/')>-1 || url.indexOf('#gallery_')>-1)
							{
								switch (url)
								{
									case url.indexOf('#gallery_')>-1:
									  	var gallery_id = url.substring(url.lastIndexOf('#gallery_')+1,url.lastIndexOf('_'));
										$.gallery_thumbs_replace(gallery_id);	
									  	break;
									case url.indexOf('?')>-1:
									  	var gallery_id = url.substring(url.lastIndexOf('/')+1,url.indexOf('?'));
										$('#gallery_nav_container').html('');	
									  	break;
									default:
									  	var gallery_id = url.substring(url.lastIndexOf('/')+1);
										$.gallery_thumbs_replace(gallery_id);	
								}								
								$('#portfolio_'+gallery_id).addClass('current');
							}
							else
							{
								$('#gallery_nav_container').html('');	
							}
						});
		   			}
	 	});					
	});
}
$.main_nav_current = function(section)
{
	$('#main_nav a')
		.removeClass('current');
	$("#main_nav a:contains('"+section+"')")
		.addClass('current');
}
$.main_photo_home_setup = function()
{
	$gallery_link = $('#current_photo a');
	url= $gallery_link.attr('href');
	id = url.substring(url.lastIndexOf('/')+1);
	$gallery_link.remote('#content_for_layout', {hashPrefix: 'gallery_'+id+'_'}, function(event)
	{
			url = String(this);
		  	id = url.substring(url.lastIndexOf('#gallery_')+9,url.lastIndexOf('_'));
			$.main_nav_current('Portfolio');
			$('#portfolio_nav_portfolios a')
			//	.css({'background':'none'})
			//	.removeClass('icon')
				.removeClass('current');
		//	$.portfolio_nav_setup();
			$('#portfolio_'+id)
				.addClass('current');
			tb_init('#content_for_layout a.thickbox');
			$('#pre_load').fadeOut('slow');
			$('#content_for_layout').fadeTo('slow',1,function()
			{
				$.gallery_thumbs_replace(id);
			});
			return false;
	});
}
$.prev_next_buttons_setup = function()
{
//alert('inside pnb setup');
	arguments[0]?id=arguments[0]:id=null;
	if(id)
	{
		$current_photo = $('#photo_'+id);
	}
	else
	{
		$current_photo = $('#gallery_nav a.current').parent('li');
	}
	if($('*').index($current_photo.prev()[0])>-1)
	{
		var prev_url = $current_photo
							.prev()
							.children('a')
							.attr('href')
		prev_url = prev_url.replace(/_\d*$/,'');
		prev_url = prev_url.replace(/#photo_/,'/photography/index.php/photos/view/');
		$('#gallery_nav a.prev_button')
			.unbind('click')
			.attr('href',prev_url)
	        .one('click',function(e) 
			{ 
//alert('clicked prev');
				$.main_content_replace(prev_url);
				return false;
            }) 
			.removeClass('inactive');
	}
	else
	{
		$('#gallery_nav a.prev_button')
			.addClass('inactive');
	}
	if($('*').index($current_photo.next()[0])>-1)
	{
		var next_url = $current_photo
							.next()
							.children('a')
							.attr('href')
		next_url = next_url.replace(/_\d*$/,'');
		next_url = next_url.replace(/#photo_/,'/photography/index.php/photos/view/');
		$('#gallery_nav a.next_button')
			.unbind('click')
			.attr('href',next_url)
 	        .one('click',function(e) 
			{ 
//alert('clicked next');
				$.main_content_replace(next_url);
				return false;
					
            }) 
 			.removeClass('inactive');
	}
	else
	{
		$('#gallery_nav a.next_button')
			.addClass('inactive');

	}
}
$.portfolio_nav_setup = function()
{
	var	sn_width		=	$('#sub_nav').width();
	var pn_width		=	10;	
	var list_item_width	=	$('#portfolio_nav ul li:first').width();
	var	current_portfolio_index	=	$('#portfolio_nav_portfolios ul li')
										.index($('#portfolio_nav_portfolios a.current')
													.parent('li')[0]);
//on zingo:
	
/*	var $prev_button	=	$('<div class="portfolio_prev_next portfolio_prev clickable"><img src="/eastman_v3/app/webroot/img/portfolio_previous.png" alt="more portfolios" title="more portfolios"/></div>');
	var $next_button	=	$('<div class="portfolio_prev_next portfolio_next clickable"><img src="/eastman_v3/app/webroot/img/portfolio_next.png" alt="more portfolios" title="more portfolios"/></div>');
*/	
//on hostmonster:
var $prev_button	=	$('<div class="portfolio_prev_next portfolio_prev clickable"><img src="app/webroot/img/portfolio_previous.png" alt="more portfolios" title="more portfolios"/></div>');
var $next_button	=	$('<div class="portfolio_prev_next portfolio_next clickable"><img src="app/webroot/img/portfolio_next.png" alt="more portfolios" title="more portfolios"/></div>');


	var pnp_width		=	sn_width-46; //hard-coded amt to cover prv & next buttons	
	
	var numPerPage		=	Math.floor(pnp_width/list_item_width);
	//if the last list item is cut off in portfolio_nav_portfolios width,
	//shorten portfolio_nav_portfolios width so it only shows whole
	//list items
	if((pnp_width % list_item_width) > 0)
	{
		pnp_width = numPerPage*list_item_width;
	}
	$('#portfolio_nav_portfolios').width(pnp_width);
	//get max needed width for portfolio ul
	$('#portfolio_nav_portfolios ul li').each(function()
	{
		pn_width	+=	$(this).width();
	});
	//set it (to max width if that's bigger than portfolio_nav_portfolios width, 
	//otherwise, use portfolio_nav_portfolios width)
	$('#portfolio_nav_portfolios ul')
		.width(pn_width > pnp_width ? pn_width : pnp_width);
	//if it's smaller than portfolio_nav width, set a left margin so it will center
	if(pnp_width > pn_width)
	{
		$('#portfolio_nav_portfolios ul')
			.css('margin-left',(pnp_width-pn_width)/2);
	}
	var numPhotos		=	$('#portfolio_nav_portfolios').find('li').length;
	var numPages		=	Math.ceil(numPhotos/numPerPage);
	var currentPage		=	Math.ceil((current_portfolio_index +1)/numPerPage);

	$('#portfolio_nav_portfolios a')
		.bind('mouseover', function()
		{
			if($('*').index($('#gallery_nav_photos')[0])<0)
			{
				$this = $(this);
				$this
					.addClass('current')
					.parent('li')
					.siblings()
					.children('a')
						.removeClass('current');	
				$('#current_photo_caption').text($this.text());
				var photo_id = $this.attr('id').substr($this.attr('id').indexOf('_')+1);
				$('.main_photo')
					.attr('src',pathToImage)
					.attr('src',$('#img_preload_'+photo_id).text())
					.attr('title',$this.text())
					.attr('alt',$this.text())
					.attr('rel',$this.attr('id'))
					.parent('a')
						.attr('title',$this.text())
						.attr('alt',$this.text())
						.attr('href',$('#img_preload_'+photo_id).text().replace(/medium\/thumb/,'photos/photo'))
					;
			}
		});
	$('#portfolio_nav_portfolios').bind('repaginate',
	 	function()
		{
			$prev_button.unbind('click');
			$next_button.unbind('click');
			$prev_button
					.hover(function()
					{
						$(this).addClass('portfolio_prev_next_hover');
					}, function()
					{
						$(this).removeClass('portfolio_prev_next_hover');
					})
					.bind(
						'click', 
						{'newPage': (currentPage-1)},
						function(event)
						{
							$(this).removeClass('portfolio_prev_next_hover');
							currentPage = event.data['newPage'];
							$('#portfolio_nav_portfolios').trigger('repaginate');
							return false;
						})
					.insertBefore($('#portfolio_nav_portfolios'))
					;
			$next_button
					.hover(function()
					{
						$(this).addClass('portfolio_prev_next_hover');
					}, function()
					{
						$(this).removeClass('portfolio_prev_next_hover');
					})
					.bind(
						'click', 
						{'newPage': (currentPage+1)},
						function(event)
						{
							$(this).removeClass('portfolio_prev_next_hover');
							currentPage = event.data['newPage'];
							$('#portfolio_nav_portfolios').trigger('repaginate');
							return false;
						})
					.insertBefore($('#portfolio_nav_portfolios'))
					;
			if (currentPage <= numPages)
			{
		    	$('#portfolio_nav_portfolios ul')
			        .animate({
								'left': "-"+((list_item_width*numPerPage)*(currentPage-1))+'px'
							},
							'slow');

				currentPage <= 1 ? $prev_button.addClass('inactive'):$prev_button.removeClass('inactive');
				currentPage >= numPages ? $next_button.addClass('inactive'):$next_button.removeClass('inactive');
				
			}
		});
		$('#portfolio_nav_portfolios').trigger('repaginate');
}
$.text_content_replace = function(url)
{
	$('#content_for_layout').load(url);

}
$.text_sub_nav_setup = function()
{
	$('#text_nav a')	
		.each(function()
		{
			$this = $(this);
			url= $this.attr('href');
			var sub_section 	= $this.text();
			$this.remote('#text_area', {hashPrefix: sub_section+'_'}, function(event)
			{
					url = String(this);
				  	sub_section = url.substring(url.lastIndexOf('#')+1,url.lastIndexOf('_'));
					$.text_nav_current(sub_section);
					$('#portfolio_nav_portfolios a')
						.removeClass('current');
					$('#gallery_nav_container').html('');
					$('#pre_load').fadeOut('slow');
					$('#text_area').fadeTo('slow',1);
					return false;
			});
	
		});	
};
$.text_nav_current = function(section)
{
	$('#text_nav a')
		.removeClass('current');
	$("#text_nav a:contains('"+section+"')")
		.addClass('current');
}
$.thumbnails_current = function(id)
{
//	alert(id);
	$('#gallery_nav_photos li')
		.removeClass('current');
	$('#gallery_nav_photos a')
		.removeClass('current');
	$('#photo_'+id)
		.addClass('current');
	$('#photo_'+id).children('a')
		.addClass('current');
	
}
$.thumbnails_setup = function()
	{

	$('#gallery_nav_photos a')
		.each(function()
		{
			$this = $(this);
			url= $this.attr('href');
			id = url.substring(url.lastIndexOf('/')+1);
			$this.remote('#content_for_layout', {hashPrefix: 'photo_'+id+'_'}, function(event)
			{
					url = String(this);
				//	alert(url);
				  	id = url.substring(url.lastIndexOf('#photo_')+7,url.lastIndexOf('_'));
					tb_init('#content_for_layout a.thickbox');
					$.thumbnails_current(id);
					$.prev_next_buttons_setup(id);
					$.gallery_nav_scroll(id);
					$('#pre_load').fadeOut('slow');
					$('#content_for_layout').fadeTo('slow',1);
					return false;
			});
			
		});
		return this;		
	}

/*********** 
MAIN FUNCTIONS 
***********/
/* ----- INITIALIZIING HISTORY ----- */
$(document).ready(function() 
{
	$.ajaxHistory.initialize(function()
	{
	//	$.main_content_replace('galleries/view/0');
	})
});

/* ----- SETTING UP THE GALLERY NAV ----- */
$(document).ready(function() 
{
	$.thumbnails_setup();
//	$.prev_next_buttons_setup();
	/*$('#gallery_nav_photos li a').parent('li').addClass('current');
	$('#gallery_nav_photos li a').removeClass('current');
	var gallery_url		= 	$('#portfolio_nav_portfolios a.current').attr('href')
	var gallery_id 		= 	gallery_url.substring(gallery_url.lastIndexOf('/')+1);
	$.gallery_thumbs_replace(gallery_id,true);*/	
});

/* ----- SETTING UP THE PORTFOLIO NAV CONTAINER ----- */
$(document).ready(function() 
{
	$.portfolio_nav_setup();
});

/* ----- SETTING UP FOR CHANGING PORTFOLIO/GALLERY ----- */

$(document).ready(function() 
{
	$('#portfolio_nav_portfolios a')

		.each(function()
		{
			$this = $(this);
			url= $this.attr('href');
			id = url.substring(url.lastIndexOf('/')+1);
			$this.remote('#content_for_layout', {hashPrefix: 'gallery_'+id+'_'}, function(event)
			{
					url = String(this);
				  	id = url.substring(url.lastIndexOf('#gallery_')+9,url.lastIndexOf('_'));
					$.main_nav_current('Portfolio');
					$('#portfolio_nav_portfolios a')
					//	.css({'background':'none'})
					//	.removeClass('icon')
						.removeClass('current');
				//	$.portfolio_nav_setup();
					$('#portfolio_'+id)
						.addClass('current');
					tb_init('#content_for_layout a.thickbox');
					$('#pre_load').fadeOut('slow');
					$('#content_for_layout').fadeTo('slow',1,function()
					{
						$.gallery_thumbs_replace(id);
					});
					return false;
			});
			
		});	
});
/* ----- SETTING UP FOR CHANGING SECTION ----- */
$(document).ready(function() 
{
	$.main_photo_home_setup();
	$('#main_nav a')	
		.each(function()
		{
			$this = $(this);
			url= $this.attr('href');
			var section 	= $this.text();
			$this.remote('#content_for_layout', {hashPrefix: section+'_'}, function(event)
			{
					url = String(this);
				  	section = url.substring(url.lastIndexOf('#')+1,url.lastIndexOf('_'));
					$.main_nav_current(section);
					//$('#portfolio_nav_portfolios a')
					//	.removeClass('current');
					$('#gallery_nav_container').html('');
					$('#pre_load').fadeOut('slow');
					$('#content_for_layout').fadeTo('slow',1);
					if($('*').index($('#text_nav a')[0])>-1)
					{
						if($('#text_nav a:eq(0)').attr('href').indexOf("#")<0)
						{
							$.text_sub_nav_setup();
						}
					}
					if(section == 'Home' || section == 'Portfolio')
					{
						$('#current_photo a')
							.removeClass('thickbox');
						$.main_photo_home_setup();
						main_photo_rel = $('#current_photo img').attr('rel');
						gallery_icon_id	=	main_photo_rel.substring(main_photo_rel.lastIndexOf("portfolio_"));
						$('#'+gallery_icon_id).addClass('current');
						if($('#sub_nav').css('opacity')==0)
						{
							$('#sub_nav').fadeTo('slow',1);
						}
					}
					else
					{
						$('#sub_nav').fadeTo('slow',0);
						tb_init('#content_for_layout a.thickbox');
						
					}
					return false;
			});
		});	
});
$(document).ready(function() {
	$('a')
    .livequery(function()
	{ 
        $(this) 
            .click(function() 
			{ 
				$('.preloading_image_container').remove();
            }); 
    }, 
	function() 
	{ 
        $(this) 
		.unbind('click')
    })
});
