/*
 * This file contains all the JavaScript necessary to make the find a show functionality work. 
 */
var findAShow = {
		
	// Defaults, can be overridden by callers to getResults and page code
	analytics : {
		clone: function() {return jQuery.extend(true, {}, this); },
		omniture : {
				pageName: "ondemand"
		}
	},
	
	// Valid saved search ids 
	searchCookie  : 'myOnDemandSearchOption',
	
	searchOptions : [ 
	                  'search', 'partnerSearch', 
	                  'letterSearch', 'genreSearch','channelSearch' ],
	
	setLastSearchId : function (id) {
		if (jQuery.inArray(id,this.searchOptions) >= 0)
			www.createCookie(this.searchCookie,id, 365);
	},
	getLastSearchId : function () {
		rv = www.readCookie(this.searchCookie);
		if (!rv || jQuery.inArray(rv,this.searchOptions) == -1) { 
			// none saved so return a random one
			var randomizeSearchOptions = this.searchOptions.slice(2); // search/partnerSearch not to be included in randomize
			return randomizeSearchOptions[Math.floor(Math.random()*randomizeSearchOptions.length)];
		}
		else
			return rv;
	}
}


findAShow.search = function(queryTerm) {
	var analytics = findAShow.analytics.clone();
	analytics.omniture.pageName += "search";
	return findAShow.getResults('search','/search/ta_ent_programme_result_module_skin.xml?q=' + queryTerm + '&requiredfields=type:programme.site:tv&partialfields=keyword:ondemand.programme-title:' + queryTerm + '&num=999',undefined,analytics);
}

findAShow.searchAll = function(offset) {
	var analytics = findAShow.analytics.clone();
	analytics.omniture.pageName += "search";
	return findAShow.getResults('letterSearch','/content/ta_ent_video_shows_group/ta_ent_programme_result_module_skin.xinc', offset,analytics);
}

findAShow.letterSearch = function(letter, offset) {
	var analytics = findAShow.analytics.clone();
	analytics.omniture.pageName += "filteraz";
	return findAShow.getResults('letterSearch','/content/ta_ent_video_shows_group/ta_ent_programme_result_module_skin.xinc?letter=' + letter, offset,analytics);
}

findAShow.partnerSearch = function(partner, offset) {
	var analytics = findAShow.analytics.clone();
	analytics.omniture.pageName += "filterpartner";
	return findAShow.getResults('partnerSearch','/content/ta_ent_video_shows_' + partner + '_group/ta_ent_programme_result_module_skin.xinc?partner=' + partner, offset,analytics);
}

findAShow.genreSearch = function(genre, offset) {
	var analytics = findAShow.analytics.clone();
	analytics.omniture.pageName += "filtergenre";
	return findAShow.getResults('genreSearch','/content/ta_ent_video_shows_group/ta_ent_programme_result_module_skin.xinc?genre=' + genre, offset,analytics);
}

findAShow.channelSearch = function(channel, offset) {
	var analytics = findAShow.analytics.clone();
	analytics.omniture.pageName += "filterchannel";
	return findAShow.getResults('channelSearch','/content/ta_ent_video_shows_group/ta_ent_programme_result_module_skin.xinc?channel=' + channel, offset,analytics);
}

findAShow.getResults = function(searchId,queryUrl, offset, analyticsOpt ) {
	var analyticsProps = analyticsOpt ? analyticsOpt : findashow.analytics;
	if (typeof offset != 'undefined' ) {
		queryUrl = queryUrl + '&offset=' + offset;
	}
	if ($('#primaryRow').exists()) {
		$('#primaryRow').removeAttr('id');
		$('#findAShowResultsDiv .rowContentBg').attr('id', 'primaryRow');
	}
	//In case we want to do a second search
	$('#spinnerDiv').show();
	$('#info, #findAShowFooter').hide();

	//show the div and force the sifr header for the div to render even though it started hidden
	$('#findAShowResultsDiv').show();
	replaceSifrs();

	$('html, body').animate({scrollTop: $('#findAShowResultsDiv').offset().top}, 1000);
	
	jQuery.ajax({
		dataType: 'html',
		url: queryUrl,
		success: function(data) {
			$('#spinnerDiv').hide();
			$('#info').html(data);
			findAShow.bindShowMoreFunctions();
			$('#info, #findAShowFooter').show();
			
			analytics.omniture.fakePageView(analyticsProps.omniture.pageName);
			analytics.nielsen.fakePageView();
			
			findAShow.setLastSearchId(searchId);
		}
	});
	return false;
}

//Binds two different onclick functions to showMore links
findAShow.bindShowMoreFunctions = function() {
	$("a.showMore").toggle(
		//function to show more
		function() {
			$(".show").each(function() {
				$(this).find("a.showClose").attr("class", "showMore");
				$(this).find(".showDetails").remove();
				$(this).find(".allResults").remove();
			});
	
			var getShow		= $(this).parent().attr("title");
			var getID		= $(this).parent().attr("id");
			var getType		= $(this).parent().attr("id").substring(0,5);
			var howMany;
			var mediaCount;
			var extrasCount;
			var episodeCount;
			var maxMediaCount = 15;
			$(this).attr("class", "showClose");
			$.ajax({
				type: "GET",
				url: "/content/"+getShow.replace(/-/g,"_")+"_"+(getType=="extra"?"extras":"episodes")+"_group/ta_ent_ajax_searchresult_module_skin.xml",
				dataType: "xml",
				success: function(xml) {
	
					mediaCount 		= $(xml).find('medias').attr("media-count");
					extrasCount 	= $(xml).find('medias').attr("extras-count");
					episodeCount 	= $(xml).find('medias').attr("episode-count");
	
					$(xml).find('media').each(function(i) {
						var showDetails  = "<ul class='showDetails'>" + "\n";
							showDetails += "<li class='show'><a href='" + $(this).find('uri').text() + "'>" +$(this).find('show').text() + "</a>&nbsp;</li>" + "\n";
							showDetails += "<li class='date'>" + $(this).find('date').text() + "&nbsp;</li>" + "\n";
							showDetails += "<li class='type'>" + $(this).find('type').text() + "&nbsp;</li>" + "\n";
							showDetails += "<li class='duration'>" + $(this).find('duration').text() + "&nbsp;</li>" + "\n";
							showDetails += "<li class='details'>" + $(this).find('details').text() + "&nbsp;</li>" + "\n";
							showDetails += "<li class='channel'>" + $(this).find('channel').text() + "&nbsp;</li>" + "\n";
							showDetails += "</ul>" + "\n";
	
						$("#"+getID).append(showDetails);		
					});
					
					//alert("extrasCount " + extrasCount + "  mediaCount" +mediaCount+ "  episodeCount" +episodeCount + " type="+getType);
					if (mediaCount < (getType == 'extra' ? extrasCount-1 : episodeCount-1)) {
						if(episodeCount >  maxMediaCount || extrasCount > maxMediaCount){
							var searchURI = "/search/ta_ent_search_tv_skin.xhtml?requiredfields=type:media." +
								(getType == 'extra' ? "(format:extras|format:preview)" : "format:full+episode") +
								"&partialfields=programme:%3B" + getShow + "&q="+getShow.replace(/-/g,"+")+"+video&tab=tvmedia&start=0&sort=date:D:S:d1&view=all";
							$("#"+getID).append("<a class='allResults' href='" + searchURI + "'>View all Results</a>");
						}
					}

					$(".showDetails:even").addClass("alt");
				}
			});
			return false;
		},
		//function to hide the show more on alternate clicks
		function() {
			$(this).attr("class", "showMore");
			$(this).parent().find(".showDetails").remove();
			$(this).parent().find(".allResults").remove();
			return false;
		}
	);
}

