/*
 * Story Details page javascript
 * 
 * NOTE: THIS FILE IS USED TO CREATE story_detail.pack.js WHICH IS USED BY THE LIVE SITE
 * MAKE SURE TO CREATE THE UPDATED PACK VERSION AFTER MAKING CHANGES HERE
 * 
 * IF YOU CANNOT CREATE A PACKED VERSION, JUST COPY THE FULL SIZE VERSION INTO THE .PACK FILE
 * 
 * To enable debug mode, use query string ?test=1 or ?test=2
 * 
 * 
 * 
 * 
 * 
 * 
 * 
 * 
 * 
 * 
 * 
 * 
 * 
 * 
 * 
 * 
 * 
 * 
 * 
 * 
 * 
 * 
 * 
 * 
 * 
 */

////////////////////////////////////////////////////////////////////////////////////////////////
// BEGIN CONFIGURATION: Set the values for the main media asset area
////////////////////////////////////////////////////////////////////////////////////////////////
var mediaDisplayAreaMaxWidth = 316;
var mediaDisplayAreaDefaultHeight = 234;
var audioPlayerMaxWidth = 260;
var audioPlayerMaxHeight = 20;
var photoGalleryMaxWidth = mediaDisplayAreaMaxWidth;
var photoGalleryMaxHeight = 274;
var vmixMaxWidth = mediaDisplayAreaMaxWidth;
var vmixMaxHeight = 257;
var videoControlsHeightSWF = 0;
var videoControlsHeightWMV = 45;
var videoControlsHeightMOV = 0;
var scrollToTopHeight = 237; // Where should the browser jump to when scrolling back to the top
// Use this to replace characters that break the section front linking autoplay
var vmix_asset_id_replace = /%|!|\.|\*|\$/g; // Other potentially bad characters: [\^$.|?*+(){}

var currDomain = document.domain;
if (currDomain.indexOf("miamiherald")!=-1) {
	var mediaServerURL = "http://media.miamiherald.com";
}
if (currDomain.indexOf("elnuevoherald")!=-1) {
	var mediaServerURL = "http://media.elnuevoherald.com";
}

////////////////////////////////////////////////////////////////////////////////////////////////
// END CONFIGURATION
////////////////////////////////////////////////////////////////////////////////////////////////




/*
 * Tell JavaScript how much of each type of content there is
 */
var storyVideoCount = 0; // Must be decalred to here to be properly updated by the .comp
var storyVideoBoxCount;
var storyVideoOldTypeCount;
var storyAudioCount;
var storyPhotoCount;
var storyPhotoGalleryCount;
var storySoundslidesCount;
var storyGoogleMapCount;
var storyMapBoxCount;











var storyVideoCurrent = 0; // Count current video box

// If this page is called from a story's media link on a section front, get the parameters
var defaultAssetID = getQueryStrVariable('asset_id');
var defaultAssetType = getQueryStrVariable('asset_type');

// handle the spanish accents incoming through AJAX
/*
		$.ajaxSetup({
			'beforeSend' : function(xhr) {
				xhr.overrideMimeType('text/html; charset=iso-8859-1');
			},
		});
*/


/*
 * On Page load, 
 */
 $(document).ready(function(){
/////////////// TEMPORARY FIX. REMOVE AFTER ALL PAGES HAVE RELOADED WITH NO CF IN BODYCONTENT
	$('#storyBodyContent').removeClass('cf');

// Here we attach functions to resize text to the anchors on story detail pages.
	$("#txtResizeMinusLink").click(function () { 
		txtResizeSmaller();
	});
	$("#txtResizePlusLink").click(function () { 
		txtResizeLarger();
	});

// Reformat Yahoo Buzz button
/* // Removed when footer was converted to link instead of JS widget call
	$('div.storyTools_footer div.storyShareTextBar div.shareLinksArea ul.shareLinks li.buzzStoryLink span.yahooBuzzBadge a span span').css({
		'background-image':'none',
		'background':'none'
	});
	$('div.storyTools_footer div.storyShareTextBar div.shareLinksArea ul.shareLinks li.buzzStoryLink span.yahooBuzzBadge a span').css({
		'padding-left':'0',
		'padding':'0'
	});
	$('div.storyTools_footer div.storyShareTextBar div.shareLinksArea ul.shareLinks li.buzzStoryLink span.yahooBuzzBadge a').css({
		'background-position':'left'
	});
*/


////////////////////////////////////////////////////////////////////////////////////////////////
// Set CLICK TRIGGER - AUDIO
////////////////////////////////////////////////////////////////////////////////////////////////
	$('#storyAssetMediaDisplayAreaLinks #storyAudioLinksArea ul li.storyAssetSingle a.media_jquery_audio_link').click(function(){
	alertTest('CLICKED - Audio  - Link href = ' + $(this).attr('href'));

		loadAudioEmbed($(this).attr('href'));
		setstoryAssetNowPlaying(this); // Find the originating link and set to the now playing state
		return false;
	});

////////////////////////////////////////////////////////////////////////////////////////////////
// Set CLICK TRIGGER - photo GALLERY
////////////////////////////////////////////////////////////////////////////////////////////////
//	$('#storyAssetMediaDisplayAreaLinks div.storyPhotoLinksArea ul.mediaAssetList div.storyPhotoGalleryLinksArea li.storyAssetSingle a.storyPhotoGalleryLink').click(function(){
	$('#storyAssetMediaDisplayAreaLinks a.storyPhotoGalleryLink').click(function(){
	alertTest('CLICKED - Photo Gallery  - Link href = ' + $(this).attr('href'));
		
		loadPhotoGalleryEmbed($(this).attr('href'));
		setstoryAssetNowPlaying(this); // Find the originating link and set to the now playing state
		return false;
	});


////////////////////////////////////////////////////////////////////////////////////////////////
// Set CLICK TRIGGER - SINGLE PHOTO
////////////////////////////////////////////////////////////////////////////////////////////////
	$('#storyAssetMediaDisplayAreaLinks #storyAssetAttachPhotoLink').click(function(){
	alertTest('CLICKED - single photo - Link href = ' + $(this).attr('href'));
		
		hideAllMedia();
		$('#storyPhotoContentArea div.storyAssetSingle').show();
		setstoryAssetNowPlaying(this); // Find the originating link and set to the now playing state
		return false;
	});


////////////////////////////////////////////////////////////////////////////////////////////////
// Set CLICK TRIGGER - VIDEO
////////////////////////////////////////////////////////////////////////////////////////////////
// This is handled by displayVideoVmixEmbedLink() to instantiate the click routine after the link is created

////////////////////////////////////////////////////////////////////////////////////////////////
// Set CLICK TRIGGER - VIDEO OLD Type
////////////////////////////////////////////////////////////////////////////////////////////////
	$('#storyAssetMediaDisplayAreaLinks li.storyAssetSingle a.media_jquery_video_link').click(function(){
		alertTest('CLICKED - Video  - Link CLASS = ' + $(this).attr('class'));

		loadVideoOldTypeEmbed($(this).attr('href'));
		setstoryAssetNowPlaying(this); // Find the originating link and set to the now playing state
		return false;
	});


////////////////////////////////////////////////////////////////////////////////////////////////
// Set CLICK TRIGGER - Google Map / MAP BOX
////////////////////////////////////////////////////////////////////////////////////////////////
	$('#storyNonImageContentArea ul.link_list li.storyAssetSingle a.storyMapLink').click(function(){
		alertTest('CLICKED - MAP BOX  - Link CLASS = ' + $(this).attr('class'));
	// Create new video file holder - Must hideAll() first to make sure the destination area is empty
		hideAllMedia();

		$('#storyAssetMediaDisplayArea #storyGoogleMapBoxContentArea div.storyAssetSingle').show();

		// When the map is created while hidden w/o a width, it is confused in FF.
		// If it is a google map initialize it one way. Otherwise use the other method
		if (storyGoogleMapCount) {
			reInitializeGoogleMap();
		}
		else if (storyMapBoxCount) {
			initmap();
		}

		setstoryAssetNowPlaying(this); // Find the originating link and set to the now playing state

		scrollToTop('map');

		return false;
	});


////////////////////////////////////////////////////////////////////////////////////////////////
// Initialize the SHARE TOOLS hiding functions
////////////////////////////////////////////////////////////////////////////////////////////////

	$('div.storyTools div.storyShareTextBar div.shareLinksArea ul.shareLinks li.shareStoryLink a').click(function(){
	// Toggle the shared layer
		$('div.storyTools div.storyShareToolsBar').toggle();
		return false;
	});
	$('div.storyTools_footer div.storyShareTextBar div.shareLinksArea ul.shareLinks li.shareStoryLink a').click(function(){
	// Toggle the shared layer
		$('div.storyTools_footer div.storyShareToolsBar').toggle();
		return false;
	});


////////////////////////////////////////////////////////////////////////////////////////////////
// Set CLICK TRIGGER - Pluck Recommend Tool Link
////////////////////////////////////////////////////////////////////////////////////////////////
// When the user clicks either link, call pluck and replicate to the footer link.
	var footerRecommendLI = $('div.storyTools_footer div.storyShareTextBar div.shareLinksArea ul.shareLinks li.recommendStoryLink');
	var footerRecommendLink = $(footerRecommendLI).find('a');

	$(footerRecommendLink).click(function(){
		var pluckRecommendedLI = $('div.storyTools div.storyShareTextBar div.shareLinksArea ul.shareLinks li.recommendStoryLink');
		var pluckRecommendLink = $(pluckRecommendedLI).find('a');
	alertTest('Pluck link clicked now');

		$(footerRecommendLink).addClass('pluck_recommended');
		$(footerRecommendLink).text('recommended');
		$(pluckRecommendLink).addClass('pluck_recommended');

		if (($(this).hasClass('pluck_recommended')) || ($(pluckRecommendedLI).find('#story_recommended_count'))) {
			// Do nothing, link has been clicked
			alertTest('Pluck ALREADY clicked');
			return false;
		}
		else {
			alertTest('This is the pluck footer link');
			artRecommend(); // initialize recommend script
			return false;
		}
	});

// Determine which media to display: Video if available and on down the line
// Setup the jQuery player media defaults
		loadStoryAssetMediaDisplayArea();



////////////////////////////////////////////////////////////////////////////////////////////////
}); // END $(document).ready(function(){})
////////////////////////////////////////////////////////////////////////////////////////////////



////////////////////////////////////////////////////////////////////////////////////////////////
// Standard Document Functions
////////////////////////////////////////////////////////////////////////////////////////////////

/*********************
 * Loading graphic HTML
 */
var storyAssetMediaLoadingImage = '<div class="storyAssetMediaLoadingImage"><img alt="Loading..." src="/static/images/redesign/ajax-loader_media-assets.gif"/></div>';

/*********************
 * HIDE main asset image / player area display
 */
function hideAllMedia() {
// Hide all the media display area content in preparation to show it
	alertTest('Hiding all media display area content');

	// Remove existing Video box holder
	if ($('div.storyVideoBoxContentArea').html() != "") {
		alertTest('Video Box (Vmix) Area EXISTS and will be removed');
		$('div.storyVideoBoxContentArea div.storyAssetSingle div').remove();
		$('div.storyVideoBoxContentArea div.storyAssetSingle').empty();
	}
	
	// Remove existing Video Old Type holder
	if ($('div.storyVideoOldTypeContentArea').html() != "") {
		alertTest('Video File (Old Type) Area EXISTS and will be removed');
		$('div.storyVideoOldTypeContentArea div.storyAssetSingle').remove();
		$('div.storyVideoOldTypeContentArea').empty();
	}
	
	// Remove existing Audio
	if ($('div.storyAudioContentArea').html() != "") {
		alertTest('Audio File Area EXISTS and will be removed');
		$('div.storyAudioContentArea div.storyAssetSingle').remove();
		$('div.storyAudioContentArea').empty();
	}
	
	// Remove existing Google Map
		$('#storyAssetMediaDisplayArea #storyGoogleMapBoxContentArea div.storyAssetSingle').hide();

	// Remove existing single attached photo
		$('#storyPhotoContentArea div.storyAssetSingle').hide();
	
	// Remove existing photo gallery holder
	if ($('#storyPhotoGalleryContentArea div.storyAssetSingle').html() != "") {
		alertTest('Photo Gallery Area EXISTS and will be removed');
		$('#storyPhotoGalleryContentArea div.storyAssetSingle object').remove();
		$('#storyPhotoGalleryContentArea div.storyAssetSingle').empty();
//		$('#storyPhotoGalleryContentArea div.storyAssetSingle').remove();
//		$('#storyPhotoGalleryContentArea').empty();
	}

	// Hide the download flash link (in case the user clicks on a non flash asset)
	$('#storyAssetMediaDisplayArea .getFlashPlayer').css('display','none');

} // END hideAllMedia()


/*********************
 * Control current Now Playing link color
 */
function setstoryAssetNowPlaying(thisLink) {
	alertTest('storyAssetNowPlaying triggered. Link CLASS = ' + $(thisLink).attr('class'));
	$('.storyAssetNowPlaying').removeClass('storyAssetNowPlaying');	
	$(thisLink).addClass('storyAssetNowPlaying');	

}

/*********************
 * Load the Flash PHOTO GALLERY content
 */
function loadPhotoGalleryEmbed(flashvarsXML){
// Pass this function an XML feed with the list of images.
	var params = {};
	params.quality = "best";
	params.allowfullscreen = "true";
	params.allowscriptaccess="always";
	params.wmode = "transparent";

	var attributes = {};
	attributes.id = "PhotoGallery";

	var photoGalDestinationID = "photoGalleryPlaceHolder";

	var flashvars = {};
	if (flashvarsXML.charAt(0) == '#') {
	// In case there is a # in front of URL
		flashvarsXML = mediaServerURL + flashvarsXML.substring(1);
	}
	flashvars.xmlfile = flashvarsXML;

	// Create new photo gallery holder - Must run hide first to make sure the destination area is empty
		hideAllMedia();
		alertTest('Photo Gallery Area is UNDEFINED and will be created');
		$('#storyPhotoGalleryContentArea div.storyAssetSingle').append('<div id="' + photoGalDestinationID + '"></div>');
	// Assign ID to new photo gallery holder
		$('#storyPhotoGalleryContentArea div.storyAssetSingle div').attr('id',photoGalDestinationID);

// Instantiate SWFobject
	swfobject.embedSWF(mediaServerURL + "/static/multimedia/story_detail/StoryLevel-PhotoGallery.swf", photoGalDestinationID, photoGalleryMaxWidth, photoGalleryMaxHeight, "9.0.115", mediaServerURL + "/scripts/expressInstall.swf", flashvars, params, attributes);

	// If the flash player does not load, show the download flash link
	checkStoryAssetNoFlashLink($('#' + photoGalDestinationID));

}

/*********************
 * Load the inline Flash Video Box Player (VMIX)
 */
function showVideoVmixEmbed(media_id,vmix_player_id,vmix_token){
	alertTest('Vmix video being displayed as embedded');

// Create the destination for the inline vmix video
	var destinationID = "inlineVmixPlaceHolder_" + media_id;
	document.write('<div id="' + destinationID + '">' + storyAssetMediaLoadingImage + '</div>');

// Need to tell the parent div.html_module to display
	$('#vmix_title_' + media_id).parents('div.html_module').addClass('vmix_html_module').css({
		'display':'inline',
		'float':'left'
	});

	// Call the video display function and pass it the display ID's as an href 
	// and give it the destination ID name. Empty fields are being passed &nbsp;
	$(document).ready(function(){

		displayVideoVmixEmbed('#?media_id=' + media_id + '&player_id=' + vmix_player_id + '&token=' + vmix_token + '&vmix_title=%26nbsp%3B&vmix_descrip=%26nbsp%3B&vmix_credit=%26nbsp%3B',destinationID);
	});
}

/*********************
 * Write out the Video Box VMIX link
 * 
 * NOTE: Do not change the function name: displayVideoVmixEmbedLink() as it is used
 *       by the html_module, top_stories, etc to determine if there is vmix in the HM
 * 
 */
var vmix_titles = new Object;
var vmix_descrips = new Object;
var vmix_credits = new Object;
var vmix_asset_id = new Object;
var linkAreaUL = "";
var newLink = "";
var newLinkHref = "";
var newLinkIcon = "";
function displayVideoVmixEmbedLink(media_id,vmix_player_id,vmix_token) {
// Store the Vmix meta info to an object identified by the vmix media id.
// This data will be stored as an href so it must be escaped
	vmix_titles[media_id] = escape($('#vmix_title_' + media_id).html()); // Replace all line breaks
	vmix_descrips[media_id] = escape($('#vmix_descrip_' + media_id).html());
	vmix_credits[media_id] = escape($('#vmix_credit_' + media_id).html());
	vmix_asset_id[media_id] = $('#vmix_title_' + media_id).parents('.html_module').attr('id').replace(vmix_asset_id_replace, ""); // Replace escaped % signs

// Determine where this link should be shown and what they href should be
	alertTest('templateType == "' + templateType + '"');
	// STORY LEVEL
	if (templateType.indexOf("story") == 0 )  {
		linkAreaUL = $('#storyAssetMediaDisplayAreaLinks #storyVideoLinksArea ul.mediaAssetList');
		newLinkHref = '#player_id=' + vmix_player_id + '&token=' + vmix_token + '&media_id=' + media_id + '&vmix_title=' + vmix_titles[media_id] + '&vmix_credit=' + vmix_credits[media_id] + '&vmix_descrip=' + vmix_descrips[media_id];
	} // END if storylevel

	alertTest('STORY LEVEL: WRITE OUT VMIX LINK: ' + newLinkHref);

// Append New LI tag
	$(linkAreaUL).append('<li></li>');
// Modify last new LI element, add new link
	$(linkAreaUL).find('li:last').addClass('storyAssetSingle').append('<a onclick="javascript:return false; ">' + unescape(vmix_titles[media_id]) + newLinkIcon + '</a>');
// Modify last new Link and creat href to be parsed by click-to-display function
	$(linkAreaUL).find('li.storyAssetSingle:last a').attr('href',newLinkHref).addClass('vmixLink asset_type_html_module ' + vmix_asset_id[media_id]);
	alertTest('linkAreaUL class: ' + $(linkAreaUL).attr('class'));

	/*********************
	* Setup the click event and 
	* Load the first vmix video
	*/
	if (templateType.indexOf("story") == 0 )  {
		// Increment the current video html_module counter to instantiate only after all links are ready
		storyVideoCurrent++;
		if (storyVideoCurrent == storyVideoCount) {
			alertTest('LAST html_module FOUND, initialize vmix links: storyVideoCount = ' + storyVideoCount);
	
			////////////////////////////////////////////////////////////////////////////////////////////////
			// Set CLICK TRIGGER - html_module (Vmix)
			////////////////////////////////////////////////////////////////////////////////////////////////
			$(linkAreaUL).find('li.storyAssetSingle a.vmixLink').click(function(){
				alertTest('CLICKED - html_module - Link CLASS = ' + $(this).attr('class'));
				
				var flashvarsHref = $(this).attr('href');
				displayVideoVmixEmbed(flashvarsHref);
				setstoryAssetNowPlaying(this); // Find the originating link and set to the now playing state


				return false;
			});


			// If the URL does not have a default media asset to be played, play the first video
			// If it is an audio link, continue as normal since video should still load
			if (!(defaultAssetID) || (defaultAssetType == 'audio')) {
				// Play the first vmix link
				$('a.vmixLink:first').trigger('click');
			}
			// If the default asset is a video
			if (defaultAssetType == 'html_module') {
			// Run this only after the video links have been dynamically created
				alertTest('Running displayDefaultAsset() for html_module');
				displayDefaultAsset();
		    }

		} // END if storyVideoCount
	} // END IF story-detail
} // END displayVideoVmixEmbedLink()






/*********************
 * Load the Flash Video Box Player (VMIX)
 */
function displayVideoVmixEmbed(flashvarsHref,destinationID){
// Pass this function a code for the video.
	var params = {};
	params.quality = "best";
	params.allowfullscreen = "true";
	params.allowscriptaccess="always";
	params.wmode = "transparent";

	var attributes = {};
	attributes.id  = "VideoBox";
	attributes.name  = "UnifiedVideoPlayer";
	
	var flashvars = {};
	if (flashvarsHref.charAt(0) == '#') {
	// In case there is a # in front of URL
		flashvarsHref = flashvarsHref.substring(1);
	}
	// Parse the variables. For the meta info, the data must be unescaped
	var vmix_media_id = getQueryStrVariable('media_id',flashvarsHref);
	var vmix_player_id = getQueryStrVariable('player_id',flashvarsHref);
	var vmix_token = getQueryStrVariable('token',flashvarsHref);
	var vmix_title = unescape(getQueryStrVariable('vmix_title',flashvarsHref));
	var vmix_descrip = unescape(getQueryStrVariable('vmix_descrip',flashvarsHref));
	var vmix_credit = unescape(getQueryStrVariable('vmix_credit',flashvarsHref));

	flashvars.player_id = vmix_player_id;
	flashvars.token = vmix_token;

	// If a destination Id is passed, use that.
	if (destinationID) {
		var videoBoxDestinationID = destinationID;
	}
	else {
		var videoBoxDestinationID = "videoBoxPlaceHolder_" + vmix_media_id;
	}



	// Create new video box holder - Must run hide first to make sure the destination area is empty
		hideAllMedia();
		alertTest('Video Box Area is UNDEFINED and will be created');
		$('div.storyVideoBoxContentArea div.storyAssetSingle').append('<div id="' + videoBoxDestinationID + '"></div>');
	// Assign ID to new video box holder
		$('div.storyVideoBoxContentArea div.storyAssetSingle div').attr('id',videoBoxDestinationID);

// Instantiate SWFobject
//	Old file: http://media.m.com/core-flash/UnifiedVideoPlayer/UnifiedVideoPlayer.swf
	swfobject.embedSWF(mediaServerURL + "/static/multimedia/story_detail/UnifiedVideoPlayer.swf", videoBoxDestinationID, vmixMaxWidth, vmixMaxHeight, "9.0.115", mediaServerURL + "/scripts/expressInstall.swf", flashvars, params, attributes);
/**
 * THIS FUNCTIONALITY IS BROKEN. When the page loads w/ flash enabled, the links shows.
 * When the user clicks any flash asset link, it does not return.
 */
	// If the flash player does not load, show the download flash link
	//			checkStoryAssetNoFlashLink($('#' + videoBoxDestinationID));



// Insert the additional info
	if ((vmix_title) || (vmix_descrip) || (vmix_credit)) {
		$('div.storyVideoBoxContentArea div.storyAssetSingle').append('<div class="vmixCaptionArea"></div>');
		$('div.storyVideoBoxContentArea div.storyAssetSingle div:last').addClass('vmixCaptionArea');
	}
	if (vmix_title) {
		$('div.storyVideoBoxContentArea div.storyAssetSingle div.vmixCaptionArea').append('<div class="vmixTitle">' + vmix_title + '</div>');
		$('div.storyVideoBoxContentArea div.storyAssetSingle div.vmixCaptionArea div:last').addClass('vmixTitle');
	}
	if (vmix_descrip) {
		$('div.storyVideoBoxContentArea div.storyAssetSingle div.vmixCaptionArea').append('<div class="vmixDescrip">' + vmix_descrip + '</div>');
		$('div.storyVideoBoxContentArea div.storyAssetSingle div.vmixCaptionArea div:last').addClass('vmixDescrip');
	}
	if (vmix_credit) {
		$('div.storyVideoBoxContentArea div.storyAssetSingle div.vmixCaptionArea').append('<div class="vmixCredit">' + vmix_credit + '</div>');
		$('div.storyVideoBoxContentArea div.storyAssetSingle div.vmixCaptionArea div:last').addClass('vmixCredit');
	}
}

/*********************
 * Load the VIDEO OLD TYPE Content (Files) with jQuery .media
 */
function loadVideoOldTypeEmbed(storyAssetVideoFileURL){
// Pass this function an XML feed with the list of images.
	var videoFileDestinationID = "videoFilePlaceHolder";

	if (storyAssetVideoFileURL.charAt(0) == '#') {
	// In case there is a # in front of URL
		storyAssetVideoFileURL = storyAssetVideoFileURL.substring(1);
	}

	if (storyAssetVideoFileURL.indexOf("http") != 0 )  {
	// If the URL does not have the domain name - May need to update this to replace any domain with the media server
		storyAssetVideoFileURL = mediaServerURL + storyAssetVideoFileURL;
	}

	// Create new video file holder - Must hideAll() first to make sure the destination area is empty
		hideAllMedia();
	// Assign ID and class to new video file holder
		alertTest('Video File (Old Type) Area will be created. URL was passed as: ' + storyAssetVideoFileURL);
		$('div.storyVideoOldTypeContentArea').append('<div class="storyAssetSingle"></div>');
		$('div.storyVideoOldTypeContentArea div').addClass('storyAssetSingle');
		$('div.storyVideoOldTypeContentArea div.storyAssetSingle').append('<div id="' + videoFileDestinationID + '"></div>');
		$('div.storyVideoOldTypeContentArea div.storyAssetSingle div').attr('id',videoFileDestinationID);

	// copy link to new video file holder and Assign href to new video file holder link
		var thisVideo = $('div.storyVideoOldTypeContentArea div.storyAssetSingle #' + videoFileDestinationID);
		thisVideo = $(thisVideo).append('<a href="' + storyAssetVideoFileURL + '" class="media_jquery_video">Loading video...</a>');
		thisVideo = $(thisVideo).addClass('media_jquery_video');
		thisVideo = $(thisVideo).attr('href',storyAssetVideoFileURL);

		alertTest('This Video File HREF is: ' + $(thisVideo).attr('href'));

	// Convert new link to media object
	// Scale the height if needed 
		var aryVideoOldTypeSize = [getQueryStrVariable('width',storyAssetVideoFileURL),getQueryStrVariable('height',storyAssetVideoFileURL)]; // W(0) x H(1)
		if ((aryVideoOldTypeSize[0]) && (aryVideoOldTypeSize[1])) {
			var aryVideoOldTypeSizeScaled = ['none','none']; // W(0) x H(1)
			getMediaDisplayAreaScaled(mediaDisplayAreaMaxWidth,mediaDisplayAreaDefaultHeight,aryVideoOldTypeSize,aryVideoOldTypeSizeScaled);
		alertTest('Old Width: ' + aryVideoOldTypeSize[0] + ', New Width: ' + aryVideoOldTypeSizeScaled[0] + '\nOld Height: ' + aryVideoOldTypeSize[1] + ', New Height: ' + aryVideoOldTypeSizeScaled[1]);
		}
		else {
			var aryVideoOldTypeSizeScaled = [mediaDisplayAreaMaxWidth,mediaDisplayAreaDefaultHeight]; // W(field 0) x H(field 1)
		}	
//////////////////////////////////////////////////////////////
// Will need to dynamically sniff URL to determine resulting player's controller height
	if ((storyAssetVideoFileURL.indexOf(".wmv") != -1) && (aryVideoOldTypeSizeScaled[1] > 0))  {
		alertTest('This Video File height is being adjusted for WMV: ' + $(thisVideo).attr('href'));
		aryVideoOldTypeSizeScaled[1] += videoControlsHeightWMV;
	}

//////////////////////////////////////////////////////////////
		$(thisVideo).show(); // Show the link
		$(thisVideo).media({ 
			width: aryVideoOldTypeSizeScaled[0],
			height: aryVideoOldTypeSizeScaled[1],
			autoplay: 1,
			caption:   false
		});

} // END loadVideoOldTypeEmbed()


/*********************
 * Load the AUDIO Files with jQuery .media
 */
function loadAudioEmbed(storyAssetAudioFileURL){
// Pass this function audio file URL
	var audioFileDestinationID = "audioFilePlaceHolder";

	if (storyAssetAudioFileURL.charAt(0) == '#') {
	// In case there is a # in front of URL
		storyAssetAudioFileURL = storyAssetAudioFileURL.substring(1);
	}

	if (storyAssetAudioFileURL.indexOf("http") != 0 )  {
	// If the URL does not have the domain name - May need to update this to replace any domain with the media server
		storyAssetAudioFileURL = mediaServerURL + storyAssetAudioFileURL;
	}

	// Create new audio file holder - Must hideAll() first to make sure the destination area is empty
		hideAllMedia();
	// Assign ID and class to new audio file holder
		alertTest('Audio File Area will be created. URL was passed as: ' + storyAssetAudioFileURL);
		$('div.storyAudioContentArea').append('<div class="storyAssetSingle"></div>');
		$('div.storyAudioContentArea div').addClass('storyAssetSingle');
		$('div.storyAudioContentArea div.storyAssetSingle').append('<div id="' + audioFileDestinationID + '"></div>');
		$('div.storyAudioContentArea div.storyAssetSingle div').attr('id',audioFileDestinationID);

	// copy link to new audio file holder and Assign href to new video file holder link
		var thisAudio = $('div.storyAudioContentArea div.storyAssetSingle #' + audioFileDestinationID);
		thisAudio = $(thisAudio).append('<a href="' + storyAssetAudioFileURL + '" class="media_jquery_audio">Loading audio...</a>');
		thisAudio = $(thisAudio).addClass('media_jquery_audio');
		thisAudio = $(thisAudio).attr('href',storyAssetAudioFileURL);

		alertTest('This Audio File HREF is: ' + $(thisAudio).attr('href'));

	// Convert new link to media object
//////////////////////////////////////////////////////////////
		$(thisAudio).show(); // Show the link
		$(thisAudio).media({ 
			width: audioPlayerMaxWidth,
			height: audioPlayerMaxHeight,
			autoplay: 1,
			caption: false
		});

} // END loadAudioEmbed()


/*********************
 * Use this to parse a query string
 */ 
// function getQueryStrVariable() moved to redesign.js

/*********************
 * MEDIA RESIZER - Maintains Aspect Ratio
 * Use this to determine the correct size / aspect ratio
 * Pass the width and the height in the arrays in that order
 */
function getMediaDisplayAreaScaled(maxwidth,defaultHeight,aryOldSize,aryNewSize) {
	if (isInteger(aryOldSize[0])) {
alertTest('isInteger Passed');
		var thisratio = maxwidth / aryOldSize[0];
		aryNewSize[1] = thisratio * aryOldSize[1]; // New Height
		aryNewSize[0] = maxwidth; // New Width
	}
	else {
// Use the current dimensions
		aryNewSize[0] = maxwidth; // Old Width
		aryNewSize[1] = defaultHeight; // Old Height
	}
}
/*********************
 * Check if the value is an integer
 */
function isInteger(s) {
	if (s) {
		return (s.toString().search(/^-?[0-9]+$/) == 0);
	}
	else {
alertTest('isInteger Failed due to undefined');
		return false;
	}
}
/*********************
 * Text Resizing Functionality
 */
function txtResizeSmaller() {
	var currentTxtSize = $("#storyBodyContent > p").css("font-size");
	var newTxtSize = currentTxtSize.split("px");

	var currentTxtLineHeight = $("#storyBodyContent > p").css("line-height");
	var newTxtLineHeight = currentTxtLineHeight.split("px");

	if( parseInt( newTxtSize[0] ) <= 8 ){
		$("#txtResizeMinus").hide();
		$("#txtResizeMinusFade").show();
	} else {
		currentTxtSize = parseInt( newTxtSize[0] ) - 2;
		currentTxtLineHeight = parseFloat( newTxtLineHeight[0] ) - 2;
		if( parseInt( currentTxtSize ) <= 8 ){
			$("#txtResizeMinus").hide();
			$("#txtResizeMinusFade").show();
		}

		currentTxtSize = currentTxtSize + "px";
		currentTxtLineHeight = currentTxtLineHeight + "px";
	}
	
	$("#txtResizePlus").show();
	$("#txtResizePlusFade").hide();

	$("#storyBodyContent > p").css("font-size", currentTxtSize);
	$("#storyBodyContent > p").css("line-height", currentTxtLineHeight);
//	$("#story_text_remaining > p").css("font-size", currentTxtSize);
//	$("#story_text_remaining > p").css("line-height", currentTxtLineHeight);
}

function txtResizeLarger() {
	var currentTxtSize = $("#storyBodyContent > p").css("font-size");
	var newTxtSize = currentTxtSize.split("px");

	var currentTxtLineHeight = $("#storyBodyContent > p").css("line-height");
	var newTxtLineHeight = currentTxtLineHeight.split("px");

	if( parseInt( newTxtSize[0] ) >= 24 ){
		$("#txtResizePlus").hide();
		$("#txtResizePlusFade").show();
	} else {
		currentTxtSize = parseInt( newTxtSize[0] ) + 2;
		currentTxtLineHeight = parseFloat( newTxtLineHeight[0] ) + 2;
		if( parseInt( currentTxtSize ) >= 24 ){
			$("#txtResizePlus").hide();
			$("#txtResizePlusFade").show();
		}

		currentTxtSize = currentTxtSize + "px";
		currentTxtLineHeight = currentTxtLineHeight + "px";
	}
	
	$("#txtResizeMinus").show();
	$("#txtResizeMinusFade").hide();

	$("#storyBodyContent > p").css("font-size", currentTxtSize);
	$("#storyBodyContent > p").css("line-height", currentTxtLineHeight);
//	$("#story_text_remaining > p").css("font-size", currentTxtSize);
//	$("#story_text_remaining > p").css("line-height", currentTxtLineHeight);
}

/*********************
 * Display link to download flash if the flash media asset player does not load
 */
function checkStoryAssetNoFlashLink(destinationElement){
	$(document).ready(function(){
// If there is n media display asset using flash and it does not display, then show DL link
		if (($(destinationElement).html() == '')) {
//			$('#storyAssetMediaDisplayArea .getFlashPlayer').css('display','block');
		}
	});
}
/*********************
 * Prep the page's storyAssetMediaDisplayArea and Video
 * Make sure to list this in order of importance
 */
function loadStoryAssetMediaDisplayArea() {
/*
 * Use this function to load the story assets media, if needed. 
 * It must be run at document.ready
 * Set them in the order of importance. If certain types are found, the function is aborted, 
 * so do not have anything critical at the end.
 */



/*********************
 * Determine if the jQuery Media player needs to be loaded
 */ 
    if ((storyVideoOldTypeCount > 0) || (storyAudioCount > 0)){
	alertTest2('jQuery Media Player defaults will be loaded');
		$.fn.media.defaults.flvPlayer = mediaServerURL + '/static/media/flvplayer_embedded.swf';
		$.fn.media.defaults.mp3Player = mediaServerURL + '/static/media/mp3player.swf';
		$.fn.media.mapFormat('mp4', 'quicktime');
    }
	else {
		alertTest2('NO JQUERY MEDIA PLAYER NEEDED');
	} 

/*********************
 * Determine if the Video Old Type player needs to be loaded
 * NOTE: DO NOT AUTO LOAD - Since this can be any file type, it can cause problems\
 * if the user does not have the correct plugin
 */ 
    if (storyVideoOldTypeCount > 0){
	alertTest2('VIDEO FILES FOUND: storyVideoOldTypeCount = ' + storyVideoOldTypeCount);
//		return;
    }
	else {
		alertTest2('NO VIDEO FILES FOUND');
	} 
 
/*********************
 * When linked from a section front media link, Determine which media asset to display first
 * 
 * Find the media ID with the matching positional ID and trigger a click
 * 
 * Affected Asset types:
 * 		photo gallery
 * 		video - (html_module) - ?asset_id=0
 * 		audio (audio|mp3|ra) - ?asset_id=2
 */ 
	if ((defaultAssetType) && (defaultAssetType != 'html_module')) {
		displayDefaultAsset();
			// If this is not an audio asset, then exit, else, continue
		if (defaultAssetType != 'audio') {
			return;
		}
    }
	else {
		alertTest2('NO PRESELECTED MEDIA ASSET ID - else html_module found');
	} 


/*********************
 * Determine if the Vmix HTML_MODULE player needs to be loaded
 */ 
// This is handled by displayVideoVmixEmbedLink() to instantiate the video after the link is created
    if (storyVideoCount > 0){
	alertTest2('VMIX html_module FOUND: storyVideoCount = ' + storyVideoCount);
		return;
    }
	else {
		alertTest2('VMIX html_module FOUND');
	} 
 
/*********************
 * Determine if the Video Box (embedded) player needs to be loaded
 */ 
// This is handled by displayVideoVmixEmbedLink() to instantiate the video after the link is created
    if (storyVideoBoxCount > 0){
	alertTest2('VIDEO BOX (vmix) FOUND: storyVideoCount = ' + storyVideoCount);
		return;
    }
	else {
		alertTest2('VIDEO BOX (vmix) FOUND');
	} 
 
/*********************
 * Determine if the Single Attached Photo 
 */ 
    if (storyPhotoCount == 1 ){
		alertTest2('SINGLE PHOTO FOUND: storyPhotoCount = ' + storyPhotoCount);

		$('#storyPhotoLinksArea').css('border-top','none');
		setstoryAssetNowPlaying($('#storyAssetAttachPhotoLink'));
		return;
    }
	else {
		alertTest2('NO PHOTOS FOUND');
	}

/*********************
 * Determine if the Photo gallery player need to be loaded & styled
 */ 
    if ((storyPhotoCount > 0) || (storyPhotoGalleryCount > 0)){
		alertTest2('PHOTO GALLERY FOUND: storyPhotoGalleryCount = ' + storyPhotoGalleryCount);

		// Play the first photo gallery link
		$('#storyAssetMediaDisplayAreaLinks a.storyPhotoGalleryLink:first').trigger('click'); 
		$('#storyPhotoLinksArea').css('border-top','none');
		return;
    }
	else {
		alertTest2('NO PHOTO GALLERY FOUND');
	}

/*********************
 * Determine if the audio specific player CSS needs to be styled
 * Does not need main media area so continue if successful
 */ 
    if (storyAudioCount > 0){
		alertTest2('AUDIO FOUND: storyAudioCount = ' + storyAudioCount);
		$('#storyAudioLinksArea').css('border-top','none');
    }
	else {
		alertTest2('NO AUDIO FOUND');
	}

/*********************
 * Determine if the Google Map / Map Box needs to be loaded
 */ 
    if (storyGoogleMapCount > 0){
	alertTest2('GOOGLE MAP FOUND: storyGoogleMapCount = ' + storyGoogleMapCount);
//		$('#storyNonImageContentArea ul.link_list li.storyAssetSingle a.storyMapLink').trigger('click');
//		return;
    }
	else {
		alertTest2('NO GOOGLE MAP FOUND');
	} 

} // END loadStoryAssetMediaDisplayArea()

/*********************
 * Check the query string to determine which media asset to display first
 *
 * This cannot be called to trigger a click if the link 
 * has not been built yet
 */ 
function displayDefaultAsset() {
	alertTest2("URL Media Asset Position Id (defaultAssetID): " + defaultAssetID + "\nURL Media Asset Type (defaultAssetType): "  + defaultAssetType);

	var defaultAssetID_temp = defaultAssetID;
	// If there is a default asset ID in the URL, get it and the default type
	// If they are missing the prefix, then prepend it
	if (defaultAssetID.indexOf("asset_id_") != 0) {
		defaultAssetID_temp = 'asset_id_' + defaultAssetID;
	}
	if (defaultAssetType.indexOf("asset_type_") != 0) {
		defaultAssetType_temp = 'asset_type_' + defaultAssetType;
	}
	// Trigger a click event on the desired link - Remove % from the string for html_module name/ID (using global switch)
	$('a.' + defaultAssetID_temp.replace(vmix_asset_id_replace, "") + '.' + defaultAssetType_temp).trigger("click");
}

/*********************
 * Scroll to the top of the page
 * 
 * You can pass this fuction a type of media asset for a future use
 */ 
function scrollToTop() {
	window.scrollTo(0,scrollToTopHeight);
}
