window.addEvent('domready', function() {
  // Set the width and padding of each thumbnail.
  // If we're in Fatwire's InSite editing mode, we need to take into account
  // the width of the InSite bar (which is wider than the thumbnail...)
  if (checkFatwireInsiteMode()) {
    nb_thumbnail = 4;
    thumbnail_size = 215;
    thumbnail_padding = 0;
  } else {   // Normal mode
    nb_thumbnail = 8;
    thumbnail_size = 87;
    thumbnail_padding = 13;
  }

  // If we're in Fatwire's InSite editing mode, the carousel needs to be
  // higher to allow for the extra editing controls
  if (checkFatwireInsiteMode()) {
      $('gallery').style.height = '120px';
      $('carousel-container').style.height = '120px';
  }

	gallery_size = 0;
	// Check if there are elements in the gallery, and hide it otherwise,
	// unless we're in Fatwire InSite mode (in which case it should always
	// be displayed to allow addition of the first element)
	var gallery_items = $$('#gallery li');
	if (gallery_items.length > 0 || checkFatwireInsiteMode()) {
	  $('text-area').className='with-gallery';
	  $$('.scroller').setProperty('id','with-gallery');
	  $('gallery').setStyle('opacity','0.9');  
	  $('carousel').setStyle('left','0px');  
	  gallery_items.each(initialise);
	  $('carousel').setStyle('width',gallery_size+'px');
          createCentralPictureStructure();
	  var buttonPrevious = new Element('img',{src:'/common/images/news/previous_off.jpg', id:'previous-button'});
	  buttonPrevious.setStyle('position','absolute');
	  buttonPrevious.setStyle('top','1px');
	  buttonPrevious.setStyle('left','14px');
	  buttonPrevious.setStyle('cursor','pointer');
	  buttonPrevious.setStyle('opacity','0.9');
	  buttonPrevious.inject($('gallery'));
	  
	  if ($$('ul#carousel li').length <= nb_thumbnail) {
	  	var buttonNext = new Element('img',{src:'/common/images/news/next_off.jpg', id:'next-button'});
	  }
	  else {
	  	var buttonNext = new Element('img',{src:'/common/images/news/next_on.jpg', id:'next-button'});
	  	buttonNext.addEvent('click',advanceGallery);
	  }
	  buttonNext.setStyle('position','absolute');
	  buttonNext.setStyle('top','1px');
	  buttonNext.setStyle('right','5px');
	  buttonNext.setStyle('cursor','pointer');
	  buttonNext.inject($('gallery'));
	  buttonNext.setStyle('opacity','0.9');
	}
	else{
	  $('text-area').className='without-gallery';
	  $$('.scroller').setProperty('id','without-gallery');
	}

	new MooScroller($('scroll'), $('scrollKnob'), {
		mode: 'vertical',
		scrollLinks: {
			forward: $('scrollForward'),
			back: $('scrollBack')
		}
	});
  $('knobImg').setStyles({
	'position':'absolute',
	'height': '100%',
	'width':'15px'
  });
  $('knob_center').setStyles({
	'position':'absolute',
	'top':'50%',
	'left':'50%',
	'margin-top':'-3px',
	'margin-left':'-2px'
  });
  if($('scrollKnob').getStyle('height').toInt()==235){
	$('scrollKnob').setStyle('display','none');
	$('scrollarea').setStyle('opacity','0.5');
  }

  var buttonClosePanel = new Element('img',{src:'/common/images/news/btn_close_panel.gif', id:'text-area-button'});
  buttonClosePanel.setStyle('position','absolute');
  buttonClosePanel.setStyle('left','8px');
  buttonClosePanel.setStyle('top','29px');
  buttonClosePanel.setStyle('cursor','pointer');
  buttonClosePanel.inject($('text-area'));
  buttonClosePanel.addEvent('click',closePanel);

});

function closePanel() {
  this.removeEvent('click',closePanel);
  $('text-area').set('morph',{'duration':800,'onComplete': function () {
												   $('text-area-button').setProperty('src','/common/images/news/btn_open_panel.gif');
												   $('text-area-button').addEvent('click',openPanel);
											}});
  $('text-area').morph({'margin-right':'-232px'});
}

function openPanel() {
  this.removeEvent('click',openPanel);
  $('text-area').set('morph',{'duration':800,'onComplete': function () {
												   $('text-area-button').setProperty('src','/common/images/news/btn_close_panel.gif');
												   $('text-area-button').addEvent('click',closePanel);
											}});
  $('text-area').morph({'margin-right':''});
}

function advanceGallery() {
  $('next-button').removeEvent('click',advanceGallery);
  $('previous-button').removeEvent('click',backGallery);
  var newMargin = (($('carousel').getStyle('left').toInt())- thumbnail_size-thumbnail_padding)+'px';
  $('carousel').set('morph',{'duration':500, 'onComplete': end_advanceGallery});
  $('carousel').morph({'left':newMargin}); 
}

function end_advanceGallery() {
  var pos = $('carousel-container').getStyle('width').toInt() +
            Math.abs($('carousel').getStyle('left').toInt());
  if (pos + thumbnail_size + thumbnail_padding < $('carousel').getStyle('width').toInt()) {
    $('next-button').addEvent('click',advanceGallery);
    $('next-button').setProperty('src','/common/images/news/next_on.jpg');
  }
  else{
    $('next-button').setProperty('src','/common/images/news/next_off.jpg');
  }
  $('previous-button').addEvent('click',backGallery);
  $('previous-button').setProperty('src','/common/images/news/previous_on.jpg');
}

function backGallery() {
  $('previous-button').removeEvent('click',backGallery);
  $('next-button').removeEvent('click',advanceGallery);
  var newMargin = (($('carousel').getStyle('left').toInt())+ thumbnail_size+thumbnail_padding)+'px';
  $('carousel').set('morph',{'duration':500, 'onComplete': end_backGallery});
  $('carousel').morph({'left':newMargin}); 
}

function end_backGallery() {
  if ($('carousel').getStyle('left').toInt() < 0) {
    $('previous-button').addEvent('click',backGallery);
    $('previous-button').setProperty('src','/common/images/news/previous_on.jpg');
  }
  else{
    $('previous-button').setProperty('src','/common/images/news/previous_off.jpg');
  }
  $('next-button').addEvent('click',advanceGallery);
  $('next-button').setProperty('src','/common/images/news/next_on.jpg');
}
  
function initialise(item,index) {
  // Replace the link with a call to our function
  item.getElement('a').href = "javascript:void(0)";
  if (item.hasClass('GalleryImage')) {
    item.addEvent('click', displayGalleryImage);
  }
  
  if (item.hasClass('GalleryVideo')) {
    item.addEvent('click', displayGalleryVideo);
  }  
  
  gallery_size += thumbnail_size+thumbnail_padding;
  var thumbnail = item.getElement('img.thumbnail');
  item.getElement('img.thumbnail').setStyle('opacity',0.5);
  item.addEvent('mouseover',lessOpacity);
  item.addEvent('mouseout',moreOpacity);
}

function lessOpacity() {
  this.getElement('img.thumbnail').setStyles({
	'opacity':1,
	'border':'solid 1px white'
  });
  this.setStyle('padding-right','11px');
}

function moreOpacity() {
  this.getElement('img.thumbnail').setStyles({
	'opacity':0.5,
	'border':''
  });
  this.setStyle('padding-right','13px');
}

function createCentralPictureStructure() {
	$('central_image_div').morph({'opacity':0});
	$('shadow_div').setStyle('opacity', 0.6);
}

function displayGalleryImage() {
	// Set the link, if one was defined
	$('central_video_div').setStyle('opacity', 0);
	$('central_image_div').setStyle('opacity', 0);
	var linkEl = this.getElement('.ExternalLink');
	if (linkEl == null) {
		$('central_image_link').href = 'javascript:void(0);';
		$('central_button_image_link').href = 'javascript:void(0);';
		$('central_link_button').setStyle('display', 'none');
	} else {
		$('central_image_link').href = linkEl.href;
		$('central_button_image_link').href = linkEl.href;
		$('central_link_button').setStyle('display', 'block');
	}
	
	var bigImgSrc = this.getElement('.bigpicture').src; 
	// Check if an image is already displayed, and fade it out if so
	if ($('shadow_div').getStyle('display') == 'block') {
		// TODO: Implement fadeout
	}
		
	$('central_image').src = bigImgSrc;
	$('central_image_div').setStyle('opacity', 0);
	$('central_image_div').setStyle('display', 'block');
	$('central_image_div').set('morph',{'duration': 250,'onComplete':function(){
		$('shadow_div').setStyle('display', 'block');
	}}).morph({
		'opacity' : 1
	});		
	$('central_image_div').addEvent('click', closeImage);
	$('shadow_div').addEvent('click', closeImage);	
}

function displayGalleryVideo() {
	var videoPath = this.getElement('.newsItemVideoPath').firstChild.nodeValue;
	// This path is going to passed as a Flashvar, so the & must be escaped
	videoPath = videoPath.replace(/&/g, "%26");
	var videoTitle = this.getElement('.newsItemVideoTitle');
	
	$('central_video_div').setStyle('opacity', 0);
	$('central_image_div').setStyle('opacity', 0);
	$('central_video_div').setStyle('display', 'block');
	$('central_video_div').set('morph',{'duration':250,'onComplete':function(){
		$('shadow_div').setStyle('display', 'block');
	}}).morph({
		'opacity' : 1
	});
	
	var newDiv = document.createElement('div');
    newDiv.id = 'embedvideo';
    $('central_video').appendChild(newDiv);
	
	var flashvars = {
		fv_videopath: videoPath,
		fv_videotitle: videoTitle.get('html'),
		fv_autostart: true
	};
	var params = {
		align: "middle",
		salign: "TL",
		allowScriptAccess: "always",
		loop: "false",
		menu: "false",
		quality: "high",
		scale: "noScale",
		allowFullScreen: "true",
		wmode: "window"
	};
	var attributes = {
		id: "flashmain",
		name: "flashmain"
	};
	swfobject.embedSWF("/common/swf/modules/appmediaplayerstandalone.swf", "embedvideo", "401", "367", "9.0.45.0", "/common/swf/expressinstall.swf", flashvars, params, attributes);

	$('central_video_div').addEvent('click', closeVideo);		
	$('shadow_div').addEvent('click', closeVideo);
	$('shadow_div').setStyle('display', 'block');
}

function closeImage(){
	$('central_image_div').set('morph',{
		'duration': 250,
		'onComplete':function(){
        	$('shadow_div').setStyle('display', 'none');
        	$('shadow_div').removeEvent('click', closeImage);		
		}
	}).morph({
		'opacity' : 0
	});
}

function closeVideo(){
	$('central_video_div').set('morph',{
		'duration': 250,
		'onComplete':function(){
        	$('shadow_div').setStyle('display', 'none');
			$('central_video').removeChild($('flashmain'));
        	$('shadow_div').removeEvent('click', closeVideo);		
		}
	}).morph({
		'opacity' : 0
	});
}
