var SEARCH_ORIGIN = '';
var playlist = '';
isManualSearch = false;
isManualUrlSearch = false;
isVideoPlaying = false;
isMainVideoPage = false;
var VideoData = new Object();

VideoData.loaded = false;
VideoData.mode = 'single';
// max search results
VideoData.maxResults = 40; 
VideoData.lastSearch = '';
// defaultTab
VideoData.current_tab = '';

// VideoPage Navigation
function HideVideoLinks() { }
function ShowVideoLink(MainLinkId, SubLinkId) { }
function VideoMenu(MainLinkId, SubLinkId) {
	return ; /* Quick Hack to get search working. */
	VideoData.current_tab = SubLinkId;
}

var currentPlaylist;
var currentChannelIndex = 0; // Defaults to PGATOUR video;

// Video Play function
function play_video(video, override) {
	if(isAdPlaying) {	//prevent changing video during ad playback
		return;
	}
	
	if(typeof video == 'string') {	//if video is a string, it is a single video
		cvp_playVideo(video);
	} else {	//else it's a playlist of videos size 1 to n
		var len = video.length;
		if(len == 0) {	//no playlist, just return
			return;
		}
		
		var currId = video[0].url;
		currId = cvp_prepareVideoId(currId);
		
		cvp_playVideo(currId);	//play the first
		cvp_enqueueVideos(video, currId);	//queue the rest
	}
}

// Channel Changer
function change_channel(channel, autoplay){
	if (autoplay == null) autoplay = true;
	// removed code for development
}

//per ticket: PGATOUR-3116, make the page default to the latest videos, with auto-play option
function defaultToLatestVideos(autoplay) {
	//show latest videos, hide channels
	VideoMenu('tourVideoNav1', 'tourVideoLatest');
	
	//import the top 10 latest videos playlist, and play them starting from the most recent
	if (autoplay) {
		play_video(playlist,1);
	}

	tourCVPMain.setAdSection(oVideoChannel.ssid);	//set site_section to latest videos
}

// What do I do first?
function initialize_video_page () {
	var q = '';
	var search = getParam('s');
	var channel = getParam('c');
	if (search) {
		// Go to video search
		q = search.replace(/\+/g, ' ');
		$(searchboxID).value = unescape(q);
		isManualUrlSearch = true;
		video_search();
		return;
	} else if (channel)	{
		change_channel(channel);
		return;
	}
	else {
		// Process what is being called
		var regex = new RegExp( "[?](.*)$" );
		var results = regex.exec( window.location.href );
		if (results && (!results.join('').match('dmtdebug|cvpoption|gigyaoption'))){
			if (results.length == 2) q = results[1];
		}
	}
	
	// Fix for mal-formed urls
	q = q.replace('/video/?','');
	
	//CVP sharing on Facebook requires that the URL be decoded for the link to work correctly
	q = decodeURIComponent(q);
	//q = q.replace('/video/video', '/video');	//also remove extra /video, if it exists.
	if (q != '' && q.indexOf('/video/video') == -1 && q.indexOf('/audio') == -1) {
		q = '/video' + q;
	}	
	// default
	if (q == '') { defaultToLatestVideos(true); return; }
	else {
		play_video(q);
	}
}

// Video Search --------------------------------------
function video_search() {
	var q = $(searchboxID).value;
	cleanSearchTerm = q;
	searchTerm = q = q.replace(/ /g, '+');
	isManualSearch = true;
	
	if (q) {
		VideoData.lastSearch = q;
		VideoMenu('x','tourVideoSearchResults');

		categoryID = 'pgatour_search_catcher';
		tourVideoChangeCategory();

		//function to call updated SearchProcessor to return query results
		if (theTour.id == "r") {
			$('tourVideoChannelTitle').innerHTML = "<span>Results for</span> \"" + $(searchboxID).value + "\"";
		}
		else  {
			$('tourVideoChannelTitle').innerHTML = "Results for <span>\"" + $(searchboxID).value + "\"</span>";
		}

		$('tourVideoThumbs').innerHTML = 'Loading...'; // Clear the inner HTML


		$(channelsID).innerHTML = "";


		//tourAddSearchAttribute('&sort=date',0);
		SEARCH_ORIGIN = 'site_search';
		coreUpdateAttributeWithoutCalling('&sort=date&isExpired=no',0);
		tourSearchAnew(1, q);
		//coreUpdateQuery(q);

		if (Prototype.Browser.IE && Prototype.BrowserFeatures['Version'] < 8) { ieHoverEffectSleeper(true); }

		var csiMgrArgs = "term=" + escape(searchTerm) + csiMgrExtraArgs;
		// CSIManager.getInstance().call(myPgaMetaSearchUrl, csiMgrArgs, channelsID, golfMetas);

		// $(searchboxID).value = cleanSearchTerm = "search";
		//Keeps the user's search term in the text field
	}
}

/////////////////////////////////////////////
// Aug 2010 Redesign Code
/////////////////////////////////////////////

// Targeting IDs
searchboxID = 'video_search_string';
categoriesID = 'tourVideoCategories';
channelsID = 'tourVideoChannels';

// Selected / Active Classes
categoryAClass = 'active';
channelAClass = 'selected';

/* Aug 2010 Redesign Channels Object. */
VideoChannels = [
	{ // TOUR
		name: "PGATour",
		id: 'r',
		urlPart: 'pga-tour',
		categories: [
			{ // Highlights
				name:"Highlights",
				urlPart: "highlights",
				id: "highlights",
				channels:[
					{ name:"Top Shots", id: "mine", urlPart:"top_shots" },
					/*{ name:"Morning Movers", id: "movers", urlPart:"morning_movers" },*/
					{ name:"Round Recaps", id: "highs", urlPart:"round_recap" },
					{ name:"Shot of the Day", id: "sod", urlPart:"shot_of_the_day" },
					{ name:"Shots of the Week", id: "sotw", urlPart:"shots_of_the_week" },
					//{ name:"More Driven", id: "moredriven", urlPart:"more_driven" },
					{ name:"Top 10", id: "top10", urlPart:"top_10" },
					{ name:"Interviews", id: "int", urlPart:"interviews" },
					
					{ name:"Memorable Moments", id: "memmom", urlPart:"memorable_moments" },
					{ name:"LIVE@", id: "lat", urlPart:"live_at" },
					{ name:"FedExCup", id: "fec", urlPart:"fedexcup" }
					/*{ name:"Kodak Challenge", id: "kodak", urlPart:"kodak_challenge" }*/
				]
			},
			{ // Features
				name:"Features",
				id: "features",
				urlPart: "features",
				channels:[
					{ name:"Player of the Month", id: "playermonth", urlPart:"player_of_the_month" },
					/*{ name:"Top Holes on TOUR", id: "topholes", urlPart:"top_holes_on_tour" },
					{ name:"19th Hole", id: "clubhouse", urlPart:"clubhouse_tour" },*/
					{ name:"Maginnes Uncut", id: "uncut", urlPart:"maginnes_uncut" },
					/*{ name:"In the Bag", id: "itb", urlPart:"in_the_bag" },*/
					{ name:"Outside the Ropes", id: "otr", urlPart:"outside_the_ropes" },
					{ name:"Celebrity Spotlight", id: "celeb", urlPart:"celebrity_spotlight" },
					{ name:"Flyovers", id: "flyovers", urlPart:"flyovers" },
					{ name:"SwingPlex", id: "swingplex", urlPart:"swingplex" },
					{ name:"Payne Stewart", id: "paynestewartaward", urlPart:"payne_stewart_award" },
					{ name:"Charity", id: "charity", urlPart:"charity" },
					{ name:"Commercials", id: "psa", urlPart:"commercials" }
				]
			},
			{ // Shows
				name:"Shows",
				id: "shows",
				urlPart: "shows",
				channels:[
					{ name:"INSIDE the PGA TOUR", id: "inside", urlPart:"inside_the_pga_tour" },
					{ name:"Direct Connect", id: "dct", urlPart:"direct_connect" },
					/*{ name:"Match Play", id: "matchplay", urlPart:"match_play" },*/
					{ name:"Fantasy Insider", id: "fantasy", urlPart:"fantasy_insider" },
					{ name:"PGA TOUR Today", id: "tt", urlPart:"pga_tour_today" },
					{ name:"Monday Backspin", id: "backspin", urlPart:"monday_backspin" }
				]
			},
			{ // Audio
				name:"Audio",
				id: "audio",
				urlPart: "audio",
				channels:[
					{ name:"Talk of the TOUR", id: "tott", urlPart:"talk_of_the_tour" },
					{ name:"oPINionated", id: "opin", urlPart:"opinionated" },
					{ name:"PGA TOUR Replay", id: "replay", urlPart:"pga_tour_replay" },
					{ name:"PGA TOUR Minute", id: "minute", urlPart:"pga_tour_minute" },
					{ name:"Power Rankings", id: "bolton", urlPart:"power_rankings" },
					/*{ name:"TOUR Academy", id: "academy", urlPart:"tour_academy" },*/
					{ name:"Race to Dubai", id: "dubai", urlPart:"race_to_dubai" },
					{ name:"Interviews", id: "xm", urlPart:"interviews" }
				]
			},
			{ // Instruction
				name:"Instruction",
				id: "instruction",
				urlPart:"instruction",
				channels:[
					{ name:"Swing Coaches", id: "coaches", urlPart:"swing_coaches" },
					{ name:"Pro Tips", id: "protips", urlPart:"pro_tips" },
					//{ name:"Technology", id: "tech", urlPart:"technology" },
					{ name:"Pro Fitness", id: "depuy", urlPart:"fitness" },
					{ name:"Equipment", id: "barr ", urlPart:"equipment" }
				]
			}
		]
	}, // End Tour
	{ // Champs
		name: "Champions Tour",
		id: 's',
		urlPart: "champions-tour",
		categories: [
			{ // Video
				name:"Video",
				id: "video",
				urlPart: "video",
				channels:[
					{ name:"Top Shots", id: "highs", urlPart:"top_shots" },
					{ name:"Round Recaps", id: "roundrecaps", urlPart:"round_recaps" },
					{ name:"Interviews", id: "int", urlPart:"interviews" },
					{ name:"Memorable Moments", id: "memmom", urlPart:"memorable_moments" }, // ?? //
					{ name:"Features", id: "features", urlPart:"features" }
				]
			},
			{ // Audio
				name:"Audio",
				id: "audio",
				urlPart: "audio",
				channels:[
					{ name:"Interviews", id: "xm", urlPart:"champions_tour_interviews" }
				]
			}
		]
	}, // End Champs

	{ // Nationwide
		name: "Nationwide Tour",
		id: 'h',
		urlPart: "nationwide-tour",
		categories: [
			{ // Video
				name:"Video",
				id: "video",
				urlPart: "video",
				channels:[
					{ name:"Top Shots", id: "highs", urlPart:"top_shots" },
					{ name:"Interviews", id: "int", urlPart:"interviews" },
					{ name:"Round Recaps", id: "roundrecaps", urlPart:"round_recaps" },
					{ name:"Features", id: "features", urlPart:"features" }
				]
			},
			{ // Audio
				name:"Audio",
				id: "audio",
				channels:[
					{ name:"Interviews", id: "xm", urlPart:"nationwide_tour_interviews" }
				]
			}
		]
	} // End NationWide
];


/////////////////////////////////////////////
// Aug 2010 Redesign Functions (All New)
/////////////////////////////////////////////
// IE 6 & 7 have issue with inline onmouseout / onmouseover event triggers
// so we wrote this function that only gets called for those browsers to wait until the search returns its values and then
// use prototype to loop through and add the events.
// We also add an overlay transparent image to prevent "flashing" as much as possible.
// 
function ieHoverEffectSleeper(firstRun) {
	recall = true;
	if (!firstRun) {
		thumbs = $$('#tourVideoThumbs .tourVideoThumb');
		if (thumbs) {
			thumbs.each(function(s){
				new Insertion.Top(s, '<img src="http://i.cdn.turner.com/pgatour/.element/img/1.gif" class="tourIEDivOverylay"/>')
				Event.observe(s,'mouseover',function(){ this.addClassName('tourVideoThumbHover'); });
				Event.observe(s,'mouseout',function(){ this.removeClassName('tourVideoThumbHover'); });
			});
			recall = false;
		}
	}
	if (recall) { setTimeout('ieHoverEffectSleeper()', 150); }
}

// Custom PROTOTYPE extension to get IE Version
if (Prototype.Browser.IE) { if (/MSIE (\d+\.\d+);/.test(navigator.userAgent)) { Prototype.BrowserFeatures['Version'] = new Number(RegExp.$1); } }


// This function only gets called on initial page load.
// From here, we run through our first calls to set up the search engine
function tourVideoSearchEngineInit() {

	// These variables are used to change categories and channels.
	tourID = categoryID = channelID = '';

	cleanSearchTerm = '';

	var tI=0;

	var newChan = window.location.pathname.replace('/video/','').replace(/\/$/,'').split('/');
	if (newChan) {
		// tourID = 1st Dir or 'r' by default (expecting 'r', 'h', or 's')
		// Using the switch to catch and alert any unexpected values
		switch (newChan[0]) {
			case '':
				tourID = 'r';
				break;
			case 'r': case 's': case 'h':
				tourID = newChan[0];
				break;
		
			default:
				throw("Unexpected Tour ID: '"+newChan[0]+"'");
				return;
		}

		// categoryID = 2nd Dir
		// Use this switch to catch any URL vs ID discrepancies. 
		if (newChan[1]) {
			categoryID = newChan[1];
			switch(newChan[1]) {
				default:
					break;
			}
		}

		// channelID = 3rd Dir
		// Use this switch to catch any URL vs ID discrepancies. 
		if (newChan[2]) {
			channelID = newChan[2];
			switch (newChan[2]) {
				case 'technology':
					// /r/instruction/technology 
					if (newChan[0]=='r' && newChan[1] == 'instruction') { channelID = 'tech'; }
					break;
				default:
					break;
			}
		}
	} else {
		throw('URL does not match expected format.');
		return;
	}

	VideoChannels.each(function(s, i) { if (s.id == tourID) { tI = i; throw $break; } });
	theTour = VideoChannels[tI];
	tourVideoChangeCategory();
	searchEngineStarted = true;
}

var searchEngineStarted = false;

// Updates the Category Bar with the Tour's 
function tourVideoChangeCategory(catID) {

	var caI = 0;
	// Get the current category & build the category bar.
	if (!categoryID) { categoryID = theTour.categories[0].id; }
	if (catID) { categoryID = catID; channelID='';}

	var categoryBarHTML = '<ul class="clearfix">';
	theTour.categories.each(function(s, i) {

		categoryBarHTML += '<li ';
		if (s.urlPart == categoryID || s.id == categoryID) { 
			categoryBarHTML += 'class="'+categoryAClass+'"';
			caI = i; 
		}
		categoryBarHTML +='><a href="#" onclick="tourVideoChangeCategory(\''+s.id+'\'); isManualSearch = false; return false;">'+s.name.toUpperCase()+'</a>';
	});

	categoryBarHTML += '<li class="searchtab';
	if (categoryID == 'pgatour_search_catcher') { 
		// Catcher to highlight the search tab
		// categoryBarHTML += ' active';
		categoryBarHTML += ''; //Changed value from ' active' to '' so that search tab does not get selected
	} 
	categoryBarHTML += '"><form onsubmit="video_search(); return false;"><input type="text" value="';
	if (cleanSearchTerm != '') { categoryBarHTML += cleanSearchTerm; } else { categoryBarHTML += 'search'; }
	categoryBarHTML += '" id="video_search_string" name="video_search_string" onfocus="if(this.value==\'search\'){this.value=\'\'} else {this.select()}" onblur="if(this.value==\'\'){this.value=\'search\'}"><input type="image" id="submitImg" name="" src="http://i.cdn.turner.com/pgatour/.element/img/1.gif"></form></li></ul>';

	$(categoriesID).innerHTML = categoryBarHTML;
	theCategory = theTour.categories[caI];

	if (categoryID != 'pgatour_search_catcher') { tourVideoChangeChannel(); }
}

function tourVideoChangeChannel(chanID) {
	var chI = 0;

	var channelHTML = '<ul>';
	// Get the current channel & build the channel bar.
	if (!channelID) { channelID = theCategory.channels[0].id; }
	if (chanID) { channelID = chanID; }
	theCategory.channels.each(function(s, i) {
		channelHTML += '<li><a href="#" onclick="tourVideoChangeChannel(\''+s.id+'\'); return false;"';
		if (channelID == s.urlPart || channelID == s.id) {
			chI = i; 
			channelHTML += ' class="'+channelAClass+'"';
		}
		channelHTML +='>'+s.name+'</a></li>';
	});
	channelHTML +='</ul>';
	$(channelsID).innerHTML = channelHTML;
	theChannel = theCategory.channels[chI];
	$('tourVideoChannelTitle').innerHTML = theChannel.name;
	newSearchParam = '&tc='+theTour.id+'&cat='+theCategory.id+'&chnl='+theChannel.id+'&sort=date&isExpired=no';
	tourVideoUpdateSearchResults(newSearchParam);
	if (Prototype.Browser.IE && Prototype.BrowserFeatures['Version'] < 8) { ieHoverEffectSleeper(true); }
	
	 videoChannelHeader = document.getElementById('tourVideoChannelTitle').innerHTML;
     if(videoChannelHeader == 'Payne Stewart'){document.getElementById('tourVideoChannelTitle').innerHTML = 'Payne Stewart Award'}
}

function tourVideoUpdateSearchResults(searchURL,searchQuery) {
	if (searchURL) {
		coreUpdateAttributeWithoutCalling(searchURL,0);
		SEARCH_ORIGIN = 'channel_search';
		var search = getParam('s');

		if (searchEngineStarted) {
			//coreUpdateQuery('*');
			tourSearchAnew(1, '*');
			//coreAddSearchAttribute('all', 0, 1);
		} 
		else if(!search){
			// Give the browser a breather to load the first results.
			// We are not sure why, but there is a race condition that throws
			// some browsers into a death roll if we call the funciton immediately.
			Event.observe(window, 'load',function() { coreUpdateQuery("*")} )
		}
	}
}

function tourSearchAnew(_newPage, _query) {
	SearchProcessor.getInstance().tourSearchAnew(1, 0, _newPage, _query);
}

// Call this function instead of coreAddSearchAttribute() to change the attributes and SELECTIVELY reload the results.
function tourAddSearchAttribute(newAttribs, autoReload) {

	SearchProcessor.getInstance().allInstancesQuery[0].extraUrlParameters = newAttribs;
	if (autoReload) { SearchProcessor.getInstance().changePage(1, 0); }
}

function execute_video_change(newURL) { window.location.href = newURL; }

function tourWriteSectionTitle() {
	var title_ = '';
	if (oVideoChannel.title == "Top 10") {
		$('video_section_title').innerHTML = "Top 10's";
	}
	else if (oVideoChannel.title == "Default") {
		$('video_section_title').innerHTML = " ";
	}
	else if (oVideoChannel.title == "Fitness") {
		$('video_section_title').innerHTML = "Pro Fitness";
	}
	else if (oVideoChannel.title == "Clubhouse Tour") {
		$('video_section_title').innerHTML = "19th Hole";
	}
	else if (oVideoChannel.title == "Live At") {
		$('video_section_title').innerHTML = "LIVE@";
	}

	$('video_section_title').style.visibility = "visible";

}

Event.observe(document,"dom:loaded",tourWriteSectionTitle);
Event.observe(document,"dom:loaded",tourVideoSearchEngineInit);
//Event.observe(window, "load", function(){ tourCVPMain.embedSWF('tourCVP'); })
