//Originally by Matt Haynes
//Updated to use glow library by Alexander Adu-Sarkodie March 2009
var TvListingsCarousel = function() {
			
	var initiated = false;
	var updateInterval = false;
	var baseUrl = "/tv/channels_common/1/includes/tv_listings_carousel/tv_listings_carousel_ajax_wrapper.sssi?channel={channel}&channel_region={region}";
	
	function makeCarousels() {
		
		glow.dom.get('.tv-listings-holder').each(function(i) {

			var me = glow.dom.get(this);
			
			if (!me.hasClass("debug")) {
			
				var classNames = this.className;
				
				var channel = classNames.match(/channel-([^\s]*)/);
				var region = classNames.match(/region-([^\s]*)/);
				
				if (channel && channel[1]) {

					var data = {
						channel : channel[1] ,
						region : ""
					}
					
					if (region && region[1]) {
						data["region"] = region[1];
					}

					var url = glow.lang.interpolate(baseUrl, data);
			
					var loading = glow.dom.get("#tv_listings_loading");

					var getRef = glow.net.get(url, {
						onLoad: function(response) {
							me.empty();
							var nodes = glow.dom.create(response.text());
							me.html("");
							me.append(nodes);
							makeCarousel(me, i, channel[1]);	
							checkOnNow();
							shortenTitles();
							me.get("ul.tv-listings").css("visibility", "visible");
						},
						onError : function() {
							loading.remove();
							me.get("ul.tv-listings").css("visibility", "visible");
						}
					});

					
				} else {
					me.css("visibility", "visible");									
				}
			}
		});
	}


	function makeCarousel(me, i, channel) {

		var opts;
	
		if (channel == "bbcthree") {
			opts = { 
				loop : false,
				size : 3,
				vertical:true,
				animTween: glow.tweens.linear(),
				className: "channelsCarousel"
			}
		} else {
			opts = { 
				loop : false,
				size : 7,	
				animTween: glow.tweens.linear(),
				className: "channelsCarousel"
			}		
		}
			
		// Make carousel
		var carousel = new glow.widgets.Carousel(me.get("ul.tv-listings"), opts);		

		// Hide first slide
		//carousel.moveTo(2, 1, {anim:false});
		carousel.moveTo(1, false);
		
		me.append(glow.dom.create("<div class='tv-listings-holder-btm'></div>"));
		
		carousel.channel = channel;

		// Store in array for access
		TvListingsCarousel.carousels.push(carousel);
		
		// Three Rollover titles 			
		if (channel == "bbcthree") {
			var items = carousel.items;
			items.each(function() {
				var me = glow.dom.get(this);
				
				me.get("img").removeAttr("title");
				me.get(".title").css("display", "none");
				
			
				
				
				glow.events.addListener(  
					me,  
					'mouseover',  
					function () {
						this.get(".title").css("display", "block");
						this.get(".listings_iplayer_cta").css("position", "relative");
						this.get(".listings_iplayer_cta").css("top", "-60px");						
					},
					me
				);         					

				glow.events.addListener(  
					me,  
					'mouseout',  
					function () {
						this.get(".title").css("display", "none");
						this.get(".listings_iplayer_cta").css("top", "0px");						
					},
					me
				);    
				
			});
		}
		
	}

	/**
	 *	Highlights the item in the listing that is on now and moves it to the middle if it can.
	 */
	function checkOnNow() {

		for (var i=0,len = TvListingsCarousel.carousels.length;i < len; i++) {
			var thisCarousel =  TvListingsCarousel.carousels[i],
				items = thisCarousel.items,
				onNow,
				matchStartDate = /start\-([^\s]+)/,
				dateNow = Common.getDate();
			
				// Loop each item to find out whats on now
				items.each(function(i) {
				
					// Get the start date for this item and the next item from classname
					var thisItemDateMatch = this.className.match(matchStartDate);
					
					if (thisItemDateMatch && thisItemDateMatch[1]) {
						var nextItemDateMatch = items[i+1].className.match(matchStartDate);				
						var thisItemDate = Common.parseXsdDate(thisItemDateMatch[1]);		
					 }
					 
					if (nextItemDateMatch && nextItemDateMatch[1]) {
						var nextItemDate = Common.parseXsdDate(nextItemDateMatch[1]);		
					}
					
					// if the startdate for this item is in the past and the next item in the future
					// then we are on now
					if (thisItemDate && nextItemDate 
							&& thisItemDate < dateNow
							&& dateNow < nextItemDate) {
						highlightOnNow(thisCarousel, i, thisItemDate, this.className.match(/pid\-([^\s]+)/)[1]);
						
					// Also ... if the startdate for this items is in the past and there is no
					// startdate for the next item we are on now (probably).					
					} else if (nextItemDate == undefined && thisItemDate < dateNow) {
						highlightOnNow(thisCarousel, i, thisItemDate, this.className.match(/pid\-([^\s]+)/)[1]);
					} else {
						var thisItem = glow.dom.get(this);
						if (thisItem.hasClass("onNow")) {
							thisItem.removeClass("onNow");
						}
						
						if (thisItem.get(".onNowMarker")) {
							thisItem.get(".onNowMarker").remove();
						}					
					}
				
				});
					
		}
	}
	
	function highlightOnNow(carousel, item, startTime, pid) {
	
		var onNow = glow.dom.get(carousel.items[item]);
		
		if (!onNow.hasClass("onNow")) {
			if (carousel.visibleIndexes().length == 4) {
				carousel.moveTo(item, false);
			} else {
				carousel.moveTo(item - 3, false);			
			}
			onNow.addClass("onNow");
			onNow.get(".thumb").append(glow.dom.create("<div class='onNowMarker'>on now</div>"));
		}

		var simulcast = Common.checkSimulcast(carousel.channel, startTime, pid);

		if (simulcast) {
			highlightSimulcast(carousel, item);
		}				
		

	}
	
	function highlightSimulcast(carousel, item) {

		carousel.items.each(function() {
			var me = glow.dom.get(this);
			if (me.get(".watchlive").length > 0) {
				me.get(".watchlive").remove();
				me.get(".listings_iplayer_cta").css("display", "block");
			}
		});
		
		var onNow = glow.dom.get(carousel.items[item]);
		onNow.append("<a href='/"+carousel.channel+"/watchlive/' class='watchlive'><span class='blq-hide'>Watch live</span></a>");
		onNow.get(".listings_iplayer_cta").css("display", "none");
		
	}
	
	function shortenTitles() {
		for (var i=0,len = TvListingsCarousel.carousels.length;i < len; i++) {
			var thisCarousel =  TvListingsCarousel.carousels[i],
				items = thisCarousel.items,
				titles = items.get(".title");
			
			titles.each(function() {
				var title = glow.dom.get(this);
				if (title.html().length > 25) {
					title.attr("title", title.html());
					var s_title = title.html().substring(0, 25) + "...";
					title.html(s_title);
				}
			});
		}
	}	
	
	return {
		carousels : [],
		
		init : function() {
			
			if (initiated) return;
			
			makeCarousels();
			updateInterval = window.setInterval("TvListingsCarousel.checkOnNow()", 60100);
			initiated = true;
		},
		
		checkOnNow : function() {
			checkOnNow();
		}
		
	}

}();