
/* Telemundo47.com scripts */
// Begin national js scripts

/****************************************************
 * IBSSequential (DHTML slideshow) coid: 9362226
 * Copyright 2006, Internet Broadcasting Systems, Inc.
 *	Dependencies not included in this object:
 *		function padTags()
 *		function fixString()
 *
 *  USAGE:
 * 	new IBSSequential(
 *			ibIndex['index#######'],	// ibIndex object
 * 			"parentContainerID",		// parent ID
 *			240,						// image width
 *			true,						// autoplay
 *			false);						// use play/pause controls (default == true)
 */
function IBSSequential(dataSource,parentContainer,imageWidth,autoplay,useControls) {
	var self = this; 	//for functions called by event handlers
	this.dataSource = dataSource;	//data source
	this.contentId = dataSource.coid;	//contentID of index
	this.numSlides = this.dataSource.co.length;	//number of slides present in data
	this.slideImages = new Array(); //an array to preload images; makes app feel faster
	this.text = new Object; 	//object to store current text
	this.imageWidth = imageWidth; //width of large image, in pixels
	this.thumbnailWidth = ""; //width of thumbnail image
	this.useControls = (typeof useControls == "undefined") ? true : useControls;	// if false the play/pause buttons wont show up

	/* vars related to image crossfading */
	this.clock = null; 	//timer object for image cross-fade
	this.opacityType = ""; 	//will store flag to fork code for different platforms
	this.resolution = 10; 	//number of "frames" in image crossfade (lower number = faster fading)
	this.count = 0;	//counter / sentinal for crossfade loop

	/* vars related to automatic slide show */
	this.autoplay = autoplay;	//true/false: start playing when page loads
	this.playing = "pageLoad";	//flag to start slideshow
	// this.timerObject = false; 	//timer object for automatic slideshow
	this.timerObject = -1; 	//timer object for automatic slideshow
	// this.slideShowSpeed = "7"; 	//seconds to wait before changing slides
	this.slideShowSpeed = 7;

	/* elements by ID */
	//this.dataSourceContainer = document.getElementById(dataSourceContainer); //id of container the index is dragged to (i.e. alpha, beta, theta, etc)
	this.parentContainer = document.getElementById(parentContainer); //id of the outermost container of the media player
	this.oldSlideImage = document.getElementById("oldSlideImage" + this.contentId); //Big slide image "underneath" new one in opacity change
	this.playLink = document.getElementById("playLink" + this.contentId).parentNode; //container with image - to start auto slide show
	this.pauseLink = document.getElementById("pauseLink" + this.contentId).parentNode; //container with image - to pause auto slide show
	if(!this.useControls)
	{
		this.playLink.style.display = this.pauseLink.style.display = "none";
	}
	this.blurbHeadlineText = document.getElementById("blurbHeadlineText" + this.contentId);
	this.blurbInfoTeaser = document.getElementById("blurbInfoTeaser" + this.contentId);
	this.mainSlide = document.getElementById("mainSlide" + this.contentId);

	/* dependent on elements by ID */
	this.navSlides = this.parentContainer.getElementsByTagName('ul')[0];	//the list of navigation slides (small images on the left side)	.

	/**********
	* "Constructor" - preload images, load first slide without transition effects
	**********/
	this.IBSSequential = function() {
		//preload large images
		this.preloadImages();

		//load first slide text and image
		self.getBlurbText(1);
		this.oldSlideImage.src = this.slideImages[1].src;
		var parentLink =  this.mainSlide.getElementsByTagName("a")[0];
		parentLink.href = this.dataSource.co[0].link;

		this.loadNavSlides();

		//enable play/pause button
		if(self.useControls)
		{
			this.playLink.onclick = function() {
				self.togglePlay();
				return false;
			}
			this.pauseLink.onclick = function() {
				self.togglePlay();
				return false;
			}
		}
		//initiate slideshow
		if(this.autoplay) {
			this.play();
		} else if(self.useControls) {
			this.playLink.style.display = "block";
		}
		this.mainSlide.onmouseover = this.stop;
	}

	/***********
	* Finds data source (ibIndex) based on what container the index is dragged in.
	*	Index must have instance control display type of 'jsObj'
	*	Returns ibIndex[index#######]
	***********/
	this.dataSourceFinder = function() {
		var spans = this.dataSourceContainer.getElementsByTagName('span');
		for(var i=0; i<spans.length; i++) {
			if(spans[i].id.indexOf("index") != -1) {
				return ibIndex[spans[i].id];
			}
		}
	}

	/**********
	* preload images
	**********/
	this.preloadImages = function() {
		for (var i = 1; i<(this.dataSource.co.length + 1); i++) {
			this.slideImages[i] = new Image();
			this.slideImages[i].src = this.getBigImageSource(i);
		}
	}

	/**********
	*load small images into navigation section on left side
	**********/
	this.loadNavSlides = function() {
		for(i=0; i<this.dataSource.co.length; i++) {
			var temp = this.dataSource.co[i].img.imgSrc.split("_");
			var co = this.dataSource.co[i];

			//construct thumbnail URL based on desired size.
			if(this.imageWidth == "240") {
				this.thumbnailWidth = "40";
			} else {
				this.thumbnailWidth = "60";
			}
			var smallImage = temp[0] + "_" + this.thumbnailWidth + "X" + parseInt(this.thumbnailWidth * 0.75) + ".jpg";

			var dimensions = /([0-9]+)X([0-9]+)/.exec(smallImage);

			var aListItem = document.getElementById("li"+(i+1));
			if(!aListItem)
			{
				var insertionPoint = ((document.getElementById("li"+i) &&
						document.getElementById("li"+i).nextSibling) ?
							document.getElementById("li"+i).nextSibling :
							this.navSlides.firstChild);

				// aListItem = this.navSlides.getElementsByTagName("li").item(0).cloneNode(true);
				aListItem = this.navSlides.insertBefore(
					document.createElement("li"),
					insertionPoint);
				aListItem.id = "li"+(i+1);

				var kid = aListItem.appendChild(document.createElement("a"));
				kid.href = co.link;
				kid.id = "s"+(i+1);
				kid.onmouseover = this.manageTransition;

				kid = kid.appendChild(document.createElement("span"));
				kid.id = "i"+(i+1);

				kid = kid.appendChild(document.createElement("img"));
				kid.src = smallImage;
				kid.border = 0;
				if(dimensions != null)
				{
					kid.width = dimensions[1];
					kid.height = dimensions[2];
				}
			}
			else
			{
				var currentNavListItem = this.navSlides.getElementsByTagName('li')[i].getElementsByTagName('img')[0];
				currentNavListItem.src = smallImage;

				//attach event listener to nav slides so we can change content in other areas
				var currentNavListLink = this.navSlides.getElementsByTagName('li')[i].getElementsByTagName('a')[0];
				currentNavListLink.onmouseover = this.manageTransition;
			}

		}
	}
	/**********
	* construct image size based on width
	**********/
	this.buildImageSize = function() {
		this.imageWidth = parseInt(this.imageWidth);
		var height = parseInt(this.imageWidth * 0.75);
		return this.imageWidth + "X" + height;
	}
	/**********
	* builds source of big image based on slide number
	**********/
	this.getBigImageSource = function(slide) {
		var indexNo = slide - 1;
		var temp;
		temp = this.dataSource.co[indexNo].img.imgSrc.split("_");
		return temp[0] + "_" + this.buildImageSize() + ".jpg";
	}

	/**********
	* grabs blurb headline, text, and link based on slide number
	**********/
	this.getBlurbText = function(slide) {
		slide--; //accounts for difference in 0-start and 1-start numbering
		//alert(slide);
		//store text in a new object
		this.text = {
			headline: padTags(fixString(this.dataSource.co[slide].headline)),
			teaser: padTags(fixString(this.dataSource.co[slide].teaser)),
			headlineLink: this.dataSource.co[slide].link,
			target: this.dataSource.co[slide].link_target
		}

		//create / modify headline
		var headlineLink = document.createElement('a');
		var headlineText = this.text.headline;
		//var headlineText = document.createTextNode(this.text.headline);
		headlineLink.href = this.text.headlineLink;
		if(this.text.target == "newwindow") {
			headlineLink.target = "_blank";
		}
		headlineLink.innerHTML = headlineText;
		//headlineLink.appendChild(headlineText);
		var child;
		while(child = this.blurbHeadlineText.firstChild) {
			child.parentNode.removeChild(child);
		}
		this.blurbHeadlineText.appendChild(headlineLink);

		//try inserting text.  If an error happens, strip out html tags and try again.
		try {
			this.blurbInfoTeaser.innerHTML = this.text.teaser;
		} catch(e) {
			var tags = /<\S[^>]*>/g;
			this.blurbInfoTeaser.innerHTML = this.text.teaser.replace(tags,"");
		}
	}

	/**********
	* find out which slide we are currently displaying
	**********/
	this.findCurrentSlideNumber = function(){
		//first, find the id of the first div inside the outermost div.
		var firstInsideDiv = this.parentContainer.firstChild;
		while(firstInsideDiv.nodeType == 3)
			firstInsideDiv = this.parentContainer.firstChild.nextSibling;

		//chop off "active" from the id to get just the number, and spit it out.
		return firstInsideDiv.getAttribute('id').substr(6);
	}

	/***********
	* switch from old to new slide number by simply switching a div id
	***********/
	this.switchSlideElementIds = function(slide) {
		//first, find the id of the first div inside the outermost div.
		var firstInsideDiv = this.parentContainer.firstChild;
		while(firstInsideDiv.nodeType == 3)
			firstInsideDiv = this.parentContainer.firstChild.nextSibling;

		//change id property
		firstInsideDiv.id = "active" + slide;

		// BUG: switching the parent's id causes the active <A> element
		// to not get the correct background color. enumerating the
		// properties of the element fixes it, but its a goofball hack
		var el = document.getElementById("s"+slide);
		if(el != null)
		{
			for(var p in el)
			{
				try
				{
					el[p];
				}
				catch(ex)
				{
				}
			}
		}
		// firstInsideDiv.removeAttribute("id");
		// firstInsideDiv.id = "active"+slide;
	}

	/***********
	* driver for onmouseover transition between slides
	***********/
	this.manageTransition = function() {
		//this function was called by an event handler
		var slide;
		if (this.parentNode) {
			//user fired this function by triggering an event, so let's stop the slideshow
			self.stop();
			//this.parentNode refers to the parent of the object that fired the event
			// var currentLi = this.parentNode;
			// slide = currentLi.id.substr(2);

			// NOTE: hrefs have ID too
			slide = this.id.replace(/s/,"");
		//this function was called by setInterval
		} else  {
			var currentSlide = parseInt(self.findCurrentSlideNumber());
			if (currentSlide >= self.numSlides) {
				slide = 1;
			} else {
				slide = currentSlide + 1;
			}
		}

		//Don't do anything if user mouses over current slide
		if(self.findCurrentSlideNumber() == slide) {
			return true;
		}


		//switch id's for css changes
		self.switchSlideElementIds(slide);

		//load new text
		self.getBlurbText(slide);

		//change image
		self.crossfade(slide);

	}

	/***********
	* crossfade function to gracefully switch between images
	*	parameter 'slide' is the slide number we want to show
	***********/
	this.crossfade = function(slide) {
		if(self.clock != null) {
			//cancel any fading already in progress
			clearInterval(self.clock);
		}

		//determine opacity type needed for transition effect
		if(navigator.userAgent.indexOf("Safari") != -1) {
			self.opacityType = 'w3c';
		} else if(typeof self.slideImages[slide].style.opacity != 'undefined') {
			self.opacityType = 'w3c';
		} else if (typeof self.slideImages[slide].style.MozOpacity != 'undefined') {
			self.opacityType = 'moz';
		} else if (typeof self.slideImages[slide].style.filter != 'undefined') {
			self.opacityType = 'ie';
		} else {
			self.opacityType = null;
		}


		//an array of all images in mainSlide container (they are surrounded by anchor tags)
		var imgTags = self.mainSlide.getElementsByTagName("A");

		//If there is more than one image here, nuke the first one.
		while(imgTags.length > 1) {
			imgTags[0].parentNode.removeChild(imgTags[0]);
		}

		//If this browser supports css image opacity effects...
		if (self.opacityType != null) {
			//If there is one image tag, give it the right id
			if (imgTags.length == 1) {
				var oldImageLink = self.mainSlide.getElementsByTagName("a")[0];
				oldImageLink.id = "oldSlideImageLink";
				oldImage = self.mainSlide.getElementsByTagName("img")[0];
				oldImage.id = "oldSlideImage";
				oldImage.style.zIndex = "1";
			}

			//create link for image
			newImageLink = document.createElement("a");
			newImageLink.href = self.text.headlineLink;
			if(self.text.target == "newwindow") {
				newImageLink.target = "_blank";
			}
			newImageLink.id = "newSlideImageLink";

			//create a new image object to append
			var newImage;
			if(navigator.userAgent.indexOf("Safari") != -1) {
				newImage = document.createElement("img");
				newImage.src = self.slideImages[slide].src;

			} else {
				newImage = self.slideImages[slide];
			}
			newImage.id = "newSlideImage";
			newImage.style.display = "none";
			newImage.style.zIndex = "2";

			//put the new linked image in
			self.mainSlide.appendChild(newImageLink).appendChild(newImage);

			//initialize counter
			self.count = 1;

			//start the timer, crossfade images
			self.clock = setInterval( function() {
				//loop sentinal
				if(self.count < 1/self.resolution) {
					clearInterval(self.clock);
					self.count = 0;
				} else {
					//decrease the sentinal
					self.count = self.count - (1 / self.resolution);
					if(self.count < 0)
						self.count = 0;
					else if(self.count >= 1)
						self.count = 0;
				}

				// NOTE: we want precision only to the tenths place here
				self.count = Math.round(self.count*10) / 10;

				//set new opacity value on both elements
				//using whatever method is supported
				switch(self.opacityType)
				{
					case 'ie' :
						oldImage.style.filter = "alpha(opacity=" +  (self.count * 100) + ");";
						newImage.style.filter = "alpha(opacity=" + ((1 - self.count) * 100) + ");";
						break;

					case 'khtml' :
						oldImage.style.KhtmlOpacity = self.count;
						newImage.style.KhtmlOpacity = (1 - self.count);
						break;

					case 'moz' :
						//restrict max opacity to prevent a visual popping effect in firefox
						oldImage.style.MozOpacity = (self.count == 1 ? 0.9999999 : self.count);
						newImage.style.MozOpacity = (1 - self.count);
						break;

					default :
						//restrict max opacity to prevent a visual popping effect in firefox
						oldImage.style.opacity = (self.count == 1 ? 0.9999999 : self.count);
						newImage.style.opacity = (1 - self.count);
				}
				//show fade-in image
				newImage.style.display = 'block';

			}, 50);

		//opacity is not supported, so just swap images
		} else	{
			//update link
			imgTags[0].href = self.text.headlineLink;

			//update image
			self.oldSlideImage.src = self.slideImages[slide].src;
		}
	}

	/**************
	* Toggle slideshow on / off
	**************/
	this.togglePlay = function() {
		if (!self.playing) {
			self.play();
		} else {
			self.stop();
		}
	}

	/************
	* Slideshow play
	************/
	this.play = function() {
		//advance to next slide only if this is not page load
		if(self.playing != "pageLoad") {
			self.manageTransition();
		}
		self.playing = true;

		//find out where we are (slide number)
		var slide = self.findCurrentSlideNumber();

		//create a timed driver for manageTransition
		self.timerObject = setInterval(self.manageTransition,(self.slideShowSpeed * 1000));

		//swap out play/pause image
		if(self.useControls)
		{
			self.playLink.style.display = "none";
			self.pauseLink.style.display = "block";
		}
	}

	/*************
	* Slideshow stop
	*************/
	this.stop = function() {
		self.playing = false;
		if (self.timerObject) {
			clearInterval(self.timerObject);
			self.timerObject = false;

			//swap out play/pause image
			if(self.useControls)
			{
				self.pauseLink.style.display = "none";
				self.playLink.style.display = "block";
			}
		}
	}

	//
	// NOTE: commented out ddjohnson Jun 9, 2006
	// 		 Use play() or IBSSequential() instead?
	//
	//call "constructor" function
	// if(autoplay)
	// 	this.IBSSequential();
}

/**
 * Create a new instance of IBSSequential with the given properties.
 * call <strong>start</strong> on the returned object to start
 * automatic playback.
 *
 * @param <Array> dataSourceArray
 * @param <String> parentContainer
 * @param <int> imageWidth
 * @param <boolean> autoplay
 * @param <boolean> useControls
 * @return new IBSSequential instance
 */
IBSSequential.newInstance = function(dataSourceArray,parentContainer,imageWidth,autoplay,useControls)
{
	imageWidth = (imageWidth ? imageWidth : 200);
	autoplay = (typeof autoplay != "undefined" ? autoplay : false);
	var seq = new IBSSequential(dataSourceArray,parentContainer,imageWidth,autoplay,useControls);
	seq.start = function()
	{
		seq.IBSSequential();
		// seq.play();
	};
	return seq;
}

/**
 * Returns the index content IDs for a given container
 * @param <String> container ID
 * @return array of content IDs.
 */
IBSSequential.findIndeces = function(container)
{
	var el = document.getElementById(container);
	var nl = el.getElementsByTagName("span");
	var arr = [];
	for(var j=0; j < nl.length; j++)
		if(nl.item(j).id && nl.item(j).id.match(/index[0-9]+/))
			arr.push(nl.item(j).id.replace(/index/,""));
	return arr;
}

/**
 * Returns a <code>dataSource</code> that composed of one or more ibIndex objects.
 * @param <Object> conf: { container, parentElement, width }
 * @return dataSource for use in IBSSequential
 */
IBSSequential.createSource = function(conf)
{
	var arr = IBSSequential.findIndeces(conf.container);

	var mySource = null;
	var coList = [];
	for(var j=0; j < arr.length; j++)
	{
		if(mySource == null)
			mySource = ibIndex["index"+arr[j]];

		for(var ii=0; ii < ibIndex["index"+arr[j]].co.length; ii++)
			coList.push(ibIndex["index"+arr[j]].co[ii]);
		mySource.co = coList;
	}
	return mySource;
}

var mySequence = null;

if(typeof seqconf != "undefined" && /[&\?]nojs/i.exec(window.location.search) == null)
{
	addEvent(window,"load",
		function()
		{
			var mySource = IBSSequential.createSource(seqconf);

			// count how many LI elements have been generated
			// we should have a content object for each one,
			// minus the play/pause items
			var listItemCount = document.getElementById(seqconf.parentElement).getElementsByTagName("li").length;
			var objectLimit = (listItemCount-2 >= 3) ? listItemCount-2 : 3;

			var newLimit = 0;
			var nl = document.getElementById(seqconf.parentElement).getElementsByTagName("li");

			for(var j=0; j < nl.length; j++)
			{
				if(/(play|pause)Li/.exec(nl.item(j).className) == null)
					newLimit++;
			}
			if(newLimit < 3)
				newLimit = 3;

			// Remove extra items from the end
			while(mySource.co.length > newLimit)
			{
				var obj = mySource.co.splice(mySource.co.length-1,1);
			}

			mySequence = IBSSequential.newInstance(
					mySource,						// content
					seqconf.parentElement,			// parent ID
					seqconf.width,					// image width
					true,							// autoplay
					(objectLimit > 3));				// show controls

			mySequence.slideShowSpeed = 7;
			mySequence.start();
		}
	);
}

// 
// 
// End national_js scripts

