function slideCarousel(element,distance) {
	var myFx = new Fx.Scroll(element, {
		wait: true,
		duration: 200,
		transition: Fx.Transitions.Quad.easeInOut,								 
		offset: {
			'x': distance,
			'y': 0
		}
	}).toTop();	
}

function changeStoryGalleryImage(x) {
	var images = $('photography').getElements('.photo');
	var current = 1;

	images.each(function(item, index) {
		if (item.getStyle('display') == 'block') {
			item.setStyle('display','none');
			current = index+1;
		}
	});

	var next = 1;
	if (x == 'previous') { next = (current > 1) ? current-1 : images.length; }
	else { next = (current < images.length) ? current + 1 : 1; }
	$('photo'+next).setStyle('display', 'block');
}

function embedvideoplayer(){
		var player;
		player = new Player("player", {
			allowAds: false,
			flashPlayerUrl: "/player/assets/player_417.swf",
			width:642,
			height:362,
			videoWidth:642,
			videoHeight:362,
			smallControls:true,
			autoStartFromURL:false,
			autoStartFirstClip:false,
			showDirectLinkAnchor:false,
			playListContainer : "clip",
			embedContainer : "player",
			playListIdPrefix: "hi",
			flashControls :{flashControls_setColor:1},
			flashPlayerFeed	: "news",
			playButton : "/images/play_button.png"
		});
		
		player.play('1','http://dj.rte.ie/vodfeeds/feedgenerator/videos/live/?id=7&amp;source=RTE.ie','flash',254,{autoPlay:true, noAds:true,adLocation:'/ads/video/live.inc',name:'RTE_News_Now',explicit:false});
		

	}

function setHomeNewsNow() {	
$('panel-news-now').set('html', '');
$('panel-news-now').set('html', '<div id=\"player\"></div>');
embedvideoplayer();
	
}

function setHomeTabs() {
	
	var tabs = $('home-tabs').getElements('li');
	tabs.each(function(item, index){
		item.addEvent('click', function() {
										
			$('panel-main').hide();
			$('panel-news-now').hide();
			
			$('tab-main').removeClass('selected');
			$('tab-news-now').removeClass('selected');			
			
			var currentPanel = item.get('id').replace('tab','panel');			
			$(currentPanel).show();
			item.addClass('selected');

			if (currentPanel.indexOf('news-now') >= 0) {
				setHomeNewsNow();
			}
			else {
				$('panel-news-now').set('html', '');
			}
		});
	});
}

function setNav() {
// sets main news navigation
	

	var nav = $('news-nav');
	
	$('nav-programmes').addEvent('click', function() {

		if($('nav-programmes').match('.active')) {
		
			var hideMenu = new Fx.Morph($('menu-programmes'), {duration: 200, transition: Fx.Transitions.Sine.easeOut});				 
			
			hideMenu.start({
				'height': [155, 0],
				'margin-bottom': [0, 4]			
			});
			
			$('nav-programmes').removeClass('active');


		} else {

			var showMenu = new Fx.Morph($('menu-programmes'), {duration: 200, transition: Fx.Transitions.Sine.easeOut});				 
			
			showMenu.start({
				'height': [0, 155],
				'margin-bottom': [4, 0]			
			});
			
			$('nav-programmes').addClass('active');



		}


	});


}


function setHomeFeaturedVideo() {
	if ($('featured-video') && $('featured-video').getElement('.slider')) {

		var columns = $('featured-video').getElement('.container').getElements('div');
		var sliderWidth = 0;
		
		columns.each(function(item, index) {			
			sliderWidth = sliderWidth+item.getWidth();
		});
		
		var container = $('featured-video').getElement('.container');
		container.setStyle('width',sliderWidth);
		
		var slideContainer = $('featured-video').getElement('.slider');
		
		if($('featured-video').getElement('.arrow-left') && $('featured-video').getElement('.arrow-right')) {

			var arrowLeft = $('featured-video').getElement('.arrow-left');
			var arrowRight = $('featured-video').getElement('.arrow-right');		
			
			arrowLeft.addEvent('click', function() {						 
				slideCarousel(slideContainer,-164);
			});												 
		
			arrowRight.addEvent('click', function() {									  
				slideCarousel(slideContainer,164);
			});
		
		}
	}
}

function setSidebarCarousels() {
	
	var carousels = $$('.sidebar-carousel');

	carousels.each(function(item, index) {
		// alert(item);
		
		if(item.getElement('.arrow-left') && item.getElement('.arrow-right')) {
		
			var arrowLeft = item.getElement('.arrow-left');
			var arrowRight = item.getElement('.arrow-right');
			var slider = item.getElement('.sidebar-carousel-container');
			var containerWidth = slider.getWidth();
			var sliderList = slider.getElement('ul'); 
			var sliderItems = sliderList.getElements('li');
	
	
			// get width of container
			//sliderItems.setStyle('width', containerWidth);
			
			// get number of list items and multiply by container width to get slider width
			var sliderWidth = (sliderItems.length * containerWidth);
			
			// set slider (UL) width
			sliderList.setStyle('width', sliderWidth);
			
			
			arrowLeft.addEvent('click', function() {						 
				slideCarousel(slider,-containerWidth);			
				//alert('clicked left');
				var scroll = slider.getScroll();
				
				if((sliderWidth - sliderItems[0].getWidth) == scroll.x) {
	
	
				};
				
				//alert("scroll position = "+scroll.x+ " - slider width = "+sliderWidth);
				
			});												 
		
			arrowRight.addEvent('click', function() {									  
	
				var scroll = slider.getScroll();
				//alert('clicked right');
	
				if((sliderWidth - sliderItems[0].getWidth()) == scroll.x) {
					slideCarousel(slider,-sliderWidth);				
				} else {
					slideCarousel(slider,containerWidth);				
				};
	
	
	
			});
		};
		
	});
}

function setHomeSpecialReports() {
	if ($('home-special-reports') && $('home-special-reports').getElement('.slider')) {

		var listItems = $('home-special-reports').getElement('ul').getElements('li');
		var sliderWidth = 0;
		
		listItems.each(function(item, index) {			
			sliderWidth = sliderWidth+item.getWidth();			
			// cater for 13 pixel margin to each item
			sliderWidth = sliderWidth+13;
		});
		
		// remove leading margin value from first item to give total width
		sliderWidth = sliderWidth-13;

		var container = $('home-special-reports').getElement('ul');
		container.setStyle('width',sliderWidth);
		
		var slideContainer = $('home-special-reports').getElement('.slider');
		
		var arrowLeft = $('home-special-reports').getElement('.arrow-left');
		var arrowRight = $('home-special-reports').getElement('.arrow-right');		
		
		arrowLeft.addEvent('click', function() {						 
			slideCarousel(slideContainer,-524);
		});												 
	
		arrowRight.addEvent('click', function() {									  
			slideCarousel(slideContainer,524);
		});												 
	}
}

function setStoryPhotos() {
	var storyGalleryPeriodical;
	if ($('photography')) {
		var images = $('photography').getElements('.photo');
		if (images.length > 1)	{
			images.each(function(item, index, array){
				item.getElement('.number').setStyle('visibility', 'visible');
				var left = item.getElement('.left-arrow');
				var right = item.getElement('.right-arrow');
				left.setStyle('visibility', 'visible');
				right.setStyle('visibility', 'visible');
				left.addEvent('click', function(event) {$clear(storyGalleryPeriodical);changeStoryGalleryImage('previous');});
				right.addEvent('click', function(event) {$clear(storyGalleryPeriodical);changeStoryGalleryImage('next');});
			});
		}
	}
}

function equalizeColumns(elements) {
	
	// create array for element heights
	var heights = [];
	elements.each(function(item) {
		// add heights to array
		heights.extend([item.getStyle('height').toInt()]);
	});
	
	// get max height
	var maxHeight = heights.max();
	
	// set new heights
	elements.each(function(item) { 
		item.setStyle('height', maxHeight);				   
	});
}

/* player variables for use while tabbing */
var firstPlay = true;
var isPlaying = new Hash({});

/* player functions */
function getFlashMovie(id) {
	if ($(id)) {
		var objId = ($(id).tagName.toLowerCase() == 'object') ? id : $(id).getElement("object").getAttribute('id');
		var isIE = navigator.appName.indexOf("Microsoft") != -1;
		return (isIE) ? window[objId] : document[objId];
	} else {
		return null;
	}
}

function onPlayerStateChanged(state, playerId) {
	if (getFlashMovie(playerId) !== null) {
		switch(state)
		{
			case 2 :	// Playlist Loaded
						if (!firstPlay && !isInlineEmbeddedPlayer(playerId) && $('news-article-container')) { 
							getFlashMovie(playerId).playPauseMedia();
						} else { 
							firstPlay = false;
						}
						break;													

			case 4 :	// Playlist ended
						break;
						 
			case 8 :	// Playlist load failed
						break;
						
			case 16 :	// Playing
						if (isPlaying.get(playerId) !== true) {
							pauseAllPlayers();
							isPlaying.set(playerId, true);
						}
						break;
						
			case 32 :	// Paused
						isPlaying.set(playerId, false);
						break;
						
			case 64 :	// Player ready
						break;
		}		
	}
}

function isInlineEmbeddedPlayer(id) {
	var isEmbed = false;
	$$('.av-embed').each(function(item, index){
		if (item.getElement("object").getAttribute('id') == id) {
			isEmbed = true;
		}
	});
	return isEmbed ;
}


function pauseAllPlayers() {
	isPlaying.each(function(value,key){
		if (value == true)  {
			var flash = getFlashMovie(key);
			if (flash != null) {
				flash.playPauseMedia();
			}
			else
				isPlaying.erase(key);
		}
	});
}

function setArticle() {
	// set up article galleries
	if ($('photography')) setStoryPhotos();
	
	// fix float problem with large embedded images
	
	var embeddedImages = $('news-article-container').getElements('.image-embedded-left');
	
	embeddedImages.each(function(item, index) {
			var size = item.getSize();
			if(size.x > 400) {
				item.removeClass('image-embedded-left');	
			}
	});
	
	// if we've arrive to the article on a location hash i.e. (cheezburger.html#video)
	if(window.location.hash) {
		// hide all content panels		
		var panels = $('news-article-container').getElements('.tabbed');

		panels.each(function(item, index){
			item.removeClass('open');
		});
		
		// and show panel requested from hash
		var activePanel = 'panel-'+window.location.hash.replace('#','');
		
		// is hash legit?
		if($(activePanel)) {
			$(activePanel).addClass('open');
					
			// set 'selected' on appropriate tab
			var tabs = 	$('tab-group').getElements('li');
			
			tabs.each(function(item, index) {
				item.removeClass('selected');
			});
			
			currentTab = window.location.hash.replace('#','tab-');
			$(currentTab).getParent().getParent().addClass('selected');
			
		} else {
			// hash is malformed, fire default actions
			
			// display article panel
			$('panel-article').addClass('open');
			
			// set active tab
			if ($('tab-article'))
				$('tab-article').getParent().getParent().addClass('selected');
		}
	}
	
	if($('tab-group')) {
		// set tab behaviours for switching panels
		var tabs = 	$('tab-group').getElements('li');
		
		// set 'selected' on appropriate tab
		tabs.each(function(item, index){
			item.addEvent('click', function() {
				
				/*   Pause All Players - to stop playing in background in IE ----   */
				pauseAllPlayers();				
				
				/* does not auto play first player in new tab */
				firstPlay = true; 
				
				tabs.each(function(item, index) {
					item.removeClass('selected');
				});
				
				this.addClass('selected');
								
				// close other panels
				var panels = $('news-article-container').getElements('.tabbed');
				panels.each(function(item, index){
					item.removeClass('open');
				});

				// switch to active panel
				var activePanel = this.getElement('a').get('id').replace('tab','panel');
				if ($(activePanel).addClass('open')) {
					//alert('added open class');	
				}
						
				// set window.location hash
				window.location.hash =  this.getElement('a').get('id').replace('tab-','');
				
			});
		});
	}
	
	// check if we have videos on the page
	if ($('news-article-container').getElements('.multimedia')) setArticleAV();
	setEmbeddedAV();

}

function setArticleAV() {
	/* sets up video tab player */
	setRelatedPlayers();
	
	
	var playerArray = [];
	var idArray = [];
	var avItems = $('news-article-container').getElements('.multimedia');
	
	
	
	avItems.each(function(item, index) {
		var bug = item.getElement('.bug');
		var clipContainer = item.getElement('.clipContainer');
		var clipContainerId = clipContainer.getProperty('id');
		
		var params = bug.getProperty('rel').split(",");
		var isAudio = (params[5]=="audio");
		var w = isAudio ? 174 : 642;
		var h = isAudio ? 0 : 361;
		var f = isAudio ? {"flashControls_fullScreen": 0, flashControls_setColor:1, flashControls_audioBtn:0, flashControls_audioDlg:1} : {flashControls_setColor:1};
		var feed = isAudio ? "news-audio" : "news";

		idArray[index] = clipContainerId;
		playerArray[index] = new Player(clipContainerId, {
			videoWidth:w,
			videoHeight:h,
			width:w,
			height:h,
			autoStartFromURL:false,
			autoStartFirstClip:false,
			autoPlayAll:false,
			playListContainer:'',
			smallControls:true,
			showDirectLinkAnchor:false,
			flashPlayerFeed:feed,
			flashControls:f,
			allowAds:false
		});


		
  		triggers = [item.getElement('.bug'),item.getElement('.overlay'),item.getElement('.description')];

		triggers.each(function(trigger, index)  {
			trigger.addEvents({
				click: function(event) {
					if (item.hasClass('on')) {
						closeStoryVideoAV(item);
					} else {
						openStoryVideoAV(item);
					}					
				}
			});
		});


		
		
		
	});

	function openStoryVideoAV(item) {
		if (!item.hasClass('on')) {
			avItems.each(function(item, index) {
				if (item.hasClass('on')) { closeStoryVideoAV(item);}
			});
			firstPlay = false;
			
			item.addClass('on');
			var bug = item.getElement('.bug');
			var params = bug.getProperty('rel').split(",");
			var isAudio = (params[5]=="audio");
			var title = item.getElement('.title');
			var thumbnail = item.getElement('.thumbnail');
			var description = item.getElement('.description');
			var overlay = item.getElement('.overlay');					
			var clipContainer = item.getElement('.clipContainer');
			var clipContainerId = clipContainer.getProperty('id');

			var btnOpen = item.getElement('span.open');
			var btnClose = item.getElement('span.close');
			var closeGraphic  = new Element('div', {
											id: 'close-graphic',
											html: 'close'
											});
			
			btnOpen.hide();
			btnClose.setStyle('display','inline');
			btnClose.set('rel',item.getHeight());
			
			
			
			var array = playerArray;

			var ids = idArray;
			var pos = getArrayPosition(idArray,clipContainerId);
			
			
			var vidBox = new Fx.Morph(item, {transition: Fx.Transitions.Sine.easeOut});

			var clipBox = new Fx.Morph(clipContainer, {duration: 600,transition: Fx.Transitions.Sine.easeOut,
									onComplete: function() {
													if(params.length >= 5) {
														playerArray[pos].play(params[0],params[1],params[2],params[3],JSON.decode(params[4]));
													}
													// create close graphic button
												}.bind(clipContainerId)
									});
			var titleText = new Fx.Morph(title, {transition: Fx.Transitions.Sine.easeOut});
		
			var width = isAudio ? 174 : 642;
			var height = isAudio ? 0 : 355;

		
			clipContainer.setStyle('opacity',0);
			clipBox.start({
				'display': 'block',
				'width':width,
				'height':height+27,
				'opacity':1
			});

			if (!isAudio) {
				clipContainer.setStyle('margin-top',0);
				vidBox.start({
					'display':'block',
					'width':width,
					'height':height+52, 
					'margin-bottom':7
				});
				bug.adopt(closeGraphic);																	
				thumbnail.fade('out');
				overlay.fade('out');
				description.fade('out');
			}
			else {
				clipContainer.setStyle('margin-top',item.getHeight()-16);
				vidBox.start({
					'display':'block',
					'width':width,
					'height':item.getHeight()+30
				});
			}
			bug.addClass('open');
		}
	}
	
	function closeStoryVideoAV(item, toHeight) {
		if (item.hasClass('on')) {
			item.removeClass('on');
			var bug = item.getElement('.bug');
			var params = bug.getProperty('rel').split(",");
			var isAudio = (params[5]=="audio");
			var title = item.getElement('.title');
			var description = item.getElement('.description');
			var thumbnail = item.getElement('.thumbnail');
			var overlay = item.getElement('.overlay');							
			var clipContainer = item.getElement('.clipContainer');
			var clipContainerId = clipContainer.getProperty('id');
			var btnOpen = item.getElement('span.open');
			var btnClose = item.getElement('span.close');
			var originalHeight = btnClose.get('rel');
			btnClose.hide();
			btnOpen.setStyle('display','inline');
			
			// kill close graphic button (if there is one)
			if(bug.getElement('#close-graphic')) {
				bug.getElement('#close-graphic').destroy();
			}

			var vidBox = new Fx.Morph(item, {transition: Fx.Transitions.Sine.easeOut});
			var bugBox = new Fx.Morph(bug, {transition: Fx.Transitions.Sine.easeOut});
			var clipBox = new Fx.Morph(clipContainer, {transition: Fx.Transitions.Sine.easeOut});
			var titleText = new Fx.Morph(title, {transition: Fx.Transitions.Sine.easeOut});
			
			var array = playerArray;
			var ids = idArray;
			var pos = getArrayPosition(idArray,clipContainerId);
			playerArray[pos].stop();

			vidBox.start({
				'width':174,
				'height': originalHeight,
				'margin-bottom':0
			});
			clipBox.start({
				'width':174,
				'height':0,
				'opacity':0
			});					


			if (!isAudio) {
				thumbnail.fade('in');
				description.fade('in');
				overlay.fade('in');
			}
			bug.removeClass('open');
		}
	}
}

function getArrayPosition(arrayName,arrayItem)
{
    for(var i=0;i<arrayName.length;i++){ 
       if(arrayName[i]==arrayItem)
            return i;
    }
    return -1;
}

	
function setRelatedPlayers() {
	var audioTabPlayers = [];
	var audioTabItems = [];

	if($('relatedVideoPlayer')) {
		videoPlayer = new Player("relatedVideoPlayer", {
			videoWidth:642,
			videoHeight:361,
			width:642,
			height:361,
			highlightClass: "hl",
			playListIdPrefix: "videoClip",
			autoStartFromURL:false,
			autoStartFirstClip:true,
			smallControls:true,
			showDirectLinkAnchor:false,
			playListContainer : "clip",
			flashPlayerFeed:"news",
			flashControls :{flashControls_setColor:1},
			allowAds:false
		});
	}
	
	if ($('article-audio-list')) {
		$('article-audio-list').getElements('li').each(function(item, index){
			audioTabItems[index] = item;
			var playerTmp = item.getElement('.player');
			var playerId = playerTmp.getProperty('id');
			
			//alert(item.getHeight());
			if(item.getElement('.icon').getHeight() < item.getElement('.metadata').getHeight()) {
				item.getElement('.icon').setStyle('height', item.getElement('.metadata').getHeight()-14);																		   
			}

			audioTabPlayers[index] = new Player(playerId, {
				videoWidth:642,
				videoHeight:0,
				width:642,
				height:0,
				autoStartFromURL:false,
				autoStartFirstClip:false,
				autoPlayAll:false,
				playListContainer:'',
				smallControls:true,
				showDirectLinkAnchor:false,
				flashPlayerFeed:"news-audio",
				flashControls:{flashControls_setColor:1, flashControls_fullScreen:0, flashControls_audioDlg:1},
				allowAds:false
			});

			item.getElement('.icon').addEvent('click', function(event) {
				if (this.hasClass('on')) {
					closeAudioClip(this);
				} else {
					openAudioClip(this);
				}
			}.bind(item));

			item.getElement('.metadata').addEvent('click', function(event) {
				if (this.hasClass('on')) {
					closeAudioClip(this);
				} else {
					openAudioClip(this);
				}
			}.bind(item));
			
		});
	}
	
	function openAudioClip(item) {
		firstPlay = false;
		$('article-audio-list').getElements('.on').each(function(item, index){closeAudioClip(item);});
		item.addClass('on');
		var pos = getArrayPosition(audioTabItems,item);
		var params = item.getProperty('rel').split(",");
		item.getElement('.player').set('tween',{duration: 300, onComplete: function(){
			audioTabPlayers[pos].play(params[0],params[1],params[2],params[3]);
		}}).tween('height', [0,27]);
	}
	
	function closeAudioClip(item) {
		item.removeClass('on');
		var pos = getArrayPosition(audioTabItems,item);
		audioTabPlayers[pos].stop();
		item.getElement('.player').set('html', '');
		item.getElement('.player').set('tween',{duration: 300}).tween('height', 0);
	}
} 

function updateRelatedVideoInfo(id) {
	var infoBox = $('relatedVideoInfo');
	var info = $('videoClip'+id).getElement('.clipInfo');
	infoBox.set('html', info.get('html'));	
}


function setBreakingStrap(url,title) {
	
	// check for breaking news cookie
	if(Cookie.read('rte-breaking-news') != title) {
	
		var strap = '';	
		strap+='<div class="rte_gr_12">';
		strap+='	<div id="breaking-strap">';
		strap+='		<h1>Breaking News</h1>';
		if(url == ''){
			strap+='		<p>'+title+'</p>';
		}
		else{
			strap+='		<p><a href="'+url+'">'+title+'</a></p>';
			}
		strap+='		<a class="close" title="close">Close Breaking News</a>';
		strap+='		<div class="clear"></div>';
		strap+='	</div>	 ';
		strap+='</div>';
		strap+='<div class="clear"></div>';
		
		document.write(strap);
		
		var strapContainer = $('breaking-strap').getParent();		
		var button = $('breaking-strap').getElement('.close');
		
		button.addEvent('click', function() {
			var myEffect = new Fx.Morph(strapContainer, {
										duration: 'short', 
										transition: Fx.Transitions.Sine.easeOut,
										onComplete: function() {
														// set cookie for this title
														var thisCookie  = Cookie.write('rte-breaking-news', title, {duration: 7});
													}
										});		 
			// close strap
			myEffect.start({
				'height': [strapContainer.getHeight(),0],
				'margin-top': [7,0],
				'margin-bottom': [7,0],			
				'width': [strapContainer.getWidth(),0],
				'opacity': [1,0]				
			});		
		});
	}	
}

function setVideoNav () {

	var expandables = $('video-container').getElements('.expandable');
	var subMenus = $('video-container').getElements('.sub-menu');

	//get all menu items with .droppable class
	expandables.each(function(item, index){
				
		item.addEvent('click', function() {

			// check if menu item is already open
			if(item.hasClass('open')) {
				// alert('this is already open!');
				item.removeClass('open');
				
				subMenus.each(function(item, index){			
					item.hide();
				});								
			} else {
				
				var thisMenu = item.getNext('ul');
	
				subMenus.each(function(item, index){			
					item.hide();
				});
	
				expandables.each(function(item, index){			
					item.removeClass('open');
				});
	
				this.addClass('open');						
				thisMenu.show();
				
				// check if there are calendars in the menu item
				if(thisMenu.getElements('div').length > 0) {
					setCalendars(thisMenu);	
				}
			}
			
		});
	});
	
	function setCalendars(menu) {
		
		var calendars = $('video-container').getElements('.calendar');		

		triggers = menu.getElements('.calendar').getPrevious('a');


		triggers.each(function(item, index){
			item.addEvent('click', function() {
				
				calendars.each(function(item, index){			
					item.hide();
				});
				
				triggers.each(function(item, index){			
					item.removeClass('open');
				});					
				
				item.addClass('open');
				item.getNext('.calendar').show();
			});

		});
	}
	
}

function setSidebarLatest() {
	
	var tabs = $('sidebar-latest-box').getElements('.tabs li');
	var panels = $('sidebar-latest-box').getElements('.panel');
	
	tabs.each(function(item, index){
		item.addEvent('click', function() {
			panels.removeClass('open');
			tabs.removeClass('selected');
						
			var currentPanel = '.'+item.get('class').replace('tab','panel');								
			$('sidebar-latest-box').getElement(currentPanel).addClass('open');			
			this.addClass('selected');
			
		});
	});
	
}

function setBusinessSwitcherBox() {
	
	var tabs = $('sidebar-business-switcher-box').getElements('.tabs li');
	var panels = $('sidebar-business-switcher-box').getElements('.panel');
	
	tabs.each(function(item, index){
		item.addEvent('click', function() {
			panels.removeClass('open');
			tabs.removeClass('selected');
						
			var currentPanel = '.'+item.get('class').replace('tab','panel');								
			$('sidebar-business-switcher-box').getElement(currentPanel).addClass('open');			
			this.addClass('selected');			
		});
	});	
}

function updateMainPoints(container,feed,interval){
	var datemod = '';
	var request = new Request({
	   url			:	feed,
	   method		:	"get",
	   secure		:	false,
	   async		:	false,
	   delay		:	interval,
	   onComplete	:	function(response){
							if(datemod !== this.getHeader('Last-Modified')){
								$(container).set('html',response);
							}
							datemod = this.getHeader('Last-Modified');
						}
	}).startTimer();
}

function setGalleriesRegular() {
	$$('.news-gallery-regular').each(function(item, index) {

		if (item.getElement('.thumbnails')) {

			var photoWidth = 640;
			var thumbSliderWidth = 576;
			var thumbListWidth = 0;
			var currentThumb = 1;		
			var thumbnails = item.getElement('.thumbnails');
			var thumbCount = thumbnails.getElements('.thumbnails-slider-container ul li').length;
			
			var thumbListItems = thumbnails.getElements('.thumbnails-slider-container ul li');
			var photoListWidth = 0;
			var photoItems = item.getElements('.photos-slider-container ul li');
			var photoCount = photoItems.length;			
			var photoList = item.getElements('.photos-slider-container ul');
			var photoSlider = item.getElement('.photos-slider-container');
			var photoPrev = item.getElement('.photo-prev');
			var photoNext = item.getElement('.photo-next');				
			var photoCurrent = item.getElement('.photo-current');
			
			//set thumbnail slider height if not 16x9
			
			if(thumbListItems[0].getHeight() != 76) {
				thumbnails.setStyle('height', (thumbListItems[0].getHeight()+30));
			}
			
			photoPrev.addEvent('mouseenter', function() {
				this.addClass('hover');			
			});
	
			photoPrev.addEvent('mouseleave', function() {
				this.removeClass('hover');			
			});
			
			photoNext.addEvent('mouseenter', function() {
				this.addClass('hover');			
			});
			
			photoNext.addEvent('mouseleave', function() {
				this.removeClass('hover');			
			});
			
			// basic check for photos and thumbnails
			if(thumbCount !== photoCount) {
				alert('error: there is an unequal amount of thumbnails to photos');
			}
			
			item.getElement('.photos-total').set('text', photoCount);
			photoCurrent.set('text', 1);
			
			item.getElement('.photo-count').show();
			
			// adjust photo container to accomodate 1px border
			photoWidth+=2;
			
			photoItems.each(function(item, index) {
				photoListWidth += item.getWidth();
				item.getElement('img').setStyle('cursor', 'pointer');
			});
			
			// set photo list width
			photoList.setStyle('width', photoListWidth);		
	
			thumbnails.getElements('.thumbnails-slider-container ul li').each(function(item, index) {
						
				// add click behaviours to thumbs			
				item.addEvent('click', function(e) {
					e.stop();
					//get thumbnail that was just clicked
					var clickedThumb = (thumbnails.getElements('.thumbnails-slider-container ul li').indexOf(this)+1);
					// move to selected thumbnail
					if((clickedThumb > currentThumb) || (clickedThumb < currentThumb)) {		
						moveThumb(clickedThumb);
					}
				});
				// get width for later
				thumbListWidth += item.getWidth();
			});
			
			// add margins to thumbnail list width and remove trailing margin
			thumbListWidth+=((thumbCount*14) -14);
			thumbnails.getElement('.thumbnails-slider-container ul').setStyle('width', thumbListWidth);
			
			// add events to thumbnail prev and next controls
			thumbnails.getElement('.thumbs-prev').addEvent('click', function(e) {
				e.stop();
				slideCarousel(thumbnails.getElement('.thumbnails-slider-container'),-thumbSliderWidth);			
			});
			thumbnails.getElement('.thumbs-next').addEvent('click', function(e) {
				e.stop();
				slideCarousel(thumbnails.getElement('.thumbnails-slider-container'),thumbSliderWidth);			
			});		
			
			// add events to photo prev and next controls
			photoItems.addEvent('click', function(e) {
				e.stop();
				nextPhoto();
			});		
			photoNext.addEvent('click', function(e) {
				e.stop();
				nextPhoto();
			});
			photoPrev.addEvent('click', function(e) {
				e.stop();
				prevPhoto();
			});
			
			function moveThumb(clickedThumb) {
				var currentThumbPosition = (currentThumb*photoWidth);
				var toThumbPosition = ((currentThumbPosition - (clickedThumb*photoWidth))*-1);
				slideCarousel(photoSlider, toThumbPosition);														
				thumbnails.getElements('.thumbnails-slider-container ul li').removeClass('current');				
				thumbListItems[clickedThumb-1].addClass('current');
				currentThumb = clickedThumb;
				photoCurrent.set('text', currentThumb);						
			}
			
			function nextPhoto() {
				// check current thumb is equal to or greater than 1 and less than total amount of thumbs
				if((currentThumb >= 1) && ((currentThumb) < thumbCount)) {						
					// check if we need to slide thumbnail list right
					if(!((currentThumb) % 4)) {
						slideCarousel(thumbnails.getElement('.thumbnails-slider-container'),thumbSliderWidth);
					}							
					// go to next photo and thumbnail
					slideCarousel(photoSlider, photoWidth);
					thumbListItems.removeClass('current');
					(thumbListItems[currentThumb]).addClass('current');
					// increment currentThumb
					currentThumb+=1;
					photoCurrent.set('text', currentThumb);				
				// if we try to go beyond last thumb, go back to start
				} else if(currentThumb = thumbCount) {
					slideCarousel(photoSlider, (photoListWidth*-1));
					thumbListItems.removeClass('current');
					currentThumb=1;				
					photoCurrent.set('text', currentThumb);	
					thumbListItems[0].addClass('current');
					slideCarousel(thumbnails.getElement('.thumbnails-slider-container'),-thumbListWidth);				
				}				
			}
			
			function prevPhoto() {			
				//check current thumb is greater than 1 and less than total amount of thumbs)
				if(currentThumb > 1) {	
									
					if(!((currentThumb-1) % 4)) {					
						// check to see if we're near the end of the list
						if((thumbCount - currentThumb) < 4 ) {
							var singleThumb = thumbListItems[0].getWidth()+14;
							var tempSlide = ((thumbCount - currentThumb)+1)*singleThumb;
							
							slideCarousel(thumbnails.getElement('.thumbnails-slider-container'),-tempSlide);						
						} else {					
							slideCarousel(thumbnails.getElement('.thumbnails-slider-container'),-thumbSliderWidth);
						}
					}		
					// go to previous photo and thumbnail			
					slideCarousel(photoSlider, (photoWidth*-1));
					thumbListItems.removeClass('current');
					(thumbListItems[currentThumb-2]).addClass('current');
					currentThumb-=1;
					photoCurrent.set('text', currentThumb);								
				} else if(currentThumb = 1) {	
					slideCarousel(photoSlider, (photoListWidth));
					thumbListItems.removeClass('current');
					currentThumb = thumbCount;
					photoCurrent.set('text', currentThumb);	
					thumbListItems[thumbCount-1].addClass('current');
					slideCarousel(thumbnails.getElement('.thumbnails-slider-container'),thumbListWidth);
				}
					
			}
		} 
	});
}
 
var articleLargeVideoPlayer;
function articlelargevideoplayer() {   
	articleLargeVideoPlayer = new Player('articleLargeVideoPlayer', {
		videoWidth:642,
		videoHeight:361,
		width:642,
		height:361,
		autoStartFromURL:false,
		autoStartFirstClip:true,
		autoPlayAll:false,
		playListContainer:'articleLargeVideoPlayer',
		smallControls:true,
		showDirectLinkAnchor:false,
		flashPlayerFeed:"news",
		flashControls :{flashControls_setColor:1},
		allowAds:false
	});
}

function setAudioPopouts() {
	$$('.audio-popout').each(function(item, index) {
		item.addEvent('click', function(e) {
			e.stop();
			var pos = $(player.playerCore.playerObjId).currentPosition()/1000;
			popout = window.open(item.href+","+pos, 'audiopopout', 'resizable=1,location=1,status=1,toolbar=0,width=512,height=135');
			pauseAllPlayers();
			if (window.focus) {popout.focus()}				
		});
	});
}

function setEmbeddedAV() {
	$('panel-article').getElements('.av-embed').each(function(item, index) {
		var rel = JSON.decode(item.getProperty('rel'));
		var width = (rel.mediaType == 'audio' ? 300 : 432);
		var height = (rel.mediaType == 'audio' ? 0 : Math.floor(width*9/16));
		var options = (rel.mediaType == 'audio' ? {flashControls_setColor:1,flashControls_fullScreen:0,flashControls_audioDlg:1} : {flashControls_setColor:1} );
		var feed = (rel.mediaType == 'audio' ? "news-audio" : "news");
		item.addClass('av-embed-'+rel.mediaType);
		item.setStyle('width', width);
		item.set('html', '');
		var embedPlayer = new Player(item.getProperty('id'), {
			videoWidth:width,
			videoHeight:height,
			width:width,
			height:height,
			highlightClass: "hl",
			playListIdPrefix: "clipid-",
			autoStartFromURL:false,
			autoStartFirstClip:false,
			autoPlayAll:false,
			smallControls:true,
			showDirectLinkAnchor:false,
			playListContainer : item.getProperty('id'),
			flashPlayerFeed:feed,
			flashControls :options,
			allowAds:false
		});
		embedPlayer.play(rel.ClipId, rel.ClipId, rel.media, rel.profile, {image:rel.image, autoPlay:false});
		var caption = new Element('div', {
            "class"   : "embed-caption", 
            "html" : item.getProperty('alt')
        }).inject(item, "bottom");

	});
}

function setDataTables() {
	
	// dynamically add oddrow classes to tables with the class "data-table"
	
	$$('.data-table').each(function(item, index) {
		var i = 1;		
		item.getElements('tr').each(function(el) {
			if(i % 2 == 0) { el.addClass('oddrow') }
			i++;
		});
		

	});
	
}

function doSearch(){
    //var q = encodeURIComponent($('search-text').value);
	var q = $('search-text').value;
    if (q != '') {
		window.location.href = "/news/search_results.html?query=" + q;
    }
}

function showPlayer(url) {
	var win = window.open(url, "rteplayer", "height=560,width=860,status=yes,toolbar=no,menubar=no,location=no");
	win.focus(); 
}

function showRadioPlayer(url) {
	var win = window.open(url, "rteradioplayer", "height=645,width=752,status=yes,toolbar=no,menubar=no,location=no");
	win.focus();
}


window.addEvent('domready', function() {
	
	//set up nav
	if ($('news-nav')) { setNav();}	

	// set up footer features
	if ($('footer-features')) {
		var elements = $('footer-features').getElements('li');
		equalizeColumns(elements);
	}

	// set up article page
	if ($('news-article-container')) { setArticle();}
	
	// set up home page
	if ($('news-home-container')) {		
		
		// set home page tabs		
		setHomeTabs();
		//setHomeNewsNow();

		// set feature videos
		setHomeFeaturedVideo();
		
		// set special reports
		setHomeSpecialReports();		
	}
		
	// set up most popular box
	if($('sidebar-latest-box')) { setSidebarLatest(); }
	
	// set business switcher box
	if($('sidebar-business-switcher-box')) { setBusinessSwitcherBox(); }
	
	// set sidebar content sliders
	if($$('.sidebar-carousel').length > 0) { setSidebarCarousels(); }
	
	// set low-res galleries
	if($$('.news-gallery-regular').length > 0) { setGalleriesRegular(); }

	// set up data tables
	if($$('.data-table').length > 0) { setDataTables();	}
	
	// set up search
	if($('search-form') && $('search-text') && !$('news-search-results')){
		
		$('search-form').addEvent('submit', function(event){	
			event.stop();	
			doSearch();	
		});
	
		$('search-form').getFirst('a').addEvent('click', function(event){	
			event.stop();	
			doSearch();	
		});	
		
		var self = this;
		var urlBase = "/sitesearch/select/";
		var searchInput ='search-text';
		if(typeof(Autocompleter) != "undefined")
		{
			Autocompleter.Base.implement({
				options: {
					postVarPrefix: 'lc_title'
				}
			});
			new Autocompleter.JsonP($(searchInput), urlBase+"?",
			{
				postVar: 'facet.prefix',
				jsonpOptions: {
					data: {
						'q':'*:*',
						'omitHeader': true,
						'indent':'on',
						'facet':'on',
						'facet.limit':10,
						'facet.mincount':1,
						'facet.field':'lc_title',
						'wt':'json',
						'rows':0,
						'json.nl':'arrarr',
						'json.wrf': 'Request.JSONP.request_map.request_0'
					}
				},
				minLength: 3,
				filter: function(resp) {
					try {
						return resp.facet_counts.facet_fields.lc_title;
					} catch(e){'filterResponse error: ', dbug.log(e)}
				},
				injectChoice: function(choice) {
					if(! choice)return;
					var el = new Element('li');
					var slink = new Element ("a").inject(el);
					slink.set('html', this.markQueryValue(choice[0]));
					slink.set('rel', choice[1]);
					if(parseInt(choice[1])>1){
						slink.addEvent('click',function(event){
							event.stop();
							this.formSubmit(choice[0])
						}.bind(this));
					}else{
						slink.addEvent('click',function(event){
							event.stop();
							new Request.JSON({
								url : urlBase+'?wt=json&rows=1&q=lc_title:"'+encodeURIComponent(choice[0]).toLowerCase()+'"',
								onComplete : function(obj) {
									if(obj && obj.response && obj.response.docs && obj.response.docs[0] && obj.response.docs[0].url){
										location.href = obj.response.docs[0].url.substring(obj.response.docs[0].url.indexOf('rte.ie')+6)
									}
								}
							}).send();
						});
					}
					el.inputValue = choice[0];
					this.addChoiceEvents(el).inject(this.choices);
				}
			});
		}
	}
	
});














