j$(function(){ // document.ready

	var todaysDate = (new Date()).getTime();
	var twoWeeks =  1209600000;
	var odlisting = {

		api: '/categoryHTML',
		prefs: { // default preferences
			zip: 19103,
			headendid: 'PA37745R',
			category: 'vod_all',
			subcategory: '',
			ratings: 'ALL',
			pagenumber: 0,
			pagesize: 10000,
			titlesonly: 'Y',
			sort: 'alpha',
			hd: 0,
			ondemand: 1,
			endtime: todaysDate + twoWeeks,
			starttime: todaysDate,
			alphaFilter: 'A',
			tz: 'EASTERN',
			isMicrosite: 1
		},
		noalpha: false,
		print: j$('#vod_print').length && j$('#vod_print').val() == 1 ? true : false,
		allhd: j$('#vod_hd').length && j$('#vod_hd').val() == 1 ? true : false

	};
	// Category filter (comes from hidden input field on page)
	if (j$('#vod_categoryfilter').val().length) odlisting.prefs.category = j$('#vod_categoryfilter').val();
	if (j$('#vod_subcategoryfilter').val().length) odlisting.prefs.subcategory = j$('#vod_subcategoryfilter').val();
	
	// If the category is not 'vod_all' we want to display all results and disable the alpha filters
	if (odlisting.prefs.category != 'vod_all' && odlisting.prefs.category != 'vod_music') odlisting.noalpha = true;

	if (odlisting.allhd) {
		odlisting.prefs.hd = 1;
		j$(document.body).addClass('allhd');
	}

	if (odlisting.noalpha && !odlisting.print) {
		Prefs.remove('odlistingPrefs.hdfilter','session');
		Prefs.remove('odlistingPrefs.alphafilter','session');
		Prefs.remove('odlistingPrefs.ratingsfilter','session');
		Prefs.remove('odlistingPrefs.whenfilter','session');
		j$(document.body).addClass('noalpha');
	}
	
	//if subcategory has a hyphen, replace with underscore
	odlisting.prefs.subcategory = odlisting.prefs.subcategory.replace(/\-/,"_");

	/* This function sends the request to the API for results and acts upon the alpha and hd filters, further filtering is handled through the filter function below */
	function getVODResults() {
		j$('#odlistings-grid-results').empty();
		j$('#odlistings-grid-container').addClass('loading').find('p.error').remove();
		j$('table.odlistings-grid-table').remove();
		if (odlisting.noalpha) {
			odlisting.prefs.alphaFilter = '';
		}
		saveFilterPrefs();
		new Ajax.Request(odlisting.api, {
			parameters: 'zip='+odlisting.prefs.zip+'&headendid='+odlisting.prefs.headendid+'&category='+odlisting.prefs.category+'&subcategory='+odlisting.prefs.subcategory+'&ratings='+odlisting.prefs.ratings+'&pagenumber='+odlisting.prefs.pagenumber+'&pagesize='+odlisting.prefs.pagesize+'&titlesonly='+odlisting.prefs.titlesonly+'&sort='+odlisting.prefs.sort+'&hd='+odlisting.prefs.hd+'&ondemand='+odlisting.prefs.ondemand+'&endtime='+odlisting.prefs.endtime+'&starttime='+odlisting.prefs.starttime+'&alphaFilter='+odlisting.prefs.alphaFilter+'&tz='+odlisting.prefs.tz+'&isMicrosite='+odlisting.prefs.isMicrosite+'&nocache='+Math.random(),
			method: 'get',
			onSuccess: function(transport) {	
				var myResponse = transport.responseText;
				$('odlistings-grid-results').innerHTML = myResponse;
				var results = j$('#odlistings-grid-results div.listing-row-holder');
				var myTitle, myNetwork, myRating, myStart, myEnd, mySelection;
				var newGrid = '<table id="odlistings-grid" class="odlistings-grid-table" cellspacing="0" cellpadding="0"><thead><tr><th>Titles</th><th>Network</th><th>Rating</th><th>Start</th><th>End</th><th>Menu Selection</th></tr></thead><tbody>';
				if (results.length) {
					results.each(function(i){
						isNew = j$(this).find('div.microsite-listing-title div').length? true : false;
						myTitle = j$(this).find('div.microsite-listing-title span').text();
						myNetwork = j$(this).find('div.microsite-listing-provider span').text();
						myRating = j$(this).find('div.microsite-listing-rating span').text();
						myStart = j$(this).find('div.microsite-listing-start span').text();
						myEnd = j$(this).find('div.microsite-listing-ends span').text();
						mySelection = j$(this).find('div.microsite-listing-path span').text();
						newGrid += '<tr'+(isNew?' class="new"':'')+'><td class="odlistings-grid-title">'+myTitle+'</td><td class="odlistings-grid-network">'+myNetwork+'</td><td class="odlistings-grid-rating">'+myRating+'</td><td class="odlistings-grid-start">'+myStart+'</td><td class="odlistings-grid-end">'+myEnd+'</td><td class="odlistings-grid-selection">'+mySelection+'</td></tr>';
					});
				}
				newGrid += '</tbody></table>';
				j$('#odlistings-grid-results').empty();
				j$('#odlistings-grid-container').removeClass('loading').append(newGrid);
				filterODResults();
			},
			onFailure: function() {
				j$('#odlistings-grid-container').removeClass('loading');
				j$('#odlistings-grid-container').append('<p class="error">An error occurred while processing your request, please <a href="#">click here</a> to try again.</p>').find('p.error a').click(function(){
					getVODResults();
					return false;
				});
			}
		});
	} // getVODResults


	/* The function that applies further filtering to the results returned by getVODResults, this includes rating and when filters */
	function filterODResults() {
		var inactiveRatings = j$('#odlistings-filters-rating dd li').not('.active').find('a');
		var activewhen = j$('#odlistings-filters-when dd li.active a');
		var odresults = j$('#odlistings-grid tbody tr');
		/* Reset filters */
		odresults.removeClass('hide');
		/* Ratings filter */
		if (inactiveRatings.length) {
			var rating;
			var inactiveRatingArray = [];
			inactiveRatings.each(function(i){
				inactiveRatingArray.push(j$.trim(j$(this).attr('rel')));
			});
			odresults.each(function(i){
				rating = j$.trim(j$(this).find('.odlistings-grid-rating').text());
				for (var i = 0; i < inactiveRatingArray.length; i++) {
					if (rating == inactiveRatingArray[i]) {
						j$(this).addClass('hide');
						break;
					}
				}
			});
			odresults = odresults.not('.hide');
		}
		/* When filter */
		if (activewhen.length) {
			var dataStart;
			var dataEnd;
			var sdate;
			var edate;
			var filterDate = new Date();
			filterDate.setHours(parseInt(filterDate.getHours()) + parseInt(j$.trim(activewhen.attr('rel'))));
			odresults.each(function(){
				dataStart = j$.trim(j$(this).find('.odlistings-grid-start').text()).split('/');
				dataEnd = j$.trim(j$(this).find('.odlistings-grid-end').text()).split('/');
				if (dataStart.length == 3 && dataEnd.length == 3) {
					sdate = new Date();
					sdate.setMonth(dataStart[0]-1);
					sdate.setDate(dataStart[1]);
					sdate.setYear(dataStart[2]); // i understand using a two digit date here puts it in the wrong century, but we are just using it for comparison so theres no reason to write extra code to make it display properly... however, we may need to revisit this in december of 2999
					edate = new Date();
					edate.setMonth(dataEnd[0]-1);
					edate.setDate(dataEnd[1]);
					edate.setYear(dataEnd[2]);
					filterDate.setYear(dataStart[2]);
					if (filterDate < sdate || filterDate > edate) j$(this).addClass('hide');
				}
			});
			odresults = odresults.not('.hide');
		}
		j$('#odlistings-grid-container p.error').remove();
		if (!odresults.length) j$('#odlistings-grid-container').append('<p class="error">Your query returned 0 results. Try adjusting your filter settings and try again.</p>');
		saveFilterPrefs();
	} // filterODResults


	/* This function checks all the active filters and saves them to a cookie so they will persist throughout each new page refresh */
	function saveFilterPrefs() {
		var odlistingPrefs = '';
		var hdfilter = j$('#odlistingsFilterHD').hasClass('active');
		var inactiveRatings = j$('#odlistings-filters-rating dd li').not('.active').find('a');
		var activewhen = j$('#odlistings-filters-when dd li.active a').attr('rel');
		var alphafilter = '';
		if (j$('#odlistings-header-menu li.active').length) alphafilter = j$('#odlistings-header-menu li.active a').attr('rel');
		var inactiveArray = [];
		inactiveRatings.each(function(i){
			inactiveArray.push(j$(this).attr('rel'));
		});
		Prefs.set('odlistingPrefs.hdfilter', hdfilter,'session');
		Prefs.set('odlistingPrefs.alphafilter', alphafilter,'session');
		Prefs.set('odlistingPrefs.ratingsfilter', inactiveArray.join(),'session');
		if (activewhen) Prefs.set('odlistingPrefs.whenfilter', activewhen,'session');
	} // saveFilterPrefs


	/* This function reads any filter prefs saved in cookies and applies them to the page when it is initially loaded */
	function setPredefinedODPrefs() {
		var hdfilter = Prefs.get('odlistingPrefs.hdfilter');
		var whenfilter = Prefs.get('odlistingPrefs.whenfilter');
		var ratingsfilter = Prefs.get('odlistingPrefs.ratingsfilter');
		var alphafilter = Prefs.get('odlistingPrefs.alphafilter');
		if (hdfilter) {
			j$('#odlistingsFilterHD').addClass('active');
			odlisting.prefs.hd = j$('#odlistingsFilterHD').hasClass('active') ? 1:0;
		}
		if (whenfilter) {
			j$('#odlistings-filters-when dd li a[@rel='+whenfilter+']').parent().addClass('active');
			j$('#odlistings-filters-when dt a').text(j$('#odlistings-filters-when dd li.active a').text());
			j$('#odlistings-footnote').empty().text(j$('#odlistings-filters-when dd li.active a').attr('title'));
		}
		if (ratingsfilter) {
			ratingsfilter = ratingsfilter.split(',');
			for (var i = 0; i < ratingsfilter.length; i++) {
				j$('#odlistings-filters-rating dd li a[@rel='+ratingsfilter[i]+']').parent().removeClass('active');
			}
		}
		if (alphafilter) {
			j$('#odlistings-header-menu li.active').removeClass('active');
			j$('#odlistings-header-menu li a[@rel='+alphafilter+']').parent().addClass('active');
			odlisting.prefs.alphaFilter = alphafilter;
		}
		getVODResults();
	} // setPredefinedODPrefs


	/* Alpha filter behavior */
	j$('#odlistings-header-menu li a').click(function(){
		j$(this).parent().parent().find('li.active').removeClass('active');
		j$(this).parent().addClass('active');
		odlisting.prefs.alphaFilter = j$(this).attr('rel');
		getVODResults();
		return false;
	});


	/* HD filter behavior */
	j$('#odlistingsFilterHD').click(function(){
		j$(this).toggleClass('active');
		odlisting.prefs.hd = j$(this).hasClass('active') ? 1:0;
		getVODResults();
		return false;
	});


	/* Ratings filter behavior */
	j$('#odlistings-filters-rating dd ul li a').click(function(){
		j$(this).parent().toggleClass('active');
		filterODResults();
		return false;
	});


	/* When filter behavior */
	j$('#odlistings-filters-when dd li a').click(function(){
		j$('#odlistings-filters-when dd li.active').removeClass('active');
		j$(this).parent().addClass('active');
		j$('#odlistings-filters-when dt a').text(j$(this).text());
		filterODResults();
		j$(this).parent().parent().parent().parent().removeClass('open');
		j$('#odlistings-footnote').empty().text(j$(this).attr('title'));
		return false;
	});


	/* Next-Prev links */
	j$('#odlistingsPrevBtn').click(function(){
		var newfilter = j$('#odlistings-header-menu li.active').removeClass('active').prev().addClass('active').find('a').attr('rel');
		if (!newfilter) {
			newfilter = j$('#odlistings-header-menu li:last').addClass('active').find('a').attr('rel');
		}
		odlisting.prefs.alphaFilter = newfilter;
		getVODResults();
		return false;
	});

	j$('#odlistingsNextBtn').click(function(){
		var newfilter = j$('#odlistings-header-menu li.active').removeClass('active').next().addClass('active').find('a').attr('rel');
		if (!newfilter) {
			newfilter = j$('#odlistings-header-menu li:first').addClass('active').find('a').attr('rel');
		}
		odlisting.prefs.alphaFilter = newfilter;
		getVODResults();
		return false;
	});


	/* Show all HD button behavior (currently inactive) */
	j$('#btnShowAllHD').click(function(){
		j$(document.body).addClass('allhd');
		odlisting.prefs.hd = 1;
		odlisting.prefs.alphaFilter = '';
		getVODResults();
		return false;
	});


	/* Print button behavior */
	j$('a#printClose').click(function(){
		window.close();
		return false;
	});

	j$('a#printAction').click(function(){
		window.print();
		return false;
	});

	/* Zip code box (headend required) */
	j$("#tvlistings-postalcode-form").bind('submit',function() {
		showOverlay(function() {
			return HeadEndWindow.create_window(j$("#tvlistings-postalcode-input").val());
		});
		return false;
	});

	j$("#grid-settings-change").click(function() {
		showOverlay(function() {
			return HeadEndWindow.create_window();
		});
		return false;
	});

	tvGrid = {
		displayHeadendSettings: function(zip) {
			j$("#headend-setting-zip").html(zip);
			j$("#tvlistings-postalcode-form").css('display','none');
			j$("#your-grid-settings").css('display','block');
		},
		build_grid: function(no) {
			return false;
		}
	};

	var tvZip = Prefs.get('tvZip');
	if (tvZip) {
		odlisting.prefs.zip = tvZip;
		tvGrid.displayHeadendSettings(tvZip);
	} else {
		j$("#tvlistings-postalcode-form").css('display','block');
	}


	/* On document ready, run the function that applies all filters saved in preference cookies */
	setPredefinedODPrefs();
	
	
	//console.log("subcat=" + odlisting.prefs.subcategory);
	
}); // document.ready

function mouseoutRow() {
	return false;
}

function mouseoverRow() {
	return false;
}

function clickBrowseResult() {
	return false;
}