(function($) {
	var shows = new Array;
	var current = new Object;
	var confirmMessage = "Welcome to South Bend Civic Theatre’s online ticketing!\n\nTo keep your transaction safe and to provide real-time links to our seating map, your online experience will be handled by a secure site that charges a per ticket handling fee.\n\nTo avoid the additional charge of $2 per ticket, call our box office between noon and 6 weekdays: 574-234-1112, or visit us at 403 N. Main, downtown South Bend.\n\nIf you still want to guarantee the best seats possible with an online reservation, (or want to check seating availability), hit the \"OK\" button… and enjoy the show!  Otherwise, hit \"Cancel\" to return to the South Bend Civic Theatre site.";
	
	// INDIVIDUAL SHOW FUNCTIONS
	$.fn.show = function() {
		return this.each(function(){
			$(this).click(function(e){
				$(this).addClass('current').parent().siblings().find('a').removeClass('current');
				current.url = getVariable($(this).attr('href'));
				current.type = 'show';
				SWFAddress.setValue('show/'+current.url);
				pageTracker._trackPageview('show/'+current.url);
				//clearStage();
				return false;
			});
		});		  
	};
	
	$.fn.show.start = function() { 
		var c = null;
		$(shows[current.year]).each(function(i,s) { if(s.url == current.url) c=s; });
		if(!c) {
			for(var i=current.startingYear+1;  i>2005; i--)
				$(shows[i]).each(function(i,s) { if(s.url == current.url) { c=s; current.year=i; return true; }});
		}
		if(!c) { setTimeout($.fn.show.start, 300); return false; };
		$('<img id="show-image" src="" alt="" />').appendTo('#mask').css({ left:'-560px' }).unbind("load").bind("load",imageLoaded);
		$('<div id="show-title">'+(c.tickets_url ? (c.sold_out ? '<img src="images/sold-out.jpg" alt="Sold Out" />' : '<a href="'+c.tickets_url+'" class="order-tickets"><img src="images/order-tickets.jpg" alt="Order Tickets Online" /></a>') : '')+'<h2>'+c.name+'</h2><p id="byline">'+c.byline+'</p></div>').appendTo('#mask').css({ opacity:0 });
		handleTicket();
		$.fn.show.setupDescription(c);
		$('#show-image').attr('src', '/images/shows/'+c.image).attr('alt', c.name); 
	};
	
	function imageLoaded() {
		$(this).animate({ left:'10px' }, 350);
		$('#show-title').animate({ opacity:1 }, 300);
		$('#show-description').animate({ bottom:0 }, { duration:800, easing:'easeOutElastic' });
		//$('#show-description').animate({ bottom:0 }, { duration:300 });
	};
	
	function handleTicket() {
		$('a.order-tickets').click(function() {
			var answer = window.confirm(confirmMessage);
			if(answer) {
				window.open(this.href, "_blank");
			};
			return false;
		});
	};
	
	$.fn.show.setupDescription = function(c) {
		var html = 				'<a class="current-view" href="/?c=show&i='+c.url+'&p=synopsis">Synopsis</a>';
		if(c.times) html += 	' | <a href="/?c=show&i='+c.url+'&p=times">Times</a>';
		if(c.gallery) html +=	' | <a href="/?c=gallery&i='+c.galleryImage+'">Gallery</a>';
		$('<div id="show-description"><h3>'+html+'</h3></div>').appendTo('#mask');
		
		var sponsors = 	''
		if(c.sponsors && c.sponsors.length>0) {
			sponsors += '<p id="sponsors-list"><strong>Sponsored By:</strong><br />';
			for(var i=0; i<c.sponsors.length; i++) 
				sponsors += 	'- <a href="http://'+c.sponsors[i].url+'" target="_blank">'+c.sponsors[i].name+'</a><br />';
			sponsors += 	'</p>';
		}
		
		$('<div id="synopsis">'+c.synopsis+sponsors+'</div>').appendTo('#show-description');
		if(c.times) $('<div id="times"><p style="margin: 5px 0pt -10px 10px; font-weight:bold;">'+c.series+'</p>'+c.times+sponsors+'</div>').appendTo('#show-description').css({ display:'none' });
		if(c.gallery) {
			$('<div id="gallery"><div id="gallery-preview"><img src="images/galleries/'+c.galleryImage+'" alt="'+c.name+'" /></div>'+c.galleryDescription+'<p><strong><a href="/?c=gallery&i='+c.galleryURL+'">View Gallery ></a></strong></p></div>').appendTo('#show-description').css({ display:'none' });
			$('#gallery a').gallery();
		}
		
		$('#show-description').css({ bottom:-$('#show-description').height() });
		$.fn.show.handleDescription();
	}
	
	$.fn.show.handleDescription = function() {
		$('#show-description h3 a').click(function() {
			$(this).addClass('current-view').siblings().removeClass('current-view'); 
			$('#'+$(this).text().toLowerCase()).css({ display:'block' }).siblings('div').css({ display:'none' }); 
			return false; 
		});
	}
	
	// GALLERY FUNCTIONS 
	$.fn.gallery = function() {
		return this.each(function(){
			$(this).click(function(e){
				current.url = getVariable($(this).attr('href'));
				current.type = 'gallery';
				SWFAddress.setValue('gallery/'+current.url);
				pageTracker._trackPageview('gallery/'+current.url);
				//clearStage();
				return false;
			});
		});		  
	}
	
	$.fn.gallery.start = function(gallery) {
		$('<div id="gallery-caption">'+gallery.images[0].caption+'</div>').appendTo('body').css({ height:0 });
		var h = $('#gallery-caption p').height();
		if(h) $('#gallery-caption').animate({ height:h+6 });
		$('<div id="gallery-main"><img src="/images/galleries/'+gallery.images[0].filename+'" alt="'+gallery.name+'" /></div>').appendTo('#mask').css({ top:'-500px' }).animate({ marginTop:0 }, 300).animate({ top:'40px' }, { duration:800, easing:"easeOutElastic" });
		$('<div id="gallery-thumbs-container"><div id="gallery-controls"></div><div id="gallery-thumbs-mask"><div id="gallery-thumbs"></div></div>').appendTo('#mask').css({ left:'700px' }).animate({ marginTop:0 }, 600).animate({ left:'0' }, { duration:1000, easing:"easeOutElastic" });
		$(gallery.images).each(function(i,img) {
			$('<img src="/images/galleries/thumbs/'+img.filename+'" alt="'+gallery.name+'" />').appendTo('#gallery-thumbs').css({ cursor:'pointer', opacity:.75 }).hover(function() { $(this).animate({ opacity:1 },200) }, function() { $(this).stop().animate({ opacity:.75 },200); }).click(function() { $.fn.gallery.nextImage(img); });				
		});	
		if(gallery.images.length>4) $.fn.gallery.setupArrows(gallery.images.length);	
	}
	
	$.fn.gallery.setupArrows = function(count) {
		var xPos = 0;
		$('<img src="/images/gallery-prev.jpg" alt="Previous" />').appendTo('#gallery-controls').css({ position:'absolute', left:'10px', opacity:0 }).click(function() { 
			$(this).siblings().animate({ opacity:1 }); 
			xPos = (xPos+280>=0 ? 0 : xPos+280); 
			$('#gallery-thumbs').animate({ left:xPos }); 
			if(xPos>=0) { $(this).animate({ opacity:0 }); } 
			return false; 
		});
		$('<img src="/images/gallery-next.jpg" alt="Next" />').appendTo('#gallery-controls').css({ position:'absolute', right:'10px' }).click(function() { 
			$(this).siblings().animate({ opacity:1 }); 
			var t = count*140-10;
			xPos = (-(t-550)<xPos-280 ? xPos-280 : -(t-550)); 
			$('#gallery-thumbs').animate({ left:xPos });
			if(-(t-550)>xPos-280) { $(this).animate({ opacity:0 }); } 
		});
	}
	
	$.fn.gallery.nextImage = function(img) {
		$('#gallery-caption').animate({ height:0 },150);
		$('#gallery-main img').stop().animate({ opacity:0 }, 'fast', function() {
			$('#gallery-caption').html(img.caption);
			var h = $('#gallery-caption p').height();
			$('#gallery-caption').animate({ height:(h ? h+6 : 0) }, 200);
			$(this).load(function() { $(this).animate({ opacity:1 }, { duration:'fast', queue:false }); }).attr('src','/images/galleries/'+img.filename);
		});	
	}
	
	// SCHEDULE FUNCTIONS 
	$.fn.schedule = function() {
		return this.each(function(){
			$(this).click(function(e){
				current.year = current.url = getVariable($(this).attr('href'));
				current.type = 'schedule';
				SWFAddress.setValue('schedule/'+current.url);
				pageTracker._trackPageview('schedule/'+current.url);
				//clearStage();
				return false;
			});
		});		  
	}
	
	$.fn.schedule.start = function() {
		var html = '';
		var cMonth = '';
		$(shows[current.year]).each(function(i,s) {
			if(cMonth != s.month) { html += (cMonth ? '</div>' : '') + '<div class="schedule-month"><h2>'+s.month+'</h2>'; cMonth = s.month; }
			html += '<p class="'+s.series_filter+'"><a href="/?c=show&i='+s.url+'">'+s.name+'</a><br />'+s.series+'<br />'+s.details+'</p>';
		});
		html += '</div>';
		var schedule = $('<div id="schedule-full">'+html+'</div>').appendTo('#mask').css({ position:'absolute', top:'640px' }).animate({ top:0 }, { duration:600, easing:'easeOutElastic' }).find('a').show();
		
		$('#mask').mousewheel(function(event, delta) {
			var top = $('#schedule-full').css('top');
			var height = $('#schedule-full').height();
			top = Number(top.slice(0,-2));
			if (delta > 0) if(top+100<0) $('#schedule-full').stop().animate({ top:'+=100px' },150); else $('#schedule-full').stop().animate({ top:0 });
			else if (delta < 0) if(height>-(top-550)) $('#schedule-full').stop().animate({ top:'-=100px' },150); 
			return false;
		});
		
		html = 	'<h3>'+current.year+' Full Schedule</h3>';
		html +=	'<p>For more information on any of our show, simply click the name of the show to the left.</p><p>To scroll the schedule, use the scroll button on your mouse of the arrows below.</p>';
		html += '<p class="list">';
		if(shows[Number(current.startingYear)+1]) html += '<a href="/?c=schedule&i='+(Number(current.startingYear)+1)+'">View '+(Number(current.startingYear)+1)+' Schedule</a><br />';
		for(var i=current.startingYear;  i>2005; i--)
			html += '<a href="/?c=schedule&i='+i+'">View '+i+' Schedule</a><br />';
		html += '<a href="/files/sbct-season-archive.pdf" target="_blank">View Season Archive (pdf)</a></p>';
		html += '<p class="filter">Show: <select><option value="">All Series</option><option value="mainstage">MainStage Season</option><option value="studio">Studio Season</option><option value="family">Family Series</option></select></p>';
		html += '<p class="arrows"><a href="/?c=schedule&i='+current.year+'"><img src="/images/schedule-up.jpg" alt="Move Schedule Up" /></a><a href="/?c=schedule&i='+current.year+'"><img src="/images/schedule-down.jpg" alt="Move Schedule Down" /></a></p>';
		$('<div id="schedule-description">'+html+'</div>').appendTo('#mask').css({ right:'-300px' }).animate({ right:'-3px' })
			.find('.filter select').css({ width:'175px', padding:'2px', margin:'0 10px'  }).change(filterSchedule);	
		if($('p.bonus')[0]) $('<option value="bonus">Bonus Production</option>').appendTo('.filter select');
		$('.list a').not(':last').schedule();
		
		var height = 0;
		$('.arrows a:first').css({ opacity:0 }).click(function() { 
			if($(this).css('opacity')==1) {
				height = (height+250>=0 ? 0 : height+250); 
				$('#schedule-full').animate({ top:height }); 
				$(this).siblings().animate({ opacity:1 }); 
				if(height>=0) { $(this).animate({ opacity:0 }); } 
			}
			return false; x	
		});
		$('.arrows a:last').click(function() {
			if($(this).css('opacity')==1) {
				height = (height-250<=(550-$('#schedule-full').height()) ? 550-$('#schedule-full').height(): height-250); 
				$('#schedule-full').animate({ top:height }); 
				$(this).siblings().animate({ opacity:1 }); 
				if (height == (550-$('#schedule-full').height())) { $(this).animate({ opacity:0 }); } 
			}
			return false; 
		});
	}
	
	// SHARED FUNCTIONS
	function clearStage() {
		if(current.type != 'show') $('#show-list li a, #show-list-schedule li a').removeClass('current');
		$(':animated').stop();
		$('#show-image').animate({ left:'-560px' }, 200, "linear", startNext);
		$('#show-title').animate({ opacity:0 }, 200);
		$('#show-description').animate({ bottom:-$('#show-description').height() }, 200);
		$('#schedule-full').animate({ top:'640px' }, 200);
		$('#schedule-description').animate({ right:'-300px' }, 200, "linear", startNext);
		$('#gallery-main').animate({ top:'-500px' }, 300, "linear", startNext);
		$('#gallery-thumbs-container').animate({ left:'700px' }, 250);
		$('#gallery-caption').animate({ height:0 }, 200);
	}
	
	function startNext() {
		$('#gallery-caption').remove();
		$('#mask').html('');
		switch(current.type) {
			case 'show':		$.fn.show.start();
								break;
			case 'schedule':	if(!shows[current.year]) $.getJSON('/ajax-data.php', { action:'getYear', year:current.year }, function(res) { shows[current.year] = res.schedule.shows; $.fn.schedule.start(); });
								else $.fn.schedule.start();
								break;
			case 'gallery':		$.getJSON('/ajax-data.php', { action:'getGallery', galleryURL:current.url }, $.fn.gallery.start);
								break;
			default:		break;
		}
	}
	
	function getVariable(url) {
		var p = url.indexOf('i');
		if(!p) return false;
		url = url.substr(p+2);
		if(url.indexOf('&')>-1) url = url.substr(0, url.indexOf('&'));
		return url;
	}
	
	function handleYearJSON(res) {
		current.year = res.schedule.year;
		if(!current.startingYear) current.startingYear = current.year;
		shows[current.year] = res.schedule.shows;
	}
	
	function filterSchedule() {
		$('#schedule-full').css({ top:0 });
		if(this.value) {
			var v = this.value;
			$('.schedule-month').css({ display:'block' }).each(function() {
				$(this).find('p').css({ display:'none' }).filter('.'+v).css({ display:'block' });
				if(!$(this).find('p:visible')[0]) $(this).css({ display:'none' });
			});
		} else {
			$('.schedule-month').css({ display:'block' }).find('p').css({ display:'block' });
		}
		$('.arrows a').eq(0).animate({ opacity:0 }).end().eq(1).each(function() {
			if ($('#schedule-full').height()>550) { $(this).animate({ opacity:1 }); }
			else $(this).animate({ opacity:0 });
		});
	}; 
	
	function handleAlertMessage(res) {
		if(res) {
			$('<div id="overlay"></div>').appendTo('body').css({ width:$('body').width(), height:$(document).height(), display:'block' }).fadeIn(300, function() {
				$('<div id="alertMessage"><div><h2>'+res.headline+'</h2>'+res.message+'<p class="alertClose" style="text-align:right; font-weight:bold; margin:2px 8px; text-transform:uppercase; font-size:88%; cursor:pointer;">Close</p></div></div>').appendTo('body').css({ width:400, left:($('body').width()-400)/2 }).find('.alertClose').click(hideAlertMessage);	
				$('<div id="alertMessageDS"></div>').appendTo('body').css({ width:$('#alertMessage').attr('offsetWidth'), height:$('#alertMessage').attr('offsetHeight'), position:'absolute', zIndex:999, background:'#000', top:parseInt($('#alertMessage').css('top'))+10, left:parseInt($('#alertMessage').css('left'))+10, opacity:.2 });	
			});
		};
	};
	
	function hideAlertMessage() {
		$('#alertMessage,#alertMessageDS').remove();
		$('#overlay').stop().fadeOut(300, function() { $(this).remove(); });
	};
	
	$(document).ready(function() {
		$.getJSON('/ajax-data.php', { action:'getYear', year:'prev' }, handleYearJSON); 
		$.getJSON('/ajax-data.php', { action:'getYear' }, handleYearJSON); 
		$.getJSON('/ajax-data.php', { action:'getYear', year:'next' }, handleYearJSON);
		$.getJSON('/ajax-data.php', { action:'getAlertMessage' }, handleAlertMessage);
		$('<div id="mask"></div>').appendTo('#window').css({ width:$('#window').width()-6, height: $('#window').height()-3, overflow:'hidden', position:'relative', marginLeft:'3px' });
		$('#window').children().not(':last').appendTo('#mask');
		
		$('#show-list li a, #show-list-schedule li a').show();				   
		$('#schedule-button').schedule();
		$('#gallery-button').gallery();
		$('#show-description #gallery a').gallery();
		
		handleTicket();
		
		var first = '';
		SWFAddress.addEventListener(SWFAddressEvent.CHANGE, function(e) {
			var p = e.target.getPathNames();
			if(p != '') {
				current.type = p[0];
				current.url = p[1];
				if(current.type == 'schedule') current.year = p[1];
				clearStage();
			} else if(first) {
				current.type = 'show';
				current.url = first;
				clearStage();
			} else {
				first = getVariable($('#show-list a:first, #show-list-schedule a:first').attr('href'));
				$.fn.show.handleDescription();
			}
		});
	});
})(jQuery);