if(!showId){
	var showId = 0;
}
if(!showAdId){
	var showAdId = 555555;	
}

// ---------------------------------------------------------//
// RESET THE URL HASH
// ---------------------------------------------------------//

function hashString(key)
{
	var value = null;
	if(hashStringArr[key])
	{
		value=hashStringArr[key];
	}
	return value;
}

hashStringArr = new Array();

function hashString_Parse()
{
	var query = window.location.hash.substring(1);
	var pairs = query.split("&");
	
	for (var i=0;i<pairs.length;i++)
	{
		var pos = pairs[i].indexOf('=');
		if (pos >= 0)
		{
			var argname = pairs[i].substring(0,pos);
			var value = pairs[i].substring(pos+1);
			hashStringArr[argname]=value;
		}
	}

}


// ---------------------------------------------------------//
// GENERAL DATA FLOW INFORMATION
// ---------------------------------------------------------//


// get the gallery location 
if(typeof videoScetId !='undefined'){
	var sectionFolder = videoScetId;
}else{
	var sectionFolder = showId; 
}
// set the gallery location
var xmlLoc = "/assets/xml/video/"+sectionFolder+"/new.xml"; // media data location

/* Get the current query string */
hashString_Parse(); // Start the query string gathering
if(hashString("mea")||hashString("cat")||hashString("sec"))
{
	var urlCat = hashString("cat"); // Get's the value of Category.
	var urlSec = hashString("sec"); // Get's the value of Section.
	var urlMea = hashString("mea"); // Get's the value of Media.
} else {
	QueryString_Parse();
	var urlCat = QueryString("cat"); // Get's the value of Category.
	var urlSec = QueryString("sec"); // Get's the value of Section.
	var urlMea = QueryString("mea"); // Get's the value of Media.
}
/* Set and keep the root url */
var topURL = window.location.href; // get the current url
if(topURL.indexOf("#") > -1){ // check to see if there is a ? with data
	var topURL = topURL.substring(0, topURL.indexOf("#")) //reset the url to the page url only
}

/* check to see if url is direct */
if(urlCat != null || urlMea != null){	
	var newUrl = true; // set the flag to true
}else if(urlCat != null && urlMea != null){
	var newUrl = "dir";
}else{
	var newUrl = false;	 // set the flag to false
}
	


// ---------------------------------------------------------//
// GATHER XML DATA
// ---------------------------------------------------------//

var dsShow = new Spry.Data.XMLDataSet(xmlLoc, "media"); // get all show information
var dsCategory = new Spry.Data.XMLDataSet(xmlLoc, "media/videos"); // get all category information
var dsSection = new Spry.Data.XMLDataSet(xmlLoc, "media/videos[@id = '{dsCategory::@id}']/section"); // get all section information
var dsMedia = new Spry.Data.XMLDataSet(xmlLoc, "media/videos[@id = '{dsCategory::@id}']/section[@id = '{dsSection::@id}']/video"); // get all media information
var dsComments = new Spry.Data.XMLDataSet('', "comments/comment",{useCache:false}); // get all comment information



// ---------------------------------------------------------//
// BEHAVIOR HANDLER
// ---------------------------------------------------------//

var gBehaviorsArray = []; // set the behavior handler for all effects

/* checks and sets the behavior ON/OFF (Run/Cancel) */
function CancelBehavior(id){
  if (gBehaviorsArray[id]){
    gBehaviorsArray[id].cancel();
    gBehaviorsArray[id] = null;
  }
}


// ---------------------------------------------------------//
// IMAGE PRELOADER
// ---------------------------------------------------------//

function preloadImages(arr, callback)
{
	if(typeof arr == "string"){
		arr = [arr];	
	}
	   if (!preloadImages.cached)
	{
		preloadImages.cached = {};
		preloadImages.queue = [];
		preloadImages.loader = new Image;
	}

	if (preloadImages.queue.length > 0)
	{
		// The loader is already running, just append the images
		// to our queue and return.
		preloadImages.queue = preloadImages.queue.concat(arr);
		return;
	}

	// Run through the queue and only fire off an image load
	// for images that aren't already in our cache.

	preloadImages.queue = arr;
	while(preloadImages.queue.length)
	{
		var src = preloadImages.queue[0];
		if (!preloadImages.cached[src])
		{
			// We found an image that isn't in our cache. Set up
			// an onload handler for our image loader, and then
			// fire off a load for the first image in our queue.

			preloadImages.loader.onload = function()
			{
				if (callback)
					callback(preloadImages.queue[0]);

				preloadImages.loader.src = null;
				preloadImages.cached[preloadImages.queue.shift()] = true;
				while(preloadImages.queue.length)
				{
					var path = preloadImages.queue[0];
					if (!preloadImages.cached[path])
					{
						preloadImages.loader.src = path;
						return;
					}
					preloadImages.queue.shift();
				}
				preloadImages.loader.onload = null;
			};
			preloadImages.loader.src = src;
			break;
		}
		preloadImages.queue.shift();
	}
}


// ---------------------------------------------------------//
// SET INITIAL PAGING SETS
// ---------------------------------------------------------//

var mediaPager = new Spry.Data.Pager(dsMedia, { pageSize: 6, divLoc:'mediaListNavDisplay', daPager:'mediaPager'}); //setup the paging object for media
var sectionPager = new Spry.Data.Pager(dsSection, { pageSize: 14, divLoc:'mediaSectionNavDisplay', daPager:'sectionPager'}); //setup the paging object for media
var commentsPager = new Spry.Data.Pager(dsComments, { pageSize: 6, divLoc:'commentListNavDisplay', daPager:'commentsPager', pageHit: true});  // setup the paging object for comments

// ---------------------------------------------------------//
// SETUP FOR INITIAL PAGE LOAD
// ---------------------------------------------------------//

//dsSection.addObserver(function(notType, notifier, data){ Spry.Debug.trace("****** dsSections: " + notType + ": " + (data ? data.newRowID : ""));});

if(newUrl == true){ // checks to see if there is a new url
	
	if(urlMea){
		dsMedia.addObserver({ onPostLoad: function(ds, type)
		{
			dsMedia.removeObserver(this); // remove this observer			
			dsCategory.findRowsWithColumnValues({"@id": "new"}, true, true); // search for the requested video	
				
			dsMedia.addObserver({ onPostLoad: function(ds, type)
			{
				dsMedia.removeObserver(this); // remove this observer				
				var rowMea = dsMedia.findRowsWithColumnValues({"@id": urlMea}, true, true); // search for the requested video	
		
				if (rowMea){// If we have a matching row, make it the current row for the data set.							
					dsMedia.setCurrentRow(rowMea.ds_RowID); //set the current media		
					mediaPager.goToPageContainingRowNumber(dsMedia.getCurrentRow().ds_RowID) // go to the page containing the video clip
					cueDaVid = rowMea['@id']; // Write in the Video Cue
					cuedVideo = dsMedia.getCurrentRow(); // holder for all of the video's information
					launchClip(rowMea['@id']);	
					
				}else{	
					dsMedia.setCurrentRowNumber(0);
					launchClip();
				}
				}	
			});		
				
		}	
		});	
	
	}
	if(urlCat){
		dsCategory.addObserver({ onPostLoad: function(ds, type)
		{
			dsCategory.removeObserver(this); // remove this observer			
			var rowCat = dsCategory.findRowsWithColumnValues({"@id": urlCat}, true, true); // search for the requested category
			
			if (rowCat){// If we have a matching row, make it the current row for the data set.					
				dsCategory.setCurrentRow(rowCat.ds_RowID);	
				
				gBehaviorsArray["mainList"] = 	Spry.Effect.AppearFade(mediaGuide.id, {duration:400,from:0,to:100});	
				
				dsMedia.addObserver({ onPostLoad: function(ds, type)
				{
					dsMedia.removeObserver(this); // remove this observer				
					cueDaVid = dsMedia.getCurrentRow()['@id']; // Write in the Video Cue
					cuedVideo = dsMedia.getCurrentRow(); // holder for all of the video's information
					launchClip(dsMedia.getCurrentRow()['@id']);							
					
					}	
				});					
			}else{	
				dsMedia.addObserver({ onPostLoad: function(ds, type)
				{
					dsMedia.removeObserver(this); // remove this observer				
					cueDaVid = dsMedia.getCurrentRow()['@id']; // Write in the Video Cue
					cuedVideo = dsMedia.getCurrentRow(); // holder for all of the video's information
					launchClip(dsMedia.getCurrentRow()['@id']);							
					
					}	
				});
				
			}				
		}	
		});	
		
	}
	

}

if(newUrl == false){
	dsMedia.addObserver({ onPostLoad: function(ds, type)
		{
			dsMedia.removeObserver(this); // remove this observer	
			showInfo('description'); // show the video information					
			
			var newMedia = dsMedia.getCurrentRow(); //get the current media
			cueDaVid = newMedia['@id']; // Write in the Video Cue			
			dispMedia('', dsCategory.getCurrentRow().ds_RowID); // show list containing the current media
			
			setRatings(); // set the ratings
			loadComments(); // load the comments
			
			setPermalink('media');// set permalink
			window.setTimeout("embed("+newMedia['@id']+")", 1000); // launch the video
		}	
	});
	
}

if(newUrl == "dir"){ // checks to see if there is a new url
	
	/* Categories */
	dsCategory.addObserver({ onPostLoad: function(ds, type)
		{
			dsCategory.removeObserver(this); //remove this observer
			var rowCat = dsCategory.findRowsWithColumnValues({"@id": urlCat}, true, true); // search for the requested section
			
			
			if (rowCat){// If we have a matching row, make it the current row for the data set.
				dsCategory.setCurrentRow(rowCat.ds_RowID); // Set the current row				
			//	try { alert("category data = "+dsCategory.getCurrentRow().toSource()); } catch(e) { alert("category ERROR: " + e); }
			}else{
				dsCategory.setCurrentRowNumber(0); 	
			}		
			
			/* Section */
			dsSection.addObserver({ onPostLoad: function(ds, type)
				{
					dsSection.removeObserver(this); //remove this observer
					
					/* Media */
					dsMedia.addObserver({ onPostLoad: function(ds, type)
						{
							dsMedia.removeObserver(this); // remove this observer							
							var rowSec = dsSection.findRowsWithColumnValues({"@id": urlSec}, true, true); // search for the requested section	
							
							if (rowSec){// If we have a matching row, make it the current row for the data set.
								try {dsSection.setCurrentRow(rowSec.ds_RowID);}catch(e){alert('set current section row error: '+e)} // Set the current row							
							}else{
								dsSection.setCurrentRowNumber(0);
							}
							
							dsMedia.addObserver({ onPostLoad: function(ds, type)
							{
								dsMedia.removeObserver(this); // remove this observer
								var rowMea = dsMedia.findRowsWithColumnValues({"@id": urlMea}, true, true); // search for the requested video	
						
								if (rowMea){// If we have a matching row, make it the current row for the data set.							
									dsMedia.setCurrentRow(rowMea.ds_RowID); //set the current media		
									cueDaVid = rowMea['@id']; // Write in the Video Cue
									launchClip(rowMea['@id']);											
								}else{	
									dsMedia.setCurrentRowNumber(0);
									launchClip();
								}
								}	
							});
						
							
						}	
					});
					
					
				}
			});
			
			
		
		}
	});
	

}
/* launch the clip */
function launchClip(pass){
	Spry.Data.updateRegion('mediaInfo'); // update the media region data	

	dispMediaClips('', dsSection.getCurrentRow().ds_RowID); // show list containing the current media
				
	showInfo('description'); // show the video information				
	setPermalink('media');// set permalink
	setRatings(); // set the ratings
	loadComments(); // load the comments
	window.setTimeout('embed("'+pass+'")', 2000); // launch the video
	cueDaVid=pass;
}	


// ---------------------------------------------------------//
// SECTION CHECKER
// ---------------------------------------------------------//

function checkSec(){
	var checkIt = dsSection.getData().length;

	if(checkIt >1){
		return true;
	}else{
		return false;	
	}	
}

var showSecObserver = { onPreLoad: function(ds, type)
	{
		showSec = checkSec();
		
	}
};

dsMedia.addObserver(showSecObserver);
	
	

// ---------------------------------------------------------//
// NAVIGATION FOR DISPLAYING THE MEDIA
// ---------------------------------------------------------//

var clipCrumb;
function dispMedia(navSec, row){
	
	CancelBehavior("mainList"); // cancel the effect behavior
	
	var mediaRgn = Spry.Data.getRegion('mediaInfo'); // Get a handle to the media region
	mediaRgn.locked = true; // Lock the media region
		
	/* FADE - GET DATA- APPEAR*/
	gBehaviorsArray["mainList"] = Spry.Effect.AppearFade(mediaGuide.id, {duration:300,from:100,to:0,toggle:false, finish:function()
		{
			
		dsCategory.setCurrentRow(row); // get and load the data
		clipCrumb = false;
		
		if(dsCategory.getCurrentRow()['@url']){ // Checks to see if this is a link to somewhere else...
			window.location = dsCategory.getCurrentRow()['@url']; // send the user to the new location
		}
		
		mediaPager.goToPage(1); // set the paging for the media
		
		setHash("cat="+dsCategory.getCurrentRow()['@id']); // set the permalink
		
		try{sectionPager.goToPage(1);}catch (e){/* Do nothing if there is an error */}; // set the paging for the section
		
		gBehaviorsArray["mainList"] = 	Spry.Effect.AppearFade(mediaGuide.id, {duration:400,from:0,to:100,toggle:false, finish:function(){
			mediaGuide.style.filter=''; // to stop IE from showing blocked text		
			try{sectionPager.goToPage(1);}catch (e){/* Do nothing if there is an error */}; // set the paging for the section
			}
		});		
			
		}
	});
		
	/* preload Images */
	var path = '';
	var newImg = dsMedia.getData(true);		
	for(i=0; i<newImg.length; i++){
		path = "http://video.nbc.com/"+newImg[i]["@image"];
		preloadImages(path);
	}
	
	
}

function dispMediaClips(navSec, row){
	
	dsMedia.removeObserver(showSecObserver); // remove the section observer
	showSec = false; // Hide the section
	clipCrumb = true; // show the section in the bread crumb
	CancelBehavior("mainList"); // cancel the effect behavior
	
	var mediaRgn = Spry.Data.getRegion('mediaInfo'); // Get a handle to the media region
	mediaRgn.locked = true; // Lock the media region
		
	/* FADE - GET DATA- APPEAR*/
	gBehaviorsArray["mainList"] = Spry.Effect.AppearFade(mediaGuide.id, {duration:300,from:100,to:0,toggle:false, finish:function()
		{
			
		dsSection.setCurrentRow(row); // get and load the data
		
		
		gBehaviorsArray["mainList"] = 	Spry.Effect.AppearFade(mediaGuide.id, {duration:400,from:0,to:100,toggle:false, finish:function(){			
			mediaPager.goToPageContainingRowNumber(dsMedia.getCurrentRow().ds_RowID) // go to the page containing the video clip
			dsMedia.addObserver(showSecObserver); // reload the section observer
			
			}
		});		
			
		}
	});	
}




// ---------------------------------------------------------//
// MEDIA DATASET OBSERVER
// ---------------------------------------------------------//

function mediaWatcher(region, regionDiv){
	
	myMediaWatcher = new Object;
	myMediaWatcher.onPostUpdate = function(notifier, data)
	{		
		try {mediaPager.showPages()} catch (e) { /* ignore */ }; // set the paging the media
		try {sectionPager.showPages()} catch (e) { /* ignore */ }
				
	};
	
	Spry.Data.Region.addObserver(regionDiv, myMediaWatcher); // Call addObserver() to register the object as an observer.
	
} 








// ---------------------------------------------------------//
// COMMENTS DATASET OBSERVER
// ---------------------------------------------------------//

function commentWatcher(region, regionDiv){
		
	myCommentWatcher = new Object;
	myCommentWatcher.onPostUpdate = function(notifier, data)
	{
		commentsPager.showPages(); // set the paging for the comments	
		
	};
	
	Spry.Data.Region.addObserver(regionDiv, myCommentWatcher); // Call addObserver() to register the object as an observer.
	
} 
 
// ---------------------------------------------------------//
// SHOW VIDEO CLIP INFORMATION //
// ---------------------------------------------------------//
var lastAnc;
var cueDaVid;
var cuedVideo;
var cueInfo;
var cueVid;

function showVideo(cInfo, vid, daVid){
	cueDaVid=daVid;
	cueInfo=cInfo;
	cueVid=vid;
	
	var isPlaying = embeddedPlayerManager.getPlayer().isPlayingAd; // check to see if the ad is playing
	
	if(isPlaying == true){		
		alert("Your selected clip will begin after a word from our sponsor.");
		checkVideo();		
	}else{
		Spry.Data.updateRegion('mediaGuide'); 
		/* Highlight Selected Video */
		if(lastAnc){
			lastAnc.className=lastAnc.className.replace(" mediaAssets_selected", "");
			cInfo.className +=" mediaAssets_selected";			
			mediaOn(cInfo, 'on');		
			mediaOn(lastAnc, 'off');
			lastAnc = cInfo;						
		}else{
			cInfo.className +=" mediaAssets_selected";
			mediaOn(cInfo, 'on');
			lastAnc = cInfo;
			
		}
		dsMedia.setCurrentRow(vid);	// set the current media clip	
		cuedVideo = dsMedia.getCurrentRow();
		Spry.Data.updateRegion('mediaInfo'); // update the media region data
		
		
		try{embeddedPlayerManager.getPlayer().playVideo(daVid);}catch(e){alert('play video error: '+e)} // start the video player
			
		loadComments(); // set the comments
		setRatings(); // set the ratings
		setPermalink('media');// set permalink
		showInfo('description'); // display the media information
		
		try{
			if(dsMedia.getCurrentRow()['@adKeyword'] != "off"){
				//embeddedPlayerManager.getPlayer().setAdOverrides(null, null, dsMedia.getCurrentRow()['@adKeyword'], null, null, null)
			}
		}catch(e){/*ignore*/}	
	}
}


/* Checks for video cue */
function checkVideo(stopCheck){
	var isPlaying = embeddedPlayerManager.getPlayer().isPlayingAd;
	if(stopCheck == false){
		showVideo(cueInfo, cueVid, cueDaVid); // start the video player
	}else{
		window.setTimeout("checkVideo("+isPlaying+")", 500);	
	}
}

/* Class Switcher for the selected video */
function mediaOn(cInfo, action){	
	if(action == 'on'){		
		for (i=0; i<cInfo.childNodes.length; i++) {
			if (cInfo.childNodes[i].nodeName=="A"){			
				cInfo.childNodes[i].className +=" media_selected";
			}
		}
	}
	if(action =='off'){
		for (i=0; i<cInfo.childNodes.length; i++) {
			if (cInfo.childNodes[i].nodeName=="A"){
				cInfo.childNodes[i].className=cInfo.childNodes[i].className.replace(" media_selected", "");					
			}
		}
	}
}


/* Banner Refresher */
var bannerCheck = 0;  // set the initial variable for counting
function bannerRefresh(){
	if(bannerCheck != 0){
		var ban = document.getElementById('ad728x90');
		ban.src = ban.src;		
	}
	bannerCheck++;	
}


// ---------------------------------------------------------//
// VIDEO PLAYER LAUNCHER 
// ---------------------------------------------------------//

function embed(){	
	if (typeof(videoplayerDivName) != 'undefined') {videoplayerDiv=videoplayerDivName;} else {videoplayerDiv="videoplayer";}
	if (typeof(companionDivName) != 'undefined') {companionDiv=companionDivName;} else {companionDiv="scetAd_300";}
	if (typeof(videoID) != 'undefined') {videoId=videoID;} else {videoId=cueDaVid;}
	if (typeof(playerWidth) != 'undefined') {plWidth=playerWidth;} else {plWidth=null;}
	if (typeof(playerHeight) != 'undefined') {plHeight=playerHeight;} else {plHeight=null;}
	if (typeof(playerConfig) != 'undefined') {plConfig=playerConfig;} else {plConfig="xml/config/config_nbc_3_300.xml";}
	if (typeof(playerControls) != 'undefined') {plControls=playerControls;} else {plControls="controls/controls_nbc_gray.swf";}
	if (typeof(playerAutoStart) != 'undefined') {plAutoStart=playerAutoStart;} else {plAutoStart=true;}
	if (typeof(playerVolume) != 'undefined') {plVolume=playerVolume;} else {plVolume=null;}
	if (typeof(adEmbedValue) != 'undefined') {adEmbedVal=adEmbedValue;} else {adEmbedVal=null;}
	if (typeof(adDartRandNumber) != 'undefined') {adDartRandNum=adDartRandNumber;} else {adDartRandNum=randDARTNumber;}
	if (typeof(adKeyword1) != 'undefined') {adKey1=adKeyword1;} else {adKey1=null;}
	if (typeof(adKeyword2) != 'undefined') {adKey2=adKeyword2;} else {adKey2=null;}
	if (typeof(adKeyword3) != 'undefined') {adKey3=adKeyword3;} else {adKey3=null;}
	if (typeof(adClipID) != 'undefined') {adClip=adClipID;} else {adClip=null;}
	try{
		if(adVideoKeyword){
			embeddedPlayerManager.getPlayer().setAdOverrides(adVideoKeyword);
		}
	}catch(e){/*ignore*/}
	try{		
		embeddedPlayerManager.setBaseLocation("http://video.nbc.com/embed/player_2-1/");
		embeddedPlayerManager.embedPlayer(videoplayerDiv, companionDiv,	videoId, plWidth, plHeight, plConfig, plControls, plAutoStart, plVolume, true, adEmbedVal, adDartRandNum, adKey1, adKey2, adKey3, adClip);		
		embeddedPlayerManager.getPlayer().setRunOnBegin('bannerRefresh()');	
		embeddedPlayerManager.getPlayer().setRunOnBegin('keywordFunc(cuedVideo, embeddedPlayerManager.getPlayer().currentClip.adPlaylist)')
		embeddedPlayerManager.getPlayer().setRunOnClipStart('keywordFuncLoomia(cuedVideo, embeddedPlayerManager.getPlayer().currentClip.adPlaylist)')
		embeddedPlayerManager.getPlayer().metadataContainers.setTitle('metadataTitle');
		embeddedPlayerManager.getPlayer().metadataContainers.setShortDescription('metadataDescription');
		embeddedPlayerManager.getPlayer().metadataContainers.setContainers();
		try{mediaPager.goToPageContainingRowNumber(dsMedia.getCurrentRow().ds_RowID)}catch(e){/* ignore */} // go to the page containing the video clip
	}catch(e){alert('embed error: '+e)}
		
}




// ---------------------------------------------------------//
// SET RATINGS //
// ---------------------------------------------------------//

function setRatings(){
	 rated=0;
	 preSet = '';
	 var rateData = dsMedia.getCurrentRow(); // get the current media information
	 var rating = rateData['@rating']; // set the rating of the clip
	 var totalRated = rateData['@totalRated'];
	 var rate=''; // set the default rate
	 for(i=0; i<rating; i++){ // setup the current rating display
		 rate += "<span class='rateImageOn'><\/span>";
	 }	 
	 document.getElementById('descRating').innerHTML=rate; // write current rating to the page
	 document.getElementById('actRating').innerHTML=rate; // write the current rating to the page
}


// ---------------------------------------------------------//
// SET PERMALINK INFORMATION //
// ---------------------------------------------------------//
var permalinking;
function setPermalink(location){
	
	if(location == 'media'){
		var curMeaRow = dsMedia.getCurrentRow() ; // get the current row information
		permalinking = "mea="+curMeaRow['@id']; // setup the permalink
	}
	if(location == 'category'){
		var curCatRow = dsCategory.getCurrentRow(); // get the current category information
		permalinking = "cat="+curCatRow['@id']; // setup the permalink
	}
		
	document.permalinkage.permalinkMe.value = topURL+"#"+permalinking; // put the permalink in the field
	document.send2friendSection.url.value = topURL+"#"+permalinking; // put the permalink in the field	
	setHash(permalinking) // set the url
}

function setHash(loc){
	document.location.hash= loc; // set the new url
	var newTitle = dsMedia.getCurrentRow(); //get the current media title
	var newSite = dsShow.getCurrentRow(); //get the current media title
	document.title = newSite['@site']+": "+newTitle['title']; // reset the HTML title bar	
	hashString_Parse(); // reset the parse...		
}

// ---------------------------------------------------------//
// MEDIA INFORMATION TOGGLE //
// ---------------------------------------------------------//
var postSec;
var bgSec;
function showInfo(section){
	
	newSec = document.getElementById(section+"Section");
	
	if(postSec){
		bgSec.style.borderColor = '';
		
		gBehaviorsArray["mainList"] =  Spry.Effect.AppearFade(postSec.id, {duration:100,from:100,to:0, finish:function(){
			postSec.style.display="none";
			newSec.style.display="block";
			postSec = document.getElementById(section+"Section");			
			showInfoFadeAppear(newSec)																																										
			}
		
		});
	}else{
		newSec.style.display="block";
		newSec.style.filter="";
		showInfoFadeAppear(newSec);		
		postSec = document.getElementById(section+"Section");
	}
		
	document.getElementById(section).style.borderColor="#000";
	bgSec = document.getElementById(section);
}

function showInfoFadeAppear(newSec){
	
	gBehaviorsArray["mainList"] = Spry.Effect.AppearFade(newSec.id, {duration:100,from:0,to:100, finish:function(){
		
		newSec.style.filter="";
		}
	});	
}



// ---------------------------------------------------------//
// SEND TO FRIEND SECTION //
// ---------------------------------------------------------//
function send2Friend(){
	
	var email = escape(document.send2friendSection.email.value); // get the senders email
	var friendemail = escape(document.send2friendSection.friendemail.value); // get the friends email
	var subject = escape(document.send2friendSection.subject.value); // get the subject
	var message = escape(document.send2friendSection.message.value); // get the message
	var url = escape(document.send2friendSection.url.value); // get the url
	var mediaName = escape(document.send2friendSection.mediaName.value); // get the media name
	var mediaDesc = escape(document.send2friendSection.mediaDesc.value); // get the media name
	
	if(validateFriend() == true){// see if the form is valid
	Spry.Utils.loadURL("GET", "/app/form_mail/send2friend.scet.php?email="+email+"&friendemail="+friendemail+"&subject="+subject+"&message="+message+"&url="+url+"&mediaName="+mediaName+"&mediaDesc="+mediaDesc, false, confirmIt); //send to the friend
	}
	
}

function confirmIt(req){ // confirm the request information
	var text = req.xhRequest.responseText; // get the response text
	alert('This video has been sent to your friend!');	// display the alert
	document.send2friendSection.friendemail.value = ''; // reset the friends email
}

function validateFriend(){ // validation
	if (!validate_email(document.send2friendSection.email.value))
	{
		alert("Please enter a valid e-mail address for yourself.");
		document.send2friendSection.email.focus();
		return false;
	}
	
	if (!validate_email(document.send2friendSection.friendemail.value))
	{
		alert("Please enter a valid friend's e-mail address.");
		document.send2friendSection.friendemail.focus();
		return false;
	}
	
	return true;
}

function validate_email(value)	{
		
	var good = /^([\w\d\.\-_]+)@([\w\d\.\-]+)$/i;
	var evil =  /[^a-z0-9\@_\-\.]+/i;
		
	if (good.test(value) && !evil.test(value)) {
		return true;
	} else {
		return false;
	}
}

// ---------------------------------------------------------//
// LOAD COMMENTS
// ---------------------------------------------------------//

function loadComments(req){
	
	if(req){
		text = req.xhRequest.responseText;	
		
		if(text){
			document.comment_form.name.value = '';
			document.comment_form.comment.value = '';
			commentsPager.goToPage(1);
		}
	}
	var medId = dsMedia.getCurrentRow(); // get the current media clip information	
	commentsURL = getCommentsLocation('video', showId, medId['@id']); // get the comments url
	
	Spry.Utils.loadURL("GET", commentsURL+"?"+(Math.round((Math.random() * 10000) + 1)) , true, function(req){ // go get the comments
										 
		resp = req.xhRequest.responseText;	
		if(resp !=' '){ // check for a response			
			dsComments.setURL(commentsURL); // set the url
			dsComments.loadData(); // load in the new comments			
			mediaComments.style.visibility="visible"; // show the comments
			document.getElementById('cPreview').innerHTML ='';					
		}else{
			getCommentsInitLocation(); // create comment file
			mediaComments.innerHTML = "<p id='noneYet'>No Comments Yet.<\/p>";
		}
		
	}, {errorCallback:function(){ // check for an error			
			getCommentsInitLocation(); // create comment file
			mediaComments.innerHTML = "<p id='noneYet'>No Comments Yet.<\/p>";
		}
	}); 	
}
 
// ---------------------------------------------------------//
// COMMENT POSTING 
// ---------------------------------------------------------//

function postMyComment(){

	var err='';
	var cg = document.comment_form.cg.value; // get the senders email
	var type = document.comment_form.type.value; // get the friends email
	var order = document.comment_form.order.value; // get the subject
	var max_per_page = document.comment_form.max_per_page.value; // get the message
	var name = document.comment_form.name.value; // get the url
	var comment = document.comment_form.comment.value; // get the media name
	var synch = false;
	
	if(validateComment() == true){// validte the form
	Spry.Utils.loadURL("GET", "/app/comments/post_ajax.php?cg="+cg+"&type="+type+"&order="+order+"&max_per_page="+max_per_page+"&name="+name+"&comment="+comment, synch, loadComments); //send to the friend
	}	
		
}

// ---------------------------------------------------------//
// LOOMIA TRACKING
// ---------------------------------------------------------//

function keywordFuncLoomia(keyData, metaData)
{
	L_VARS.guid = keyData['@id']+'VIDEO';
	arrival_ts=(new Date()).getTime();
	action_ts=(new Date()).getTime();

	url='http://assets.loomia.com/jsapi?methodName=addClickstream&onload=1&publisher_key=1552314287&guid='+L_VARS.guid+'&action_ts='+action_ts+'&arrival_ts='+arrival_ts;
	_pingserver(url);
}
/* Generate the timestamps */


/* This is the function that pings the server with the url */
function _pingserver(url)
{
	var img=new Image(1,1);
	img.onload = function () { };
	img.onerror = function () { };
	img.src = url;
}
var _loomia_scripts_loaded=0;
if (typeof L_VARS=='undefined') { L_VARS = new Object() }

// Loomia common settings
L_VARS.publisher_key = '1552314287';
L_VARS.anchor = "recommendations_display";

function _loomia_addScript(url,script_anchor) {
	var anchor=document.getElementById(script_anchor);
	var script= document.createElement("SCRIPT");
	script.src=url;
	//anchor.appendChild(script);
}
function _loomia_addCS() {
	try {_loomia_rec_type = document.getElementById(L_VARS.anchor).className; }
	catch(e) { _loomia_rec_type='' }

	if (!_loomia_scripts_loaded) {
	_loomia_addScript("http://assets.loomia.com/js/clixdom.js", "_loomia_cs_anchor");
	if (_loomia_rec_type.indexOf('socialrecs') != -1)
	_loomia_addScript("http://assets.loomia.com/js/socialrecs.js", "_loomia_script_anchor");
	else if (_loomia_rec_type.indexOf('similarrecs') != -1)
	_loomia_addScript("http://assets.loomia.com/js/simitems.js", "_loomia_script_anchor");
	else if (_loomia_rec_type.indexOf('personalrecs') != -1)
_loomia_addScript("http://assets.loomia.com/js/personalrecs.js", "_loomia_script_anchor");
	else if (_loomia_rec_type.indexOf('checkoutrecs') != -1)
_loomia_addScript("http://assets.loomia.com/js/checkoutrecs.js", "_loomia_script_anchor");
	}
	_loomia_scripts_loaded=1;
}

// Loads Loomia script after page has loaded
if (window.addEventListener) {
	window.addEventListener("DOMContentLoaded", _loomia_addCS, false);
	window.addEventListener("load", _loomia_addCS, false);
} else if (window.attachEvent) window.attachEvent("onload", _loomia_addCS);
