var tix = {
	
	init: function(marketId, marketUrl, marketName)
	{
		this.marketId = marketId;
		this.marketUrl = marketUrl;
		this.marketName = marketName;
		
		$.template('marketFilterTmpl',	'<div class="box rounded shadow">'+
								'<div class="bar rounded-top"><h2>Date</h2></div>'+
								'<p><select id="market-date">'+
								'{{each Dates}}'+
								'<option value="${DateId}">${SessionDate}</option>'+
								'{{/each}}'+
								'</select></p>'+
								'</div>'+
								'<div class="box rounded shadow">'+
								'<div class="bar rounded-top"><h2>Theaters</h2></div>'+
								'<ul>'+
								'{{each Cinemas}}'+
								'<li><input type="checkbox" value="#nav-${CinemaId}" class="nav-toggle" checked="checked" /> ${CinemaName}</li>'+
								'{{/each}}'+
								'</ul>'+
								'</div>'+
								'<div class="box rounded shadow">'+
								'<div class="bar rounded-top"><h2>Programming</h2></div>'+
								'<ul>'+
								'<li><input type="checkbox" value=".nav-NewRelease" class="nav-toggle" checked="checked" /> New Release Movies</li>'+
								'<li><input type="checkbox" value=".nav-Series" class="nav-toggle" checked="checked" /> Alamo Signature Series</li>'+
								'</ul>'+
								'</div>');	
			
		$.template('marketDatesTmpl',	'<em>Select a Date &#187;</em>'+
								'<select class="div-selector" id="market-date">'+
								'{{each Dates}}'+
								'<option value="${DateId}">${SessionDate}</option>'+
								'{{/each}}'+
								'</select>');
		
		$.template('marketTmpl', 	'{{each Cinemas}}'+
									'<div class="box rounded shadow" id="nav-${CinemaId}">'+
									'<div class="bar rounded-top"><a class="bar" href="${CinemaURL}"><h3>${CinemaName}</h3></a></div>'+
									'{{each Films}}'+
									'<div class="segment nav-${FilmType} clear">'+
									'<h5><a href="/uid/${FilmId}/'+tix.marketUrl+'" target="_parent">${Film}</a></h5>'+
									'<ul class="clear">'+
									'{{each Sessions}}'+
									'<li class="${SessionStatus}">'+
									'{{if SessionStatus == "notonsale"}}'+
									'<span title="Tickets are not yet available">${SessionTime}</span>'+
									'{{else SessionStatus == "soldout"}}'+
									'<span title="Tickets are sold out">${SessionTime}</span>'+
									'{{else SessionStatus == "past"}}'+
									'<span>${SessionTime}</span>'+
									'{{else}}'+
									'<a href="${SessionSalesURL}">${SessionTime}</a>'+
									'{{/if}}'+
									'{{each SessionAttributes}}'+
									'<h6>${AttributeId}</h6>'+
									'{{/each}}'+
									'</li>'+
									'{{/each}}'+
									'</ul>'+
									'</div>'+
									'{{/each}'+
									'}'+
									'</div>'+
									'{{/each}}');
		
		$.template('showLinksTmpl',	'{{each Dates}}'+
									'<div class="showtimes" id="showtimes-${DateId}">'+
									'<h3 class="segment">${Date}</h3>'+
									'{{each Cinemas}}'+
									'<div class="segment">'+
									'<a href="${CinemaURL}"><h4>${CinemaName}</h4></a>'+
									'<div class="showtimes-row clear">'+
									'<h5>Tickets:</h5>'+
									'<ul class="clear">'+
									'{{each Sessions}}'+
									'<li class="${SessionStatus}">'+
									'{{if SessionStatus == "notonsale"}}'+
									'<span title="Tickets are not yet available">${SessionTime}</span>'+
									'{{else SessionStatus == "soldout"}}'+
									'<span title="Tickets are sold out">${SessionTime}</span>'+
									'{{else SessionStatus == "past"}}'+
									'<span>${SessionTime}</span>'+
									'{{else}}'+
									'<a href="${SessionSalesURL}">${SessionTime}</a>'+
									'{{/if}}'+
									'{{each SessionAttributes}}'+
									'<h6>${AttributeId}</h6>'+
									'{{/each}}'+
									'</li>'+
									'{{/each}}'+
									'</ul>'+
									'</div> <!-- .showtimes-row -->'+
									'</div>'+
									'{{/each}}'+
									'</div>'+
									'{{/each}}');
		
		$.template('seriesLinksTmpl',	'{{each Films}}'+
										'<section class="box rounded shadow">'+
										'<header class="bar rounded-top"><h2><a href="/uid/${FilmId}/'+tix.marketUrl+'">${Film}</a></h2></header>'+
										'{{each Cinemas}}'+
										'<div class="segment">'+
										'<a href="${CinemaURL}"><h4>${CinemaName}</h4></a>'+
										'{{each Dates}}'+
										'<div class="showtimes-row clear">'+
										'<h5>${Date}:</h5>'+
										'<ul class="clear">'+
										'{{each Sessions}}'+
										'<li class="${SessionStatus}">'+
										'{{if SessionStatus == "notonsale"}}'+
										'<span title="Tickets are not yet available">${SessionTime}</span>'+
										'{{else SessionStatus == "soldout"}}'+
										'<span title="Tickets are sold out">${SessionTime}</span>'+
										'{{else SessionStatus == "past"}}'+
										'<span>${SessionTime}</span>'+
										'{{else}}'+
										'<a href="${SessionSalesURL}">${SessionTime}</a>'+
										'{{/if}}'+
										'{{each SessionAttributes}}'+
										'<h6>${AttributeId}</h6>'+
										'{{/each}}'+
										'</li>'+
										'{{/each}}'+
										'</ul>'+
										'</div> <!-- .showtimes-row -->'+
										'{{/each}}'+
										'</div>'+
										'{{/each}}'+
										'</section>'+
										'{{/each}}');
		
		$.template('eventsTmpl','{{each Films}}'+
								'<li><a href="/uid/${FilmId}/'+tix.marketUrl+'"><img src="${FilmImageUrl}" width="188" height="279" alt="${Film}" /></a>'+
								'{{/each}}');
								
		$.template('moreEventsTmpl','{{each Films}}'+
									'{{if FilmId != tix.ignore}}'+
									'<li><a href="/uid/${FilmId}/'+tix.marketUrl+'">${Film}</a>'+
									'{{/if}}'+
									'{{/each}}');
		
		$.template('theaterLinksTmpl',	'{{each Dates}}'+
										'<div class="showtimes" id="theater-${DateId}">'+
										'<h3 class="segment">${Date}</h3>'+
										'{{each Films}}'+
										'<div class="segment">'+
										'<h4><a href="/uid/${FilmId}/'+tix.marketUrl+'" target="_parent">${Film}</a></h4>'+
										'<div class="showtimes-row clear">'+
										'<h5>Tickets:</h5>'+
										'<ul class="clear">'+
										'{{each Sessions}}'+
										'<li class="${SessionStatus}">'+
										'{{if SessionStatus == "notonsale"}}'+
										'<span title="Tickets are not yet available">${SessionTime}</span>'+
										'{{else SessionStatus == "soldout"}}'+
										'<span title="Tickets are sold out">${SessionTime}</span>'+
										'{{else SessionStatus == "past"}}'+
										'<span>${SessionTime}</span>'+
										'{{else}}'+
										'<a href="${SessionSalesURL}">${SessionTime}</a>'+
										'{{/if}}'+
										'{{each SessionAttributes}}'+
										'<h6>${AttributeId}</h6>'+
										'{{/each}}'+
										'</li>'+
										'{{/each}}'+
										'</ul>'+
										'</div> <!-- .showtimes-row -->'+
										'</div>'+
										'{{/each}}'+
										'</div>'+
										'{{/each}}');
		
		$.template('dateTmpl',	'{{each Dates}}'+
								'<option value="${DivId}-${DateId}">${Date}</option>'+
								'{{/each}}');
		
		$.template('showModalTmpl',	'<div class="bar rounded-top"><h2>Buy Tickets: <em>${title}</em></h2></div>'+
									'<div class="clear" id="quickTix">'+
									'<img src="${imgSrc}" width="${imgWidth}" height="${imgHeight}" />'+
									'<div class="show" id="showtimes"></div>'+
									'</div>'+
									'<nav class="bottom rounded-bottom clear"><a href="#" onclick="Shadowbox.close()" class="button shadow">Close</a> <select class="div-selector" id="showtimes-select"></select></nav>');
		
		$.template('theaterModalTmpl',	'<div class="bar rounded-top"><h2>Showtimes: <em>${title}</em></h2></div>'+
										'<div class="theater" id="theater-showtimes"></div>'+
										'<nav class="bottom rounded-bottom clear"><a href="#" onclick="Shadowbox.close()" class="button shadow">Close</a> <select class="div-selector" id="theater-select"></select></nav>');
		
		$.template('calFilterTmpl',	//'<h5>Select Theater:</h5>'+
									//'<p><select id="cal-select">'+
									//'{{each Cinemas}}'+
									//'<option value="${CinemaId}">${CinemaName}</option>'+
									//'{{/each}}'+
									//'</select></p>'+
									//'<h5>Select:</h5>'+
									'<ul>'+
									'<li><input type="checkbox" value=".s-NewRelease" class="cal-toggle" checked="checked" /> New Release Movies</li>'+
									'<li><input type="checkbox" value=".s-Series" class="cal-toggle" checked="checked" /> Alamo Signature Series</li>'+
									'</ul>');
		
		$.template('calLinksTmpl',	'{{each Months}}'+
									'<div class="box rounded shadow calendar">'+
									'<div class="bar rounded-top"><h2><a class="bar" href="${CinemaURL}">${CinemaName}</a>: <em>${Month}</em></h2></div>'+
									'<table>'+
									'<thead>'+
									'<tr>'+
									'<td>Sunday</td>'+
									'<td>Monday</td>'+
									'<td>Tuesday</td>'+
									'<td>Wednesday</td>'+
									'<td>Thursday</td>'+
									'<td>Friday</td>'+
									'<td>Saturday</td>'+
									'</tr>'+
									'</thead>'+
									'<tbody>'+
									'{{each Weeks}}'+
									'<tr>'+
									'{{each Days}}'+
									'<td>'+
									'<h3>${Day}</h3>'+
									'{{each Films}}'+
									'<p class="s-${FilmType}"><strong><a href="/uid/${FilmId}/'+tix.marketUrl+'">${Film}</a></strong></br>'+
									'{{each Sessions}}'+
									'{{if SessionStatus == "notonsale"}}'+
									'<span class="${SessionStatus}" title="Tickets are not yet available">${SessionTime}</span>'+
									'{{else SessionStatus == "soldout"}}'+
									'<span class="${SessionStatus}" title="Tickets are sold out">${SessionTime}</span>'+
									'{{else SessionStatus == "past"}}'+
									'<span>${SessionTime}</span>'+
									'{{else}}'+
									'<a href="${SessionSalesURL}">${SessionTime}</a>'+
									'{{/if}} '+
									'{{/each}}</p>'+
									'{{/each}}'+
									'</td>'+
									'{{/each}}'+
									'</tr>'+
									'{{/each}}'+
									'</tbody>'+
									'</table>'+
									'</div>'+
									'{{/each}}');
	},
	
/*************************************/
/*                                   */
/* Data Request Callbacks - Sessions */
/*                                   */
/*************************************/
	
	marketLinks: function(data)
	{
		$('#market').empty().append($.tmpl('marketTmpl', data.Market));
		$('#market-header').html(data.Market.Date);
		$('#market .segment.eq(0)').addClass('first');
		$('#market .segment:last-child').addClass('last');
		
		$('#market li span').tipsy({fade: true});
		
		tix.checkFilters('.nav-toggle');
		tix.checkEmpties('#market');
	},
	
	calendarLinks: function(data)
	{
		$('#calendar').empty().append($.tmpl('calLinksTmpl', data.Cinema));
		
		tix.checkFilters('.cal-toggle');
			
		$('#calendar span').tipsy({fade: true});
	},
	
	showLinks: function(data)
	{
		if (data.Film)
		{
			data.Film.DivId = 'showtimes';
			
			$('#showtimes').empty().append($.tmpl('showLinksTmpl', data.Film));
			$('#showtimes-select').empty().append($.tmpl('dateTmpl', data.Film));
			
			$('#showtimes-select').divSelector('#showtimes');
			
			$('#showtimes span').tipsy({fade: true});
		}
		else
		{
			$('#showtimes').append('<h3 class="segment error">Unable to find showtimes in '+tix.marketName+'.</h3></div>');
			$('#showtimes-select').parent().remove();
		}
	},
	
	seriesLinks: function(data)
	{
		if (data.Series)
		{
			data.Series.DivId = 'showtimes';
			
			$('#events').empty().append($.tmpl('eventsTmpl', data.Series)).wrapChildren({ childElem : 'li' , sets: 3}).carousel({ nav:'#events-nav' });
			
			$('#showtimes').empty().append($.tmpl('seriesLinksTmpl', data.Series));
		
			$('#showtimes span').tipsy({fade: true});
		}
		else
		{
			$('#events').closest('section').remove();
		}
	},
	
	moreEvents: function(data)
	{
		if (data.Series)
		{
			$.when($('#more-events').empty().append($.tmpl('moreEventsTmpl', data.Series))).done(function()
			{
				if ($('#more-events li').length == 0)
				{
					$('#more-events').closest('section').remove();
				}
			});	
		}		
	},
	
	theaterLinks: function(data)
	{
		if (data.Cinema)
		{
			data.Cinema.DivId = 'theater';
			
			$('#theater-showtimes').empty().append($.tmpl('theaterLinksTmpl', data.Cinema));
			$('#theater-select').empty().append($.tmpl('dateTmpl', data.Cinema));
			
			$('#theater-select').divSelector('#theater-showtimes');
			
			$('#theater-showtimes span').tipsy({fade: true});
		}
		else
		{
			$('#theater-showtimes').append('<h3 class="segment error">Unable to find showtimes.</h3></div>');
			$('#theater-select').remove();
		}
	},
	
/************************************/
/*                                  */
/* Data Request Callbacks - Filters */
/*                                  */
/************************************/
	
	marketFilter: function(data)
	{
		$('#market-filter').empty().append($.tmpl('marketFilterTmpl', data.Market));
		
		$('#market-date').change(function()
		{
			tix.getMarketLinks($(this).val(), tix.marketId);
		});
		
		$('#market-date').change();
		
		$('.nav-toggle').change(function()
		{		
			tix.checkFilters('.nav-toggle');
			
			$('#market').checkEmpties();
		});
	},
	
	marketDates: function(data)
	{
		$('#market-filter').empty().append($.tmpl('marketDatesTmpl', data.Market));
		
		$('#market-date').change(function()
		{
			tix.getMarketLinks($(this).val(), tix.marketId);
			
			var label = $(this).find('option:selected').text().split(", ");
			
			$('#market-filter-title').html("Showtimes: " + label[1] + ", " + label[2]);
		});
		
		$('#market-date').change();
	},
	
	calendarFilter: function(data)
	{		
		$('#calendar-filter').append($.tmpl('calFilterTmpl', data.Market));
		
		$('#cal-select').change(function()
		{
			tix.getCalendarLinks($(this).val());
		});
		
		//$('#cal-select').change();
		
		$('.cal-toggle').change(function()
		{		
			tix.checkFilters('.cal-toggle');
		});
	},
	
/****************************/
/*                          */
/* Data Requests - Sessions */
/*                          */
/****************************/
	
	getMarketLinks: function(date)
	{
		$.ajax({
			cache: true,
			dataType: 'jsonp',
			data: {
				date: date,
				marketid: tix.marketId,
				callback: 'tix.marketLinks'
			},
			url: 'http://tix.drafthouse.com/adcWSVistaITJson/marketsessions.aspx'
		});
	},
	
	getCalendarLinks: function(theaterId)
	{
		$.ajax({
			cache: true,
			dataType: 'jsonp',
			data: {
				cinemaid: theaterId,
				callback: 'tix.calendarLinks'
			},
			url: 'http://tix.drafthouse.com/adcWSVistaITJson/CinemaCalendar.aspx'
		});
	},
	
	getShowLinks: function(showId)
	{
		$.ajax({
			cache: true,
			dataType: 'jsonp',
			data: { 
				marketid: tix.marketId,
				filmid: showId,
				callback: 'tix.showLinks'
			},
			url: 'http://tix.drafthouse.com/adcWSVistaITJson/FilmSessions.aspx'
		});
	},
	
	getSeriesLinks: function(seriesId)
	{
		$.ajax({
			cache: true,
			dataType: 'jsonp',
			data: { 
				marketid: tix.marketId,
				seriesid: seriesId,
				callback: 'tix.seriesLinks'
			},
			url: 'http://tix.drafthouse.com/adcWSVistaITJson/MarketSeriesSessions.aspx'
		});
	},
	
	getMoreEvents: function(seriesId)
	{
		$.ajax({
			cache: true,
			dataType: 'jsonp',
			data: { 
				marketid: tix.marketId,
				seriesid: seriesId,
				callback: 'tix.moreEvents'
			},
			url: 'http://tix.drafthouse.com/adcWSVistaITJson/MarketSeriesSessions.aspx'
		});
	},
	
	getTheaterLinks: function(theaterId)
	{
		$.ajax({
			cache: true,
			dataType: 'jsonp',
			data: { 
				cinemaid: theaterId,
				callback: 'tix.theaterLinks'
			},
			url: 'http://tix.drafthouse.com/adcWSVistaITJson/CinemaSessions.aspx'
		});
	},
	
/***************************/
/*                         */
/* Data Requests - Filters */
/*                         */
/***************************/
	
	getMarketFilter: function()
	{
		$.ajax({
			cache: true,
			dataType: 'jsonp',
			data: { 
				marketid: tix.marketId,
				callback: 'tix.marketFilter'
			},
			url: 'http://tix.drafthouse.com/adcWSVistaITJson/marketdates.aspx'
		});
	},
	
	getMarketDates: function()
	{
		$.ajax({
			cache: true,
			dataType: 'jsonp',
			data: { 
				marketid: tix.marketId,
				callback: 'tix.marketDates'
			},
			url: 'http://tix.drafthouse.com/adcWSVistaITJson/marketdates.aspx'
		});
	},
	
	getCalendarFilter: function()
	{
		$.ajax({
			cache: true,
			dataType: 'jsonp',
			data: { 
				marketid: tix.marketId,
				callback: 'tix.calendarFilter'
			},
			url: 'http://tix.drafthouse.com/adcWSVistaITJson/MarketCinemasNav.aspx'
		});
	},
	
/********************/
/*                  */
/* Filter Utilities */
/*                  */
/********************/
	
	checkFilters: function(filterClass)
	{
		$(filterClass).each(function()
 	 	{
			if (this.checked) $(this.value).show();
			
			else $(this.value).hide();
 	 	});
	},
	
	checkEmpties: function(id)
	{
		$(id).find('tr.error').remove();
		
		$(id).find('tbody').each(function()
		{
			//if ($(this).find('tr:visible').size() == 0) $(this).prepend(tix.error);
		});
	},
		
	fillContainer: function (data, container, template, selector)
	{
		$(template).tmpl(data).appendTo(container);
		$('#dateTmpl').tmpl(data).appendTo('#div-select');
		
		if (selector) $(selector).divSelector(container);
		else
		{
			$('#div-select').change(function()
			{
				$(container + ' .showtimes-page').hide();
				$('#'+this.value).toggle();
				
				tix.checkFlags();
			});
			
			$('#div-select').change();
		}
	},
	
	checkFlags: function()
	{
		$('#flags .flag').hide();
		
		$('#flags #custom div').each(function()
		{
			var id = $(this).attr('id');
			
			$('#default #'+id).remove();
		});
		
		$('#showtimes').find('h6:visible').each(function()
		{
			var flag = $(this).text();
			
			$('#flag-'+flag).show();
		});
	}
};
