var viewport_height = null;
var viewport_width = null;
if(!gallery) {
	var gallery = 'people';
}
var photo_index = 0;
var wheel_lock = false;
var num_preload = 20;
var scrollable_height = 0;
var animation_speed = 600;
var animation_lock = false;
var prev_hash = document.location.hash;

Cufon.replace('h1,h2');

function isIOS() { 
	return /(iPhone|iPad|iPod)/.test(navigator.userAgent);
}

function ajaxLog(message) {
	var request = {};
	
	if(typeof message == 'string') {
		request.data = message;
	}
	else if(typeof message == 'object') {
		request.data = $.toJSON(message);
	}
	
	$.post('?action=ajaxLog', request);
}
			
$(document).ready(function() {
	if(self != top) {
		top.location.href = self.location.href;
	}
	
	self.onresize = resize;
	viewport_width = $(document).width();
	$('#footer').show();		
	// handle indexed URLs from search engines
	if(static_gallery && static_photo) {
		document.location.hash = '#' + static_gallery + '/' + static_photo;		
	} 
	else if(static_gallery) {
		document.location.hash = '#' + gallery;		
	} 
	else {
		var hash = null;
		
		try {
			hash = unescape(document.location.hash.substr(1));
		}
		catch(e) {}

		if(hash) {
			if(/\w+\/\d+/i.test(hash)) {
				var tmp = hash.split('/');
				gallery = tmp[0];
				photo_index = tmp[1];
			}
			else if(/\w+/i.test(hash)) {
				gallery = hash;
			}
		}
		else {
			document.location.hash = '#' + gallery;
			prev_hash = document.location.hash;
			try {
				if(pageTracker) {
					window.setTimeout(function() {
						pageTracker._trackPageview(document.location.hash);
					},250);
				}
			}
			catch(e) {}
		}
	}
	
	$('#gallery_link_' + gallery).addClass('active');
	Cufon.replace('.gallery_link');
	resize();
			
	window.setInterval(function() {
		if(document.location.hash != prev_hash) {
			// send click to Google Analytics
			try {
				if(pageTracker) {
					window.setTimeout(function() {
						pageTracker._trackPageview(document.location.hash);
					},250);
				}
			}
			catch(e) {}
			prev_hash = document.location.hash;
		}
		if(document.location.hash.length > 1) {
			var hash = unescape(document.location.hash.substr(1));
			var new_gallery = null;
			
			if(/\w+\/\d+/i.test(hash)) {
				var tmp = hash.split('/');
				new_gallery = tmp[0];
			}
			else if(/\w+/i.test(hash)) {
				new_gallery = hash;
			}
							 
			if(new_gallery && new_gallery != gallery) {
				gallery = new_gallery;
				$('.gallery_link.active').removeClass('active');
				$('#gallery_link_' + gallery).addClass('active');
				Cufon.replace('.gallery_link');
				loadImages(gallery);
				try {
					if(pageTracker) {
						window.setTimeout(function() {
							pageTracker._trackPageview(document.location.hash);
						},250);
					}
				}
				catch(e) {}
			}
			
			if(tmp) {
				var new_photo_index = parseInt(tmp[1]) - 1;
				if(new_photo_index != parseInt(photo_index)) {
					photo_index = new_photo_index;
					// make sure enough photos are preloaded to get to this one
					var preload_index = parseInt(photo_index) + parseInt(num_preload);
					$('.imageFrame').each(function(i) {
						if(i < preload_index) {
							if($(this).css('background-image') == 'none') {
								loadImage($(this));
							}
							$(this).show();
						}
					});
					try {
					$('.imageFrame:eq(' + photo_index + ')').click();
					}
					catch(e) {
						//alert(e);
						return true;
					}
				}
				else {
					var container = $('.imageFrames');
					var frame = container.find('.imageFrame:eq(' + photo_index + ')');
					
					if(frame.length && !animation_lock) {
						var correct_left_pos = parseInt(frame.position().left - (viewport_width / 2) + (frame.width() / 2) + 24);
						if(correct_left_pos >= 0) {
							correct_left_pos = 0 - correct_left_pos;
							var current_left_pos = container.position().left;
							
							if(current_left_pos != correct_left_pos) {
								container.css('left',correct_left_pos + 'px');
								frame.addClass('active').find('.overlay')
									.css('-ms-filter','progid:DXImageTransform.Microsoft.Alpha(Opacity=0)')
									.css('filter','alpha(opacity=0)')
									.fadeOut('normal');
							}
						}
					}
				}
			}
		}
	},200);

	$('h1').click(function() {
		var drawer_open = ($('h1.active').length > 0 ? true : false);
		var h1 = $(this);
		if(h1.hasClass('direct_link')) {
			return true;
		}
		else if(h1.hasClass('active')) {
			// close content drawer
			$('h1').removeClass('active');
			Cufon.replace('h1'); // re-render to switch font color
			var footer = $('#footer');
			$('#information').html('');
			
			footer.animate({
				height: '90'
			}, 500, null, function() {
				resize();
			});
			try {
				if(pageTracker) {
					window.setTimeout(function() {
						pageTracker._trackEvent('Content', 'Close', h1.text());
					},250);
				}
			}
			catch(e) {}
		}
		else {
			if(h1.hasClass('contact_link')) {
				// get contact info via ajax
				$.get('?action=getContactInfo', null, function(response) {
					if(response.success) {
						$('#ContactInfo #EmailAddress').html(response.email);
						$('#ContactInfo #PhoneNumber').html(response.phone);
					}
				}, 'json');
			}
			$('h1').removeClass('active');
			h1.addClass('active');
			Cufon.replace('h1'); // re-render to switch font color
			var footer = $('#footer');
			viewport_height = window.innerHeight ? window.innerHeight : $(window).height();
			
			var new_height = (parseInt(viewport_height) - 150) + 'px';
			if(!drawer_open) {
				// open content drawer
				var info = h1.nextAll('.info');
				//var new_height = (parseInt(viewport_height) - 150) + 'px';
				var new_height = 500;
				
				footer.animate({
					height: new_height
				}, 500, null, function() {
					// show text for this section
					
					$('#information').html(info.html());
					//Cufon.replace('h3');
					//$('#information :input').get(0).focus();
					resize();
				});
				
				try {
					if(pageTracker) {
						window.setTimeout(function() {
							pageTracker._trackEvent('Content', 'Open', h1.text());
						},250);
					}
				}
				catch(e) {}
			}
			else {
				// switch content displayed in drawer (leave drawer open)
				var info = h1.nextAll('.info');
				
				// copy content into information box
				//$('#information').fadeOut('normal').html('');
				$('#information').fadeOut('fast', function() {
					$('#information').html(info.html());
					//$('#information').fadeIn('fast');
					$('#information').show();
				});
				//$('#information :input').get(0).focus();
				try {
					if(pageTracker) {
						window.setTimeout(function() {
							pageTracker._trackEvent('Content', 'Open', h1.text());
						},250);
					}
				}
				catch(e) {}
			}
		}
		
		return false;
	});
	
	$('#information').click(function() {
		if($(this).find(':input').length == 0) {
			$('h1.active').click();
		}
	});
	
	if(isIOS()) {
		$('#container').swipe(function(event, info) {
			ajaxLog(info);
		});
	}
	else {
		$('#container').mousewheel(function(event, delta) {
			if(!wheel_lock) {
				wheel_lock = true;
				window.setTimeout(function() {
					wheel_lock = false;
				}, 1000);
				
				if(delta > 0) {
					prev();
				}
				else if(delta < 0) {
					next();
				}
			}
		});
	}
});

function resize() {
	viewport_height = window.innerHeight ? window.innerHeight : $(window).height();
	viewport_width = $(document).width();
	var main_links_width = parseInt(viewport_width) - 378;
	var main_link_num = $('h1').length;
	/*$('h1')
		.css('padding-left',Number(main_links_width / main_link_num / 4) + 'px')
		.css('padding-right',Number(main_links_width / main_link_num / 4) + 'px');*/
	$('#information').width(viewport_width - 250);
	var gallery_height = viewport_height - $('#footer').height();
	if(gallery_height < 0) gallery_height = 0;
	scrollable_height = gallery_height - 60;
	if(scrollable_height < 0) scrollable_height = 0;
	
	try {
		$('#gallery').height(gallery_height).width(viewport_width);
		$('#gallery_list').css('left', viewport_width - $('#gallery_list').width() - 12);
		$('.imageFrames').css('left','0px');
		//$('.imageFrame').height(gallery_height - 50);
	    //$("div.scrollable").height(viewport_height - 90).width(viewport_width).scrollable();     
		loadImages(gallery); 
	}

	catch (e) {}
}

function changeGallery(gallery_link) {
	var g = $(gallery_link);
	$('.gallery_link.active').removeClass('active'); 
	g.addClass('active'); 
	Cufon.replace('.gallery_link');
}

function reset() {
	self.location.href = '/';		
}

function loadImages(gallery_name) {
	if(/\/\d+$/.test(gallery_name)) {
		gallery_name = gallery_name.split('/');
		gallery_name = gallery_name[0];
	}
	$.post('load_images.php', ({ 'gallery': gallery_name }), function(response) {
		var response = $.evalJSON(response);
		
		if(response.success) {
			// clear out current gallery
			/*$('.imageFrames .imageFrame').each(function(i) {
				$(this).hide('drop').remove();
			});*/
			//$('.imageFrames').fadeOut('normal',function() {
				$('.imageFrame').remove();
				$('.imageFrames').css('left',0).show();
			//});
							
			// load new images into gallery
			if(response.files) {
				photo_index = 0;
				viewport_height = window.innerHeight ? window.innerHeight : $(window).height();
				var gallery_height = viewport_height - $('#footer').height();
				scrollable_height = gallery_height - 60;
				var imageFrames = $('.imageFrames');
				
				var first_img = true;
				
				for(var i in response.files) {
					imageFrames.append('<div class="imageFrame" style="height:' + scrollable_height + 'px"><div class="overlay"></div><div class="photoInfoIcon"><em>i</em></div></div>');
					var newFrame = imageFrames.find('.imageFrame:last');
					var filename = '/galleries/' + gallery_name + '/' + response.files[i].filename;
					
					newFrame.attr('id','frame' + i);
					newFrame.data('filename',filename);
					var icon = newFrame.find('div.photoInfoIcon');
					icon.click(function() {
						togglePhotoInfo();
					});
					
					if(first_img) {
						first_img = false;
						first_frame = newFrame;
						newFrame.addClass('active');
					}
					if(i < num_preload) {
						loadImage(newFrame);
					}
					newFrame.hover(
						function() {
							if($(this).hasClass('active') && $(this).find('.photoInfo').not(':visible')) {
								var icon = $(this).find('div.photoInfoIcon');
								if(icon.not(':visible')) icon.fadeIn();
							}
						}, 
						function() {
							if($(this).hasClass('active') && $(this).find('.photoInfo').not(':visible')) {
								var icon = $(this).find('div.photoInfoIcon');
								if(icon.is(':visible')) {
									icon.fadeOut().hide();
								}
							}
						}
					);
				}
			}
			$('.imageFrames').css('left','0px');
		}
		else {
			//alert(response.error_msg);
		}
	});
	
	$('#scrollHelp').click(function() {
		$(this).fadeOut(0);
	});
	
	if(first_time) {
		showHelp();
		first_time = false;
	}
}

function loadImage(imageFrame) {
	var filename = imageFrame.data('filename');
	if(filename) {
		$.post('load_image_data.php', { 'filename': filename }, function(json_response) {
			response = $.evalJSON(json_response);
			//console.log(response);
			if(response.success) {
				var height = response.height;
				var width = response.width;
				imageFrame.data('response', json_response);
				imageFrame.data('width', width);
				imageFrame.data('height', height);
				width = parseInt((scrollable_height / height) * width);
				imageFrame.width(width);
				imageFrame.height(scrollable_height);
				var img_src = 'url(get_image.php?filename=' + filename + '&height=' + scrollable_height + ')';
				imageFrame.css('background-image', img_src);

				if(imageFrame.hasClass('active')) {
					var overlay = imageFrame.find('.overlay');
					overlay
						.css('-ms-filter','progid:DXImageTransform.Microsoft.Alpha(Opacity=0)')
						.css('filter','alpha(opacity=0)')
						.fadeOut('normal');
				}
				var info_html = '';
				var description = ''; // used for Google Analytics "page title"
				if(response['title']) { 
					info_html += 'title: <span style="font-weight: normal; text-transform: none">' +  response['title'] + '</span><br/>'; 
					description = response['title'] + '.';
				}
				else {
					description = 'untitled.';
				}
				if(response['location']) { 
					info_html += 'location: <span style="font-weight: normal; text-transform: none">' + response['location'] + '</span><br/>'; 
					description += ' ' + response['location'] + '.';
				}
				if(response['capture date']) { 
					info_html += 'capture date: <span style="font-weight: normal; text-transform: none">' + response['capture date'] + '</span><br/>'; 
					description += ' ' + response['capture date'] + '.';
				}
				if(response['camera']) { 
					info_html += 'camera: <span style="font-weight: normal; text-transform: none">' + response['camera'] + '</span><br/>'; 
				}
				if(response['aperture']) { 
					info_html += 'aperture: <span style="font-weight: normal; text-transform: none">' + response['aperture'] + '</span><br/>'; 
				}
				if(response['exposure time']) { 
					info_html += 'exposure time: <span style="font-weight: normal; text-transform: none">' + response['exposure time'] + '</span><br/>'; 
				}
				if(response['iso']) { 
					info_html += 'iso: <span style="font-weight: normal; text-transform: none">' + response['iso'] + '</span><br/>'; 
				}
				if(response['focal length']) { 
					info_html += 'focal length: <span style="font-weight: normal; text-transform: none">' + response['focal length'] + '</span><br/>'; 
				}
				if(response['tags']) {
					info_html += 'tags: <span style="font-weight: normal; text-transform: none">' + response['tags'].join(', ') + '</span><br/>'; 
				}
				description += ' by M.SAWYER PHOTOGRAPHY';
				imageFrame.data('description',description);
				imageFrame.append('<div class="photoInfo">' + info_html + '</div>');
				imageFrame.find('.photoInfoClose').click(function() {
					togglePhotoInfo();
				});
			}
			else {
				//console.error(response);
			}
		});
	}
}

function next() {
	$('.imageFrame.active').removeClass('active').find('.overlay')
		.css('-ms-filter','progid:DXImageTransform.Microsoft.Alpha(Opacity=80)')
		.css('filter','alpha(opacity=80)')
		.fadeIn('normal');

	$('.photoInfoIcon').hide();
	$('.photoInfo').hide();
	++photo_index;
	document.location.hash = '#' + gallery + '/' + (parseInt(photo_index) + 1);
	var container = $('.imageFrames');
	var frame = container.find('.imageFrame:eq(' + photo_index + ')');
	
	if(frame.length) {
		animation_lock = true;
		container.animate({
			left: '-' + (frame.position().left - (viewport_width / 2) + (frame.width() / 2) + 24)
		}, animation_speed, function() {
			animation_lock = false;
		});
		
		frame.addClass('active').find('.overlay')
			.css('-ms-filter','progid:DXImageTransform.Microsoft.Alpha(Opacity=0)')
			.css('filter','alpha(opacity=0)')
			.fadeOut('normal');
			
		if(frame.data('description')) $('title').text(frame.data('description'));
		
		var preload_index = photo_index + num_preload - 1;
		var preload_frame = $('.imageFrame:eq(' + preload_index + ')');
		
		if(preload_frame.length ) {
			if(preload_frame.css('background-image') == 'none') {
				loadImage(preload_frame);
			}
			preload_frame.show();
		}
	}
	else {
		photo_index = 0;
		document.location.hash = '#' + gallery + '/' + (parseInt(photo_index) + 1);	
		$('.imageFrame:eq(' + photo_index + ')').click();
	}
}

function prev() {
	$('.imageFrame.active').removeClass('active').find('.overlay')
		.css('-ms-filter','progid:DXImageTransform.Microsoft.Alpha(80)')
		.css('filter','alpha(opacity=80)')
		.fadeIn('normal');
		
	$('.photoInfo:visible').hide();
	--photo_index;
	document.location.hash = '#' + gallery + '/' + (parseInt(photo_index) + 1);
	var container = $('.imageFrames');
	var frame = container.find('.imageFrame:eq(' + photo_index + ')');
	
	if(frame.length) {
		var new_pos = 0;
		
		if(photo_index > 0) {
			new_pos = '-' + (frame.position().left - (viewport_width / 2) + (frame.width() / 2) + 24);
		}
		
		animation_lock = true;
		container.animate({
			left: new_pos
		}, animation_speed, function() {
			animation_lock = false;
		});
		
		frame.addClass('active').find('.overlay')
		.css('-ms-filter','progid:DXImageTransform.Microsoft.Alpha(Opacity=0)')
		.css('filter','alpha(opacity=0)')
		.fadeOut('normal');

		if(frame.data('description')) $('title').text(frame.data('description'));
	}
	else {
		if(photo_index < 0) {
			// make sure all images are loaded, then scroll to the end
			$('.imageFrame').each(function(i) {
				if($(this).css('background-image') == 'none') {
					loadImage($(this));
				}
				$(this).show();
			});
			
			photo_index = $('.imageFrame').length - 1;
			document.location.hash = '#' + gallery + '/' + (parseInt(photo_index) + 1);	
			$('.imageFrame:eq(' + photo_index + ')').click();
		}
	}
}

$('.imageFrame').live('click', function() {
	if(!$(this).hasClass('active')) {
		$('.imageFrame.active').removeClass('active').find('.overlay')
		.css('-ms-filter','progid:DXImageTransform.Microsoft.Alpha(Opacity=80)')
		.css('filter','alpha(opacity=80)')
		.fadeIn('normal');
		$('.photoInfo:visible').hide();
	}
	var container = $('.imageFrames');
	var frame = $(this);
	photo_index = parseInt($(this).attr('id').split('frame')[1]);
	document.location.hash = '#' + gallery + '/' + (photo_index + 1);
			
	var new_pos = 0;
	
	if(photo_index > 0) {
		new_pos = '-' + (frame.position().left - (viewport_width / 2) + (frame.width() / 2) + 24);
	}
	
	animation_lock = true;
	container.animate({
		left: parseInt(new_pos) + 'px'
	}, animation_speed, function() {
		animation_lock = false;
	});
	
	frame.addClass('active').find('.overlay')
		.css('-ms-filter','progid:DXImageTransform.Microsoft.Alpha(Opacity=0)')
		.css('filter','alpha(opacity=0)')
		.fadeOut('normal');

	if(frame.data('description')) $('title').text(frame.data('description'));
});

function showHelp() {
	var help = $('#scrollHelp');
	
	help.fadeIn(animation_speed, function() {
		window.setTimeout(function() {
			help.fadeOut(animation_speed);
		}, 2000);
	});
}

function sendMessage() {
	var success = true;
	
	$('#information .field_container input[type=text]').each(function(i) {
		if($(this).val()) {
			$(this).removeClass('error');
		}
		else {
			$(this).addClass('error');
			success = false;
		}
	});
	
	if(!success) {
		$('.error:first').get(0).focus();
	}
	else {
		var request = {
			name: $('#information [name=visitor_name]').val(),
			contact: $('#information [name=visitor_contact]').val(),
			msg: $('#information [name=visitor_msg]').val()
		};
		
		$.post('?action=contact', request, function(rsp) {
			$('#information').html('<div style="padding: 30px;">Thanks for your message! You should receive a response shortly.</div>');
			window.setTimeout(function() {
				$('h1.active').click();
			},2000);
		});

	}
}

function togglePhotoInfo() {
	var frame = $('.imageFrame.active');
	var photo_info = frame.find('div.photoInfo');
	var icon = frame.find('div.photoInfoIcon');
	
	if(photo_info.is(':visible')) {
		photo_info.fadeOut('normal', function() {
			icon.html('<em>i</em>');
		});
		}
	else {
		photo_info.fadeIn('normal', function() {
			icon.html('x');
		});
	}
}

