$(function() {
	initMediaCarosel();
});

function initMediaCarosel() {
  var animRefs = {};
  
	$(".carousel-holder").each(function() {
		/*** Parent container with overflow hidden ***/
  	var container = this;
	
		/*** The ID for the carousel ***/
		container.carouselID = $(container).attr("id");
	
		/*** The controls holder to target during animation ***/
		container.$controls = $("#"+container.carouselID+"-nav");
		
		/*** The container holding the media items ***/
		container.$carouselMediaHold = $(container).find(".carousel-content");
		
		/*** The container holding the info bar ***/
		container.$carouselInfoHold = $(container).find(".carousel-info-hold");
	
		/*** The actual carousel content holder ***/
		container.$carousel = container.$carouselMediaHold.find('ul.carousel-content-list');
	
		/*** The items in the carousel to transition between ***/
		container.$mediaItems = container.$carousel.find('li');
	
		/*** Get an entry to calculate dimensions ***/
		container.$singleEntry = container.$mediaItems.filter(':first');
	
		/*** How wide each media entry is (with the border) ***/
		container.mediaEntryWidth = container.$singleEntry.outerWidth();
	
		/*** How many are visible at any given time ***/
		container.numberVisible = Math.ceil((container.$carouselMediaHold.innerWidth() / container.mediaEntryWidth));
	
		/*** How many slides do we have to transition? ***/
		container.slideCount = Math.ceil(container.$mediaItems.length / container.numberVisible);
	
		/*** Start by showing the first slide ***/
		container.currentSlide = 1;
	
		/*** Variable to hold slideAnimation call ***/
		container.slideAnimation;
	
		/*** Variable to hold gotoSlide call ***/
		container.gotoSlide;
	
		/*** The timeout holder ***/
		container.animationDelay;

    /*** The left arrow ***/
		container.leftArrow = $('#home-carousel-arrow-l');	

    /*** The right arrow ***/
		container.rightArrow = $('#home-carousel-arrow-r');
		
		container.checkRealPos = function(isStart) {
			isStart = (typeof(isStart) == 'undefined')?false:true;
			 
			var caroStartPos = container.$carousel.position();
			var realPos = caroStartPos.left;
			var expectedPos = Math.abs((-1 * container.currentSlide * container.mediaEntryWidth));

			if(realPos != (-1 * expectedPos)) {
				if(realPos != 0) {
					if(isStart) {
						realPos = realPos - container.mediaEntryWidth;
					}
					container.currentSlide = Math.round((Math.abs(realPos) / container.mediaEntryWidth));
				} else {
					if(isStart) {
						container.currentSlide = 1;
					} else {
						container.currentSlide = 0;
					}
				}
			}
		}
	
		/*** We need to duplicate the content of the first and last slide content to make it seamless ***/
		container.$mediaItems.filter(':first').before(container.$mediaItems.slice(-container.numberVisible).clone().each(function() {
		  var firstMediaItem = this;
		  
			firstMediaItem.origID = $(firstMediaItem).attr("id");
			firstMediaItem.numericID = firstMediaItem.origID.substring((firstMediaItem.origID.lastIndexOf("-") + 1), firstMediaItem.origID.length);
			firstMediaItem.newID = container.carouselID+'-clone-entry-'+firstMediaItem.numericID;
			firstMediaItem.newLinkID = container.carouselID+'-carousel-clone-entry-link-'+firstMediaItem.numericID;
		
			$(firstMediaItem).find('a.linkover')
				.attr('id', firstMediaItem.newLinkID);
		
			$(firstMediaItem)
				.attr('id', firstMediaItem.newID)
				.addClass('cloned');
		}));
		container.$mediaItems.filter(':last').after(container.$mediaItems.slice(0, container.numberVisible).clone().each(function() {
		  var lastMediaItem = this;
		  
			lastMediaItem.origID = $(lastMediaItem).attr("id");
			lastMediaItem.numericID = lastMediaItem.origID.substring((lastMediaItem.origID.lastIndexOf("-") + 1), lastMediaItem.origID.length);
			lastMediaItem.newID = container.carouselID+'-clone-entry-'+lastMediaItem.numericID;
			lastMediaItem.newLinkID = container.carouselID+'-carousel-clone-entry-link-'+lastMediaItem.numericID;
		
			$(lastMediaItem).find('a.linkover')
				.attr('id', lastMediaItem.newLinkID);
			
			$(lastMediaItem)
				.attr('id', lastMediaItem.newID)
				.addClass('cloned');
		}));
	
		/*** Refresh the $mediaItems list ***/
		container.$mediaItems = container.$carousel.find('li');
	
		/*** Calculate the new width of the carousel content holder ***/
		container.newWidth = container.$mediaItems.length * container.mediaEntryWidth;
	
		container.checkRealPos(true);
	
		/*** Set new properties for the carousel content holder ***/
		container.$carousel.css('width', container.newWidth);
		container.$carousel.css('left', (-1 * container.currentSlide * container.mediaEntryWidth));
		container.$controls.find("#"+container.carouselID+"-link-"+container.currentSlide).addClass("selected");
		container.$mediaItems.find("#"+container.carouselID+"-entry-"+container.currentSlide).addClass("selected");
	
		if(container.slideCount < 2) return;
	
		container.gotoSlide = function(slideNo,navClick) {
      $('#home-carousel-video-holder').html('').hide();
      $('#home-carousel img').show();
      //find('iframe').remove();
			navClick = (typeof(navClick) == 'undefined')?false:true;
		
			/*** Get where we currently think we are ***/
			var originalPos = container.currentSlide;
		
			/*** Check where we REALLY are ***/
			container.checkRealPos();
		
			/*** If they are not equivalent correct values ***/
			if(originalPos != container.currentSlide) {
				container.$carousel.css('left', (-1 * container.currentSlide * container.mediaEntryWidth));
			
				if(!navClick) {
					if(container.currentSlide >= container.slideCount) {
						slideNo = 2;
					} else {
						slideNo = container.currentSlide + 1;
					}
				}
			}
		
			/*** Used for setting "selected" class ***/
			var actualSlide;
		
			if(slideNo > container.slideCount) {
				actualSlide = 1;
			} else if(slideNo < 1) {
				actualSlide = container.slideCount;
			} else {
				actualSlide = slideNo;
			}
		
			/*** Determine the direction of the transition ***/
			var direction = slideNo < container.currentSlide ? -1 : 1;
		
			/*** Get the required slide shift ***/
			var slideShift = Math.abs(container.currentSlide - slideNo);
		
			/*** How much in pixels we are shifting ***/
			var leftShift = direction * container.mediaEntryWidth * container.numberVisible * slideShift;
		
			/*** Remove any that are previously set as selected ***/
			container.$controls.find("li.selected").removeClass("selected");
		
			/*** Set the taget frame to selected ***/
			container.$controls.find("li#"+container.carouselID+"-link-"+actualSlide).addClass("selected");
			
			/*** Get a reference to the target slide ***/
			$targSlide = $("#"+container.carouselID+"-entry-"+actualSlide);
			
			var newInfo = { newLinkURL: null, newLinkTitle: null, contentToPush: null };
			
			if($targSlide.length > 0) {
				$targSlideLink = $targSlide.children("a:first");
				$targSlideContent = $targSlide.find(".detail-set");
				
				if($targSlideLink.length > 0) {
					newInfo.newLinkTitle = $targSlideLink.attr("title");
					newInfo.newLinkURL = $targSlideLink.attr("href");
				}
				
				if($targSlideContent.length > 0) {
					newInfo.contentToPush = $targSlideContent.html();
				}
			}
		
			container.$carousel.find('li.selected').removeClass("selected");
			
			if(container.$carouselInfoHold.length > 0) {
				if(newInfo.contentToPush) {
					container.$carouselInfoHold.fadeOut(250, function() {
						container.$carouselInfoHold.attr("title", newInfo.newLinkTitle);
						container.$carouselInfoHold.attr("href", newInfo.newLinkURL);
						container.$carouselInfoHold.html(newInfo.contentToPush);
						container.$carouselInfoHold.fadeIn(250);
					});
				}
			}
		
			container.$carousel.filter(':not(:animated)').animate({
				left: '-='+leftShift
			}, 500, function () {
				if (slideNo == 0) {
					container.$carousel.css('left', -(container.mediaEntryWidth * container.numberVisible * container.slideCount));
					slideNo = container.slideCount;
				} else if (slideNo > container.slideCount) {
					container.$carousel.css('left', -(container.mediaEntryWidth * container.numberVisible));
					slideNo = 1;
				}
			
				container.$carousel.find('li#'+container.carouselID+'-clone-entry-'+slideNo).addClass("selected");
				container.$carousel.find('li#'+container.carouselID+'-entry-'+slideNo).addClass("selected");
	
				container.currentSlide = slideNo;
			}); 
		
			container.currentSlide = slideNo;  
		
			clearTimeout(container.animationDelay);
			container.animationDelay = setTimeout(container.slideAnimation, 5000);            
		
			return false;
		}
	
		container.slideAnimation = function() {
			var jumpTo = container.currentSlide - 1;
		 
			container.gotoSlide(jumpTo);
		}
		
		container.$mediaItems.each(function() {
		  var mediaItemRef = this;
		  mediaItemRef.$keyLink = $(mediaItemRef).children("a:first");
		  mediaItemRef.$infoBar = mediaItemRef.$keyLink.find(".info-bar");


			if($(mediaItemRef).hasClass("video")) {
        // mediaItem.$liID = $(mediaItem).attr("id");
			
        // mediaItem.$videoPlay;
			
				$(mediaItemRef).find('a').each(function() {
          //          var thisLinkOver = this;
          //          
          // thisLinkOver.contId = $(thisLinkOver).attr("id");
          // thisLinkOver.video = $(thisLinkOver).attr("href");
          //        
          // thisLinkOver.$videoPlayerControls = $("<div class=\"video-player-controls-hold clearfix\" id=\""+mediaItem.$liID+"-pc\"></div>");
          //        
          // $(thisLinkOver).parent().append(thisLinkOver.$videoPlayerControls)
				});

				$(mediaItemRef).find('a').click(function(e) {
          $this = $(this);
          video_id = $this.data('videoid');
          video_source = $this.data('videosource');
          if(video_source==1) {
            $videoPlayer = $('<iframe class="youtube_carousel_frame" type="text/html" width="530" height="323" src="http://www.youtube.com/embed/'+ video_id +'" frameborder="0"></iframe>');
          } else {
            $videoPlayer = $('<iframe class="vimeo_carousel_frame" src="http://player.vimeo.com/video/'+ video_id +'" width="530" height="323" frameborder="0"></iframe>');
          }

          clearTimeout(container.animationDelay);
          $('#home-carousel-video-holder').append( $videoPlayer ).show();
          $this.find('img').hide();
          e.preventDefault();

          // $(thisLinkOver).parent().addClass("playing");
          //    
          $closeButton = $("<a href=\"#\" class=\"video_carousel_close\"><span class=\"accessibility\">Close</span></a>");
          $closeButton.click(function() {
            var thisCloseButton = this;
            
           $this.append( $videoPlayer ).find('img').show();
           $videoPlayer.remove();
           $(thisCloseButton).remove();

           if(container.slideCount > 1) {
             container.animationDelay = setTimeout(container.slideAnimation, 5000);
           }

          });
             
          $this.parent().append($closeButton);
				});
			}

		});
	
		container.$controls.find("li > a").each(function() {
		  var thisControlLink = this;
		  
			thisControlLink.origID = $(thisControlLink).parent().attr("id");
			thisControlLink.numericID = Number(thisControlLink.origID.substring((thisControlLink.origID.lastIndexOf("-") + 1), thisControlLink.origID.length));
		
			$(thisControlLink).click(function() {
				container.gotoSlide(thisControlLink.numericID,true);
				return false;
			});
		});

	container.leftArrow.click(function(e){
    container.gotoSlide(container.currentSlide+1);
	  e.preventDefault();
	});

	container.rightArrow.click(function(e){
    container.slideAnimation( );
    e.preventDefault();
	});

    container.animationDelay = setTimeout(container.slideAnimation, 5000);
		
		var carouselIDString = container.carouselID;
		animRefs[carouselIDString] = container;
	});
}
