///////////////////////////////////////////
// environmental info
//
// initialize environmemental variables and do initial settings 
///////////////////////////////////////////
var currentLocation = window.location.hostname;
var currentPath = window.location.pathname;
var currentSearch = window.location.search.substr(1);

var collectionVideoPath;
var episodeVideoPath;
// use this switch case to customize the paths to services based on the environment
switch (currentLocation) {
	case 'www.cartoonnetwork.com':
		collectionVideoPath = "/cnvideosvc2/svc/episodeSearch/getEpisodesByShow?networkName=CN2&limit=500&offset=0";
		episodeVideoPath = "/cnvideosvc2/svc/episodeSearch/getEpisodesByIDs?networkName=CN2";
		break;
	case 'staging.cartoonnetwork.com':
		collectionVideoPath = "/cnvideosvc2/svc/episodeSearch/getEpisodesByShow?networkName=CN2&limit=500&offset=0";
		episodeVideoPath = "/cnvideosvc2/svc/episodeSearch/getEpisodesByIDs?networkName=CN2";
		break;
}

// default state for any data processing function
// should be overridden by the page's associated config script
// i.e. home.js, games.js
var defaultState = "tvshows";

///////////////////////////////////////////
// content info
///////////////////////////////////////////
var showName;
// base path for images uploaded via the CMA
// can be made into a switch/case if we get the ability to preview images
var cmaImgBasePath = "http://i.cdn.turner.com/v5cache/CARTOON/site/";
var totalGames = '';
var ratingsActive;
var isAchievementGame = false;
var parentFranchise = "";
var adbpAGNames = "";



var searchArray			= new Array();
var defaultSearchText	= "Search for shows";

///////////////////////////////////////////
// utility functions
///////////////////////////////////////////

// generate a random number and return it
function getRandomNumber () {
	var fooT = new Date();
	var rnum = Math.floor(Math.random()*fooT);
	return rnum;
}

///////////////////////////////////////////
// tv shows
///////////////////////////////////////////

///////////////////////////////////////////
//  footer
///////////////////////////////////////////
function getFooterContent(data) {
	// process the genre game data
	jQuery(data).find('Games:lt(5)').each(function() {
		var thisGameUrl = jQuery(this).find('Page_URL').text();
		var thisGameSrc = jQuery(this).find('game_100x75_image:first').find('srcUrl').text();
		var thisGameAlt = jQuery(this).find('Title:first').text();

		imgString = '<img src="' + cmaImgBasePath + thisGameSrc + '" alt="' + thisGameAlt + '" border="0">';
		jQuery('<a></a>').attr('href',thisGameUrl).html(imgString).appendTo('div.more div.col2 div');
	});
	// process the genre show data
	jQuery(data).find('Video_Header_265x65:lt(4)').each(function() {
		var thisShowUrl = jQuery(this).find('URL').text();
		var thisShowSrc = jQuery(this).find('srcUrl').text();
		var thisShowAlt = jQuery(this).find('altText').text();
		imgString = '<img src="' + cmaImgBasePath + thisShowSrc + '" alt="' + thisShowAlt + '" border="0">';
		jQuery('<a></a>').attr('href',thisShowUrl).html(imgString).appendTo('div.more div.col1 div');
	});

	// select a random what's new node
	randomWhat = Math.floor(jQuery(data).find('whatsnew_300x250').length * Math.random()) + 1;
	// process the what's new data
	i = 1;
	jQuery(data).find('whatsnew_300x250').each(function() {
		if (i == randomWhat) {
			var thisUrl = jQuery(this).find('URL').text();
			var thisSrc = jQuery(this).find('srcUrl').text();
			var thisAlt = jQuery(this).find('altText').text();

			imgString = '<img src="' + cmaImgBasePath + thisSrc + '" alt="' + thisAlt + '" border="0">';
			jQuery('<a></a>').attr('href',thisUrl).html(imgString).appendTo('div.more div.col3 div');
		}
		i++
	});
}


//////////////////////////////////////////
// for video player
//////////////////////////////////////////

var pageState = "tvshows";
var contentId = "";

//var pageState = "singlegame";
//var contentId = "135624";
//var gameId = "46963";


jQuery(document).ready(function() {

	jQuery.ajax({
		// get the property meta XML
		type: "GET",
		url: "/cnservice/cartoonsvc/content/xml/getContentById.do?contentId=135624&depth=5" + previewFormat,
		dataType: "xml",
		error: function (request, error) {
			// do this on AJAX error
		},
		success: function(data) {
			getFooterContent(jQuery(data).find('Genre:first'));
		}
	});

	jQuery.ajax({
		// get the property meta XML
		type: "GET",
		url: "/cnservice/cartoonsvc/content/xml/getContentById.do?contentId=" + contentId + "&depth=5" + previewFormat,
		dataType: "xml",
		error: function (request, error) {
			// do this on AJAX error
		},
		success: function(data) {
			
			var showID 				= "8a250ab030b75f660130d24886c5025c";
			var freeWheelSectionID 	= "cn.com_shows_main";
			var pageUrl 			= "";		
			
			//initializes video player and data on page.
			if(showID != ""){
				initPropertyVideo(showID, freeWheelSectionID, pageUrl)
			}
			
		}
	});
	

});

//////////////////////////////////////////
//   tools  
//////////////////////////////////////////
function cleanHouse() {
	jQuery("div").remove(".showBox");
	jQuery("div").remove("#noResults");
	jQuery("div").remove("#allShowsLoading");
}



//////////////////////////////////////////
//   Live Search - Keyboard Commands 
//////////////////////////////////////////
function toggleSearchWord(){
	var toggle_num		= 0;
	var total_num		= jQuery(".search_dropdown A").length;
	var default_key		= jQuery("#searchText").val();
	
	
	jQuery("#searchText").keydown(function(event){		
		switch(event.keyCode){
		case 9: /* Tab */
			jQuery(".search_dropdown").children("A:eq(" +0+ ")").focus(function(){ 
				jQuery(this).addClass("on");
			});	
			break;
		case 40: /* Down */
			event.preventDefault();
			jQuery(".search_dropdown").children("A:eq(" +0+ ")").focus();
			break;
		case 13: /* Enter */
			//jQuery(".search_dropdown").css("display", "none");
			break;		
		}
	}).focus(function(){
		jQuery(".search_dropdown").css("display", "none");
	});
	if(default_key.length < 3){
		alert("too small");	
	}
	
	
	jQuery(".search_dropdown").keydown(function(event){
		switch(event.keyCode){
			case 9: /* Tab */
				event.preventDefault();
				if(toggle_num < total_num){
					toggle_num	= toggle_num + 1;
					jQuery(this).children("A").blur();
					jQuery(this).children("A:eq(" +toggle_num+ ")").focus();
				}
				break;	
			case 40: /* Down */
				event.preventDefault();
				if(toggle_num < (total_num-1)){
					toggle_num	= toggle_num + 1;
					jQuery(this).children("A").blur();
					jQuery(this).children("A:eq(" +toggle_num+ ")").focus();
				}
				break;
			case 38: /* Up */
				event.preventDefault();
				if(toggle_num > 0){
					toggle_num	= toggle_num - 1;
					jQuery(this).children("A").blur();
					jQuery(this).children("A:eq(" +toggle_num+ ")").focus();
				}else{
					jQuery("#searchText").focus().val(default_key);
				}
				break;
			case 13: /* Enter */
				event.preventDefault();
				jQuery("#searchText").focus();
				break;
		}	
	});


	jQuery(".search_dropdown A").click(function(){
			searchToon2();
			return false;
		}).focus(function(){
			jQuery("#searchText").val(jQuery(this).text());
			jQuery(this).addClass("on");
		}).blur(function(){
			jQuery(this).removeClass("on");
	});
}



//////////////////////////////////////////
//   Live Search - Activate DropDown   
//////////////////////////////////////////
function createSearchDropdown(searchArray){
	//display dropdown
	if(searchArray.length > 0){
		var drop_list		= "";
		for(a=0; a < searchArray.length; a++){
			drop_list		+= "<a href='http://www.cartoonnetwork.com'>" +searchArray[a]+ "</a>";
		}
		jQuery(".search_dropdown").css("display","block").html(drop_list);
		toggleSearchWord();
	}else{
		jQuery(".search_dropdown").css("display", "none").html("");
	}
}
function hideSearchDropdown(){
	jQuery(".search_dropdown").css("display", "none").html("");
}


//////////////////////////////////////////
//   Search - Write Results  
//////////////////////////////////////////
function writeResults(sUrl, sType) {	
	//jQuery('#clearbox').before('<div id="allShowsLoading"><img src="tools/img/loadingSetForGif.gif"></div">');
	var keyedText			= jQuery("#searchText").val();
	var counter				= 0;
	jQuery.ajax({
		// get the property meta XML
		type: "GET",
		url: sUrl, // prod url will be 
		dataType: "xml",
		error: function (request, error) {		
			cleanHouse();
			jQuery('#clearbox').before('<div id="noResults"><div id="errorBox"><span>IM SORRY</span><p>I think Rigby broke something. Try your request again.</p></div></div>')
		},
		success: function(data) {
			
			cleanHouse();
			var showDivId = 0;
			var dropdownArray		= new Array();
						
			jQuery(data).find('result').each(function() {
				var showImgOverlay = jQuery(this).find('allshowsoverlay').text();
				var showTitle = jQuery(this).find('title').text().toUpperCase();
				var showUrl = jQuery(this).find('url').text();
				var showImgUrl = jQuery(this).find('thumbnail').text();
				var showTuneIn = jQuery(this).find('tune-in-msg').text();
				var showGameUrl = jQuery(this).find('gameurl').text();
				var showVidUrl = jQuery(this).find('videourl').text();
				var showShortTitle = jQuery(this).find('shorttitle').text().toUpperCase();
				var showHomeUrl = jQuery(this).find('homeurl').text();
				var showExcerpt	= jQuery(this).find('excerpt').text();
		
				var showGameUrlHTML = "";
				var showVidUrlHTML = "";
				var showHomeUrlHTML = "";
				var showTuneInHTML = "";
				var showImgOverlayUrl = "";
				var dashlog1 = "";
				var dashlog2 = "";
				// search params (formatting, match lowercase			
				var format_key		= keyedText.toLowerCase();
				var format_title	= showTitle.toLowerCase();
				var format_excerpt	= showExcerpt.toLowerCase();
				
				
				if (showGameUrl !== "" && showGameUrl !== null) { 
					 showGameUrlHTML = ' <a href="' + showGameUrl +'">Play Games</a>'; 
				}	
				if (showVidUrl != "" && showVidUrl != null) {
					showVidUrlHTML = ' <a href="' + showVidUrl + '">Watch Videos</a>'	
				}
				if (showHomeUrl != "" && showHomeUrl != null) {
					showHomeUrlHTML = ' <a href="' + showHomeUrl + '">View Show Page</a>'	
				}
				if (showHomeUrl != "" && showHomeUrl != null && showGameUrl != "" && showGameUrl != null) {
					dashlog1 = '|'	
				}
				if (showGameUrl !== "" && showGameUrl !== null && showVidUrl != "" && showVidUrl != null) {
					dashlog2 = '|'	
				}
				if (showHomeUrl != "" && showHomeUrl != null && showVidUrl != "" && showVidUrl != null) {
					dashlog2 = '|'
				}
				if (showTuneIn.length > 36 ) {
					var numx = showTuneIn.length - 36;
					var tempString = showTuneIn.substring(0, showTuneIn.length-numx); 
					showTuneIn = tempString + " ...";
				}
				if (showTuneIn != "" && showTuneIn != null) {
					showTuneInHTML = '<span>' + showTuneIn +'</span>';
				}				
				if (showImgOverlay == "" || showImgOverlay == null ) {
					showImgOverlayUrl = "tools/img/blankOverlay.gif";
				}	else {
					showImgOverlayUrl = "" + cmaImgBasePath + showImgOverlay;
				}				
				if (showTitle.length < 20) {
					if (showShortTitle != "" || showShortTitle != null) {
					showShortTitle = showTitle; 	
					} 
				}
				
				//start of the hiding function 
			 if (jQuery('.showBox').length < 8 || jQuery('.showBox').length == null) {
				var classScroll = '"'; 
			 } else {
				 var classScroll = ' hidden" style="display:none;"'
			 }
				
				/*  DO DEFAULT SEARCH or KEYED LIVE SEARCH */
				if(keyedText.length > 2 && keyedText != defaultSearchText){ 
					//if(format_title.indexOf(format_key) > -1 || format_excerpt.indexOf(format_key) > -1){ /* Disabled, search thru titles & descriptions */
					if(format_title.indexOf(format_key) > -1){		
					jQuery('#clearbox').before('<div class="showBox' + classScroll + '><div class="showImg" id="'+ showDivId +'" style="background:url('+ cmaImgBasePath + showImgUrl +') top left no-repeat;"><a href="'+ showUrl +'"><img src="'+ showImgOverlayUrl +'" border="0" alt="" /></a></div><br /><a href="' + showUrl +'"><h3>'+ showShortTitle +'</h3></a>' + showTuneInHTML + '<br /><div class="info">' + showHomeUrlHTML + ' ' + dashlog1 + ' ' + showGameUrlHTML + ' ' + dashlog2 + ' ' + showVidUrlHTML + ' </div></div>');
					dropdownArray.push(showTitle);
					showDivId++;
					}
				}else{
					jQuery('#clearbox').before('<div class="showBox' + classScroll + '><div class="showImg" id="'+ showDivId +'" style="background:url('+ cmaImgBasePath + showImgUrl +') top left no-repeat;"><a href="'+ showUrl +'"><img src="'+ showImgOverlayUrl +'" border="0" alt="" /></a></div><br /><a href="' + showUrl +'"><h3>'+ showShortTitle +'</h3></a>' + showTuneInHTML + '<br /><div class="info">' + showHomeUrlHTML + ' ' + dashlog1 + ' ' + showGameUrlHTML + ' ' + dashlog2 + ' ' + showVidUrlHTML + ' </div></div>');
					showDivId++;
				}		
				counter++;					
			});	
			searchArray		= dropdownArray;
			
			// Manage Search Dropdown
			if(keyedText.length < 3){
				hideSearchDropdown();
			}else if(dropdownArray.length > 0 && jQuery.inArray(keyedText, dropdownArray) > -1){  //hide, when matching result
				hideSearchDropdown();	
			}else if(dropdownArray.length > 0){ // show, all
				createSearchDropdown(searchArray);
			}

			// Show error if no results
			if(showDivId < 1){
				hideSearchDropdown();
				jQuery('#clearbox').before('<div id="noResults"><div id="errorBox"><span>YOUR SEARCH</span><p class="resulttext">' + sType.toUpperCase() + '</p><div>Your search doesn&acute;t match any of our shows. Double-check your spelling and try again.</div></div>');
			}
			
		}
	});
}


//////////////////////////////////////////
// search navigation
/////////////////////////////////////////
function searchnav(foo) {
	if (foo == 1) {
		var searchNavUrl = "/cn-search/query.jsp?text=*&type=allshows&start=1&returnAll=true&sort=popular";
	}else if (foo == 2) {
		var searchNavUrl = "/cn-search/query.jsp?text=*&type=allshows&start=1&returnAll=true&sort=alpha";
	}else if (foo == 3) {
		var searchNavUrl = "/cn-search/query.jsp?text=*&type=allshows&start=1&returnAll=true&sort=recent";
	}
		
	jQuery(".searchBar > ul > li > a > div").removeClass();
	if (foo == 1) {
		jQuery("#mp").addClass("on");
	}else if (foo == 2) {
		jQuery("#az").addClass("on");
	}else if (foo == 3) {
		jQuery("#new").addClass("on");
	}
	writeResults(searchNavUrl, "nav");	
}

//////////////////////////////////////////
//  search function
/////////////////////////////////////////
function searchToon2() {
	var checker = 	jQuery("#searchText").val();
	var searchUrl = "/cn-search/query.jsp?text=*&type=allshows&start=1&returnAll=true&sort=popular";

	writeResults(searchUrl, checker);
	jQuery(".searchBar > ul > li > a > div").removeClass();
}




//////////////////////////////////////////
// tv show load
//////////////////////////////////////////
jQuery(document).ready(function() {
	writeResults("/cn-search/query.jsp?text=*&type=allshows&start=1&returnAll=true&sort=popular", "loading");
	
	/*** Live Search Function ***/	
	jQuery('#searchText').livesearch({
		searchCallback: searchFunction,
		queryDelay: 300,
		innerText: defaultSearchText,
		minimumSearchLength: 3
	});
	function searchFunction(searchTerm) {
		searchToon2();
	}

});


jQuery(window).scroll(function(){
	
  if(jQuery(window).scrollTop() + 680 > jQuery(document).height() - jQuery(window).height() ){
	var counter = 0;
    jQuery(".hidden").each(function() {
		if (counter < 6) {
			jQuery(this).show("slow");
			jQuery(this).removeClass('hidden');
			//jQuery(this).css('display','');
		}
		counter++;
	});

  }
});



