var currentTabButton = null;
var currentTechLink = null;
var cpy_TechCategoryHeader = null;
var cpy_TechSectionHeader = null;
var cpy_TechSectionCopy = null;
var cpy_TechSectionLink = null;
var flashready = null;
var xmlMediaList = null;
//var cpy_mediaPlayer = null;

jQuery(document).ready(function() {
	
	jQuery(".handofgodButton").click(function() {
		var $this = jQuery(this);
		handleTabBtnClick($this);
	});
	
	// set a default opened additional content section
	currentTabButton = jQuery("div[tabTitle='productDetails']").filter(".handofgodButton");
	currentTabButton.children("div:first").addClass("handofgodTabButtonSelected");
	//explicitly run pngfix here because we've just added one
	currentTabButton.pngFix();
	
	//position the hand for the newly selected button
	positionSelectedButton();
	
	// since product details is defaulted open just call the function that wires up all the events for that "tab"
	//wireupProductDetailsContent();
	
	embedFlash();
	
	// this needed to be moved here so that the player was loaded into the DOM first, otherwise it couldn't find it.
	jQuery(".featureCategoryDiv li:not(.nonLink)" ).click(function () {
		var $this = jQuery(this);
		handleTechLinkClicked($this);
	});
	

	// probably wire up hover states as well
	jQuery(".featureCategoryDiv li").hover(
		function() {
			jQuery(this).addClass("hover");
		},
		function() {
			jQuery(this).removeClass("hover");
		}
	);
	// grab the jquery elements for updating the third column
	cpy_TechCategoryHeader = jQuery("#techCategoryHeader");
	cpy_TechSectionHeader = jQuery("#techSectionHeader");
	cpy_TechSectionCopy = jQuery("#techSectionCopy");
	cpy_TechSectionLink = jQuery("#techSectionLink");
	
	
	// assign the default currentTechLink: it will just be the first item
	currentTechLink = jQuery( '.featureCategoryDiv:not(.nonLink) li:not(.nonLink):first' );
	
	handleTechLinkClicked(currentTechLink);
	currentTechLink.addClass("selected");
});

//for the selected button, move the finger so it's in the middle of the word, pointing at the top, and make it flexible in case the padding changes.
//TODO: take into account the font size for the top position...will need a way to convert em to px, though.
function positionSelectedButton() {
	var leftpos = -95 + (currentTabButton.outerWidth() / 2);
	var toppadding = jQuery(".handofgodButtonLink").css("padding-top");
	toppadding = new Number(toppadding.substr(0, toppadding.length -2));
	var toppos = -100 + toppadding; 
	jQuery(".handofgodTabButtonSelected").css({"left" : leftpos + "px", "top" : toppos + "px"});
	jQuery(".handofgodButton a").removeClass("active");
	currentTabButton.find("a").addClass("active");
}

function handleTabBtnClick(tabButton) {
	//alert(currentTabButton.attr("tabTitle"));
	if(!isCurrentTabButton(tabButton)) {
		jQuery("div[tabTitle = '" + tabButton.attr('tabTitle') + "']:not(.handofgodButton)").addClass("open");
		tabButton.children("div:first").addClass("handofgodTabButtonSelected");
		if(currentTabButton) {
			jQuery("div[tabTitle = '" + currentTabButton.attr('tabTitle') + "']:not(.handofgodButton)").removeClass("open");
			currentTabButton.children("div:first").removeClass("handofgodTabButtonSelected");
		}
		
		currentTabButton = tabButton;
		//explicitly run pngfix here because we've just added one
		currentTabButton.pngFix();
		
		positionSelectedButton();
	}
}

function isCurrentTabButton(tabButton) {
	var returnValue = false;
	if(tabButton.attr("tabTitle") == currentTabButton.attr("tabTitle")) {returnValue = true;}
	
	return returnValue;
}

// define an event handler that fires when the component has been fully instanced
function onMediaBrowserInstanced(pID){
	flashready = "true";
	if(console.log){
		console.log("MediaBrowser says hello!");
	}
}

function checkFlashReady()
{
	if (flashready != "true")
	{
		//continue
	}
	else
	{
		clearCheck();
		document.getElementById('mediaPlayer').setPlaylistByXMLString(xmlMediaList);
	}
}


function clearCheck()
{
	clearInterval(readyInterval);
}

function embedFlash()
{
	var flashvars = {
			playlistURL: mediaPlayerList,
			minWidth: 347,
			minHeight: 195,
			eventHandlerCB: "onMediaBrowserEvent",
			instanceCB: "onMediaBrowserInstanced",
			allowFullscreen: false
		};
 
		var params = {
			allowScriptAccess: "always",
			bgcolor: "#000000"
		};
	
		var attributes = {
			id: "mediaPlayer"
		};
		
		swfobject.embedSWF(mediaPlayerURL, "mediaPlayer", "347", "220", "9.0.15", "", flashvars, params, attributes);
}

function handleTechLinkClicked(techLink) {
	if(!isCurrentTechLink(techLink)) {
		jQuery("#mediaPlayerFrame").hide();
		flashready = false;
		// update content
		
		// enable links selected state
		techLink.addClass("selected");
		 
		
		// grab category Header
		cpy_TechCategoryHeader.html(techLink.parent().siblings(":first").html());
		// grab link Header
		cpy_TechSectionHeader.html(techLink.html());
		// grab the copy for the new link
		cpy_TechSectionCopy.empty();
		cpy_TechSectionCopy.append( techLink.children( "div.DW_PDP_FD_longDescriptionHTML").clone().show() );
		
		// grab the copy for the new link
		cpy_TechSectionLink.empty();
		cpy_TechSectionLink.append( techLink.children( "div.DW_PDP_FD_techlink").clone().show() );
				
		
		// Extract media list if any media available
		var mediaList = null;
		if ( techLink.children( "div.DW_PDP_FD_mediaList").html() ) {
			mediaList = techLink.children( "div.DW_PDP_FD_mediaList").html().split(',');
		}
		
		// is the media player necessary?
		if( mediaList && mediaList.length > 0)
		{
			// not sure how to actually figure this out, I imagine it will be coming from extending the app javascript object for product in some way
			xmlMediaList = "";
			for ( var i = mediaList.length - 1; i >= 0; i-- )
			{
				if ( !trim( mediaList[i]) )
					arrayRemove( mediaList, i );
				else 
				{ 
					// get the type of media
					var xmlMediaItem ="";
					if (mediaList[i].indexOf(".flv") == mediaList[i].length-4)
					{
						xmlMediaList = xmlMediaList.length == 0 ? '<?xml version="1.0" encoding="utf-8"?><playlist contentType="video" autoplay="false" loop="false">' : xmlMediaList;
						xmlMediaItem = '<item src="http://btv.burton.com/2010/Videos/Tech/' + mediaList[i] + '" imageURL="http://btv.burton.com/2010/Videos/Tech/CTP/' + mediaList[i].replace(".flv", ".jpg") + '"><caption></caption></item>';
					}
					else 
					{ 
						xmlMediaList = xmlMediaList.length == 0 ? '<?xml version="1.0" encoding="utf-8"?><playlist contentType="image" autoplay="true" delayms="3000">' : xmlMediaList;
						xmlMediaItem = '<item imageURL="http://btv.burton.com/2010/Videos/Tech/' + mediaList[i] + '"><caption></caption></item>';
					}
					
					xmlMediaList += xmlMediaItem;
					
					
									
				}
			}

			xmlMediaList += "</playlist>";
			//alert("Movie: " + " media " + mediaList[i] + " xmlMediaList:" +xmlMediaList);
			jQuery("#mediaPlayerFrame").show();   // and probably update the data that drives the media player
			if ( document.getElementById('mediaPlayer') != null )    
			{   
				readyInterval = setInterval("checkFlashReady()", 500);
			}
		}
		else
		{
			jQuery("#mediaPlayerFrame").hide();
		}
		
		if (currentTechLink)
		{
			//disable links selected state
			currentTechLink.removeClass("selected");
		}
		
		// swap out new active link;
		currentTechLink = techLink;
	}
}

var WHITE_SPACE = " \t\n\r";
function trim( str )
{
	/*
	if ( !str )
		return;
	*/
	for ( var i = 0; i < str.length; i++ )
	{
		if ( WHITE_SPACE.indexOf( str.charAt( i ) ) == -1 )
		{
			if ( i )
				str = str.substr( i );
			break;
		}
	}
	for ( i = str.length - 1; i >= 0; i-- )
	{
		if ( WHITE_SPACE.indexOf( str.charAt( i ) ) == -1 )
		{
			if ( i != str.length - 1 )
				str = str.substr( 0, i + 1 );
			break;
		}
	}
	return str;
}

function arrayRemove(arr, from, to)
{
	  var rest = arr.slice((to || from) + 1 || arr.length);
	  arr.length = from < 0 ? arr.length + from : from;
	  return arr.push.apply(arr, rest);
};

function isCurrentTechLink(techLink) {
	var returnValue = false;
	if(techLink.attr("key") == currentTechLink.attr("key") && techLink.parent().siblings(":first") == currentTechLink.parent().siblings(":first")) 
	{
		returnvalue = true;
	}
	return returnValue;
}