$(document).ready(function() {

	// External links
	$('a').each(function() {
		if($(this).attr('rel') == 'external') {
			$(this).click(function() {
				window.open($(this).attr('href'));
				return false;
			});
		}
	});
	
	
	// Navigation
	$('ul#navigation li').hover(function() {
		if($(this).attr('id')) $(this).addClass('hover');
	}, function() {
		$(this).removeClass('hover');
	});


	// Buttons
	$('div.button').add('div.button-sm').hover(function() {
		var o = ($(this).hasClass('.button-sm') ? -30 : -36) + 'px';
		$(this).css('backgroundPosition', 'right ' + o);
		$(this).find('span').css('backgroundPosition', '0 ' + o);
	}, function() {
		$(this).css('backgroundPosition', 'right 0');
		$(this).find('span').css('backgroundPosition', '0 0');
	});	


	// Share menu
	$('#share-page').click(function() {
		$('#share-menu').show();
		return false;
	});
	$(document).click(function() {
		$('#share-menu').hide();
	});	


	// Image lists
	$('.image-list li a').mouseover(function() {
		var ul = $(this).parent().parent().parent();
		ul.find('li').removeClass('selected');
		$(this).parent().addClass('selected');
		var idx = 0;
		ul.find('li').each(function(i) {
			if($(this).hasClass('selected')) idx = i;							  
		});
		var m = idx * ul.find('.thumbnail div').height();
		ul.find('img:first').css({ marginTop: - m });
	});


	// Gift shop
	$('#store-item-thumbs a').click(function() {
		$('#store-item-thumbs .selected').removeClass('selected');
		$(this).parent().addClass('selected');
		$('#store-item-images img:first').attr('src', $(this).attr('href'));
		this.blur();
		return false;
	});
	$('.add-to-cart').hover(function() {
		$(this).css('backgroundPosition', '0 -30px');
	}, function() {
		$(this).css('backgroundPosition', '0 0');
	});	


	// Calendar
	$('a#set-range').click(function() {
		$('div#custom-range').slideToggle();
		return false;
	});
	
	
	// Preschool tour popups
	$('a.preschool-tour').click(function() {
		var props = 'width=616, height=482, scrollbars=0,'
		+ 'resizable=0, menubar=0, statusbar=0, directories=0';
		window.open($(this).attr('href'), 'tour', props);
		return false;									 
	});
	
	
	// Grants annual report popups
	$('a.grants-report').click(function() {
		var props = 'width=450, height=550, scrollbars=1,'
		+ 'resizable=0, menubar=0, statusbar=0, directories=0';
		window.open($(this).attr('href'), 'tour', props);
		return false;									 
	});
	
	
	// Initialize when doc is ready:
	features.initialize();
	schedule.initialize();
	videos.initialize();
	slides.initialize();
	gallery.initialize();
	lightbox.initialize();
	artboard.initialize();
	webcast.initialize();
	
});



// Features
var features = {
	timer: null,
	initialize: function() {
		if($('#home-top')) {
			$('#features ul').before('<ol></ol>');
			$('#features ul li').each(function(i) {
				$('#features ol').append('<li><a href="#">' + (i + 1) + '</a></li>');									
			});
			$('#features ol li:first').addClass('selected');
			$('#features ol li a').click(function() {
				var index = parseInt($(this).html()) - 1;
				features.skip(index); 
				return false;
			});
			/*$('#features ul img').click(function() {						 
				var href = $(this).parent().find('a').attr('href') || '';
				if(href.indexOf('#gallery/') > -1 || href.indexOf('#diary/') > -1) {
					var id = href.substring(href.lastIndexOf('#') + 1);
					gallery.launch(id);
					return false;
				}
				else document.location = href;
			}).attr('galleryimg', 'no');*/
			$('#features ul li').hide().eq(0).show();
			$(window).load(function() {
				features.timer = setTimeout('features.rotate(0)', 2000);
			});
		}
	},
	rotate: function(index) {
		$('#features ul li').eq(index).fadeOut("normal",function() {
			index = (index == $('#features ul li').length - 1) ? 0 : ++ index;
			features.indicator(index);
			$('#features ul li').eq(index).fadeIn("normal",function() {
				features.timer = setTimeout('features.rotate(' + index + ')', 6000);
			});
		});
	},
	skip: function(index) {
		clearTimeout(features.timer);
		features.indicator(index);
		$('#features ul li').hide().eq(index).show();
		features.timer = setTimeout('features.rotate(' + index + ')', 6000);
	},
	indicator: function(index) {
		$('#features ol li').removeClass('selected').eq(index).addClass('selected');
	}
}

// Worship schedule
var schedule = {
	offset: 0,
	data: null,
	initialize: function() {
		$('#schedule-prev').click(function() {
			schedule.advance(-1);
			return false;
		});
		$('#schedule-next').click(function() {
			schedule.advance(1);
			return false;
		});
		$('#schedule-selector li a').each(function(i) {
			$(this).click(function() {
				schedule.change(i);
				return false;
			});
		});
		schedule.advance(0);
	},
	advance: function(d) {
		if($('#schedule-selector').length) {
			schedule.offset = schedule.offset + d;
			$.post('/_ajax/calendar',{offset: schedule.offset}, function(data) {
				schedule.data = data;
				for(var i = 0; i < 7; i ++) {
					var li = $('#schedule-selector li').eq(i);
					li.find('span').html(data[i][0]);
					if(li.find('a').hasClass('selected')) schedule.change(i);
				}
			}, 'json');
		}
	},
	change: function(d) {
		$('#schedule-selector li a').removeClass('selected').eq(d).addClass('selected');
		var trinity = '';
		var stpauls = '';
		var webcast = '';
		var data = schedule.data[d];
		for(var n = 0; n < data[1].length; n ++) {
			trinity += '<li><a href="' + data[1][n][1] + '">'
			+ data[1][n][0] + '</a></li>';
		}
		for(var n = 0; n < data[2].length; n ++) {
			stpauls += '<li><a href="' + data[2][n][1] + '">'
			+ data[2][n][0] + '</a></li>';
		}
		for(var n = 0; n < data[3].length; n ++) {
			webcast += '<li><a href="' + data[3][n][1] + '">'
			+ data[3][n][0] + '</a></li>';
		}
		$('#schedule-trinity').html(trinity).find('li:first').addClass('first');
		$('#schedule-stpauls').html(stpauls).find('li:first').addClass('first');
		$('#schedule-webcast').html(webcast).find('li:first').addClass('first');
	}
}


// Video webcasts
var videos = {
	search: false,
	initialize: function() {
		$('#video-search').show();
		$('#video-search-submit').click(function() {
			$('#video-channels li').removeClass('selected');
			var q = $('#video-search-input').val() || '';
			videos.search = q;
			videos.page(null, null, q);
			this.blur();
			return false;
		});
		$('#video-search').find('form').submit(function() {
			$('#video-search-submit').trigger('click');
			return false;
		});
		$('#video-channels a').click(function() {
			videos.search = '';
			$('#video-search-input').val('');
			$('#video-channels li').removeClass('selected');
			var par = $(this).parent();
			par.addClass('selected').find('ul').slideDown();
			par.parent().parent().not('#video-nav').addClass('selected');
			$('#video-channels li').not('.selected').find('ul').slideUp();
			var cat = videos.getCat($(this).attr('href')) || '';
			videos.page(cat, null, null);
			return false;
		});
		$('#video-pool .pagination a').live('click', function() {
			if(!$(this).parent().hasClass('selected')) {
				var u = $('#video-channels .selected:last a').attr('href') || '';
				var c = videos.getCat(u);
				var q = videos.search || null;
				var h = $(this).attr('href');
				var p = parseInt(h.substring(h.lastIndexOf('/') + 1));
				videos.page(c, p, q);
			}
			return false;
		});
	},
	getCat: function(url) {
		return url.replace(/.*\/browse\//gi, '');
	},
	page: function(cat, page, query) {
		page = page || '';
		var post = videos.search.length ? 'search' : 'categories';
		$.post('/_ajax/videos/' + post + '/' + page,
			{ category: cat || '', query: query || '' },
 			function(data) {
				if(data.videos) {
					var list = '';
					jQuery.each(data.videos, function() {
						list += '<li><a href="' + this.link + '" title="' + this.title + '">'
						+ '<img src="/images/multimedia/videos/' + this.thumbnail
						+ '" width="130" height="58" alt="" /><span>' + this.title + '</span></a></li>';
					});
					$('#video-pool ul').html(list);
				}
				$('#video-pool .pagination ul:first').html(data.pagination);
		 	},
			'json'
		);
	}
}


// Article Slideshows
var slides = {
	initialize: function() {
		var current = 1;
		var preload = new Array();
		var images = $('#slideshow .slideshow-image').length;
		if(images) {
			$.each(images, function(i) {
				preload[i] = new Image();
				preload[i].src = $(this).find('img:first').attr('src');
			});
			if(images > 1) {
				$('#slideshow-nav').html('<a href="#" class="back"></a>'
				+ '<a href="#" class="next"></a><span>1 of ' + images + '</span>');
			}
			else if(!$('#slideshow .credit:first').html().length) {
				$('#slideshow .credit').hide();
			}
			$('#slideshow-nav a').click(function() {
				var d = $(this).hasClass('back') ? current - 1 : current + 1;
				if(d < 1) d = images;
				else if(d > images) d = 1;
				$('#slideshow .slideshow-image').eq(current - 1).fadeOut(function() {
					$('#slideshow .slideshow-image').eq(d - 1).fadeIn();
					$('#slideshow-nav span:first').html(d + ' of ' + images);
					current = d;
				});
				return false;
			});
		}
	}
}


// Photo Galleries
var gallery = {
	initialize: function() {
		var links = false;
		$('#page a').each(function() {
			var href = $(this).attr('href') || '';
			if(/#(gallery|diary|contest)\//.test(href)) {
				links = true;
				$(this).click(function() {
					var id = $(this).attr('href');
					id = id.substring(id.lastIndexOf('#') + 1);
					gallery.launch(id);
					return false;
				});
			}
		});
		if(links) {
			var preload = new Image();
			preload.src = '/images/news/photos/gallery-bg.png';	
		}
	},
	launch: function(id) {
		gallery.current = 0;
		gallery.lock = false;
		$('#gallery').remove();
		$.getJSON('/_ajax/' + id, function(data) {
			if(!data.error) {
				$(document.body).append(data.template);
				$('#gallery h1').html(data.title);
				gallery.center();
				$(window).resize(gallery.center);
				$(window).scroll(gallery.center);
				$('#gallery').fadeIn('fast');
				$('#gallery-close').click(function() {
					$(window).unbind('resize', gallery.center);
					$(window).unbind('scroll', gallery.center);
					$('#gallery').fadeOut('fast', function() {
						$('#gallery').remove();
					});
					return false;
				});
				$('#gallery-nav-back').click(function() {
					gallery.navigate(-1);
					return false;
				});
				$('#gallery-nav-next').click(function() {
					gallery.navigate(1);
					return false;
				});
				gallery.photos = data.photos;
				if(data.intro) {
					var io = {intro: data.intro};
					gallery.photos.unshift(io);	
				}
				var loadImage = null;
				var imgPreload = new Image(); 
				var pl = data.intro ? 1 : 0;
				imgPreload.src = gallery.photos[pl].path;
				imgPreload.onload = function() {
					$('#photo-pad').removeClass('images-loading');
					clearInterval(loadImage);
					gallery.navigate(1);
					
				}
				var loadImage = setInterval(function() {
					if(imgPreload.complete) {
						$('#photo-pad').removeClass('images-loading');
						clearInterval(loadImage);
						gallery.navigate(1);
					}
				}, 250);
				
			}
			else alert('An error has occurred.');
		});
	},
	navigate: function(i) {
		if(!gallery.lock) {
			gallery.current = gallery.current + i;
			if(gallery.current < 1) {
				gallery.current = 1;
				return;
			}
			if(gallery.current > gallery.photos.length) {
				gallery.current = gallery.photos.length;
				return;
			}
			$('#gallery a span').removeClass('disabled');
			if(gallery.current == 1) {
				$('#gallery-nav-back span').addClass('disabled');
			}
			if(gallery.current == gallery.photos.length) {
				$('#gallery-nav-next span').addClass('disabled');
			}
			else {
				preload = new Image();
				preload.src = gallery.photos[gallery.current].path;	
			}
			var img = gallery.photos[gallery.current - 1];
			if(img.intro) {
				$('#photo').before('<div id="gallery-intro">' + img.intro + '</div>');
				$('#photo-container').css('marginTop', 210 - $('#gallery-intro').height() / 2);
				$('#gallery-nav-back span').addClass('disabled');
				$('#gallery-nav-next span').removeClass('disabled');
				$('#photo-caption').html('');
				$('#photo').hide();
			}
			else {
				$('#gallery-intro').remove();
				gallery.lock = true;
				$('#photo').fadeOut(function() {
					$('#photo').attr({
						'src': img.path,
						'width': img.width,
						'height': img.height
					});
					$('#photo-caption').html(img.caption);
					$('#photo-container').css('marginTop', 210 - $('#photo').height() / 2);
					$('#photo').fadeIn(function() {
						gallery.lock = false;							
					});
				});
			}
		}
	},
	center: function() {
		var w = $(window);
		var d = $(document);
		var g = $('#gallery');
		var l = (w.width() / 2) - (g.width() / 2) + d.scrollLeft();
		var t = (w.height() / 2) - (g.height() / 2) + d.scrollTop() - 30;
		if(t < d.scrollTop()) t = d.scrollTop();
		g.css({left: l, top: t});
	}
}


// Lightbox (Single Image)
var lightbox = {
	initialize: function() {	
		$('img.lightbox').click(function() {
			var src = $(this).attr('src');
			var ext = src.substring(src.lastIndexOf('.'));
			src = src.substring(0, src.lastIndexOf('.')) + '-lboximg' + ext;
			lightbox.open(src, $(this).attr('title'), $(this).attr('alt'));
		});
		$('a.lightbox').click(function() {
			var src = $(this).find('img').attr('src');
			var ext = src.substring(src.lastIndexOf('.'));
			src = src.substring(0, src.lastIndexOf('.')) + '-lboximg' + ext;
			lightbox.open(src, $(this).attr('title'), $(this).find('img').attr('alt'));
			return false;
		});
	},
	open: function(img, caption, title) {
		title = title.length ? title : 'Trinity Wall Street';
		lightbox.caption = caption || '';
		lightbox.img = img;
		$.get('/_ajax/lightbox', function(template) {
			$(document.body).append(template);
			$('#gallery h1').html(title);
			$(window).resize(gallery.center);
			$(window).scroll(gallery.center);
			$('#gallery-close').click(function() {
				$(window).unbind('resize', gallery.center);
				$(window).unbind('scroll', gallery.center);
				$('#gallery').fadeOut('fast', function() {
					$('#gallery').remove();
				});
				return false;
			});
			gallery.center();
			$('#gallery').fadeIn('fast');
			var imgPreload = new Image(); 
			imgPreload.src = img;
			lightbox.loadImage = setInterval(function() {
				if(imgPreload.complete) lightbox.loaded();
			}, 250);
			imgPreload.onload = function() {
				lightbox.loaded();
			}
		});
	},
	loaded: function() {
		$('#photo-pad').removeClass('images-loading');
		clearInterval(lightbox.loadImage);
		$('#photo').attr({ 'src': lightbox.img }).show();
		$('#photo-caption').html(lightbox.caption);
		$('#photo-container').css('marginTop', 210 - $('#photo').height() / 2);		
	}
}


// Preschool artwork popups
var artboard = {
	initialize: function() {
		$('#artboard-content').find('a').click(function() {
			var src = $(this).find('img:first').attr('src');
			var img = src.substring(0, src.length - 4) + '.jpg';
			var orient = $(this).parent().hasClass('landscape') ? 'landscape' : 'portrait';
			var name = $(this).parent().find('span:first').html();
			artboard.popup(img, orient, name);			
			return false;
		});
	},
	popup: function(img, orient, name) {
		$('#artboard-popup').remove();
		var w = 246;
		var h = 338;
		if(orient == 'landscape') {
			w = 338;
			h = 246;
		}
		$('#artboard-content').prepend('<div id="artboard-popup"><div>'
		+ '<a href="#">X</a>' + name + '</div><img src="' + img + '" class="'
		+ orient + '" width="' + w + '" height="' + h + '" /></div>');
		$('#artboard-popup').css('margin-top', ($(window).scrollTop() / 2) + 23);
		$('#artboard-popup a').click(function() {
			$('#artboard-popup').remove();
			return false;
		});
	}
}



// Comments for Webcasts
var webcast = {
	inc: 0,
	initialize: function() {
		$('#webcast-comments-refresh').click(function() {
			var id = $('#webcast-id').html();
			webcast.inc ++;
			$.ajax({
				type: 'post',
				url: '/_ajax/webcast/' + id + '/comments/?' + webcast.inc,
				dataType: 'json',
				success: function(data) {
					var coms = '';
					$.each(data, function(i) {
						coms += '<div class="comment"><div class="comment-index">'
						+ (i + 1) + '</div><div class="comment-body"><p>' + data[i].comment
						+ '</p><p class="comment-info">' + data[i].name + ' on '
						+ data[i].date + '</p></div></div>';	  
					});
					if(!coms.length) coms = '<p class="none-found">No comments yet.</p>';
					$('#comment-list').html(coms + '<div id="end"></div>');
				},
				error: function() {
					alert('Something went wrong. Please try again.');
				}		
			});
		});
		$('#webcast-comments-form').submit(function() {
			var id = $('#webcast-id').html();
			var n = $('#comment-name').val();
			var c = $('#comment-body').val();
			var errors = '';
			if(!n.length) errors += '- Enter your name.\n';
			if(!c.length) errors += '- Enter your comment.';
			if(errors.length) {
				alert('Please fix the following, then try again:\n\n' + errors);
			}
			else {
				$.ajax({
					type: 'post',
					url: '/_ajax/webcast/' + id + '/comments/new',
					data: {
						'name': n,
						'comment': c
					},
					success: function(data) {
						if(data == 'false') {
							alert('Something went wrong. Please try again.');
						}
						else if(data == 'timeout') {
							alert('Please wait 2 minutes before sumbitting another comment.');
						}
						else {
							$('#webcast-comments-refresh').trigger('click');
							$('#comment-name').val('');
							$('#comment-body').val('');
						}
					},
					error: function() {
						alert('Something went wrong. Please try again.');
					}
				});
			}
			return false;
		});
		$('#videos-share input').focus(function() {
			$(this).select();
		});
	}
}
