var Ticker = new Class({
  // Define options
  options: {
    toggleButton: false,
    interval: 10000
  },

  initialize: function(containerId,options) {

    // Set container div
    this.container = $(containerId);
    // Set options
    this.setOptions(options);
    this.interval = this.options.interval;
    this.toggleButton = (this.toggleButton)?$(this.options.toggleButton):false;

    this.textEl = $$('div#newsticker span.news_text')[0];
    this.autoPlayCounter = 0;

    var url = "/TNC_Router.php";

    var req = new Ajax(url, {
    	method:'post',
    	data:{controller:'announcements', action:'index'},
    	onComplete: this.loadResults.bind(this)
    });
    req.request();

    // Create toggle button when ID is supplied with options
    if (this.toggleButton != false) {
      this.toggle_button = new Element('a').setProperties({
        'href': '#',
        'id': 'togglenewsticker'
      }).setHTML('Toggle').addEvent('click',this.toggleTicker.bind(this));

      this.toggleButton.adopt(this.toggle_button);
    }


    this.timer = this.displayItem.periodical(this.interval,this);
  },

  loadResults: function(resp) {

		this.items = Json.evaluate(resp);

    this.totalItems = this.items.length;

    if (this.totalItems == 0) {
      return false;
    }

    this.displayItem();
  },

  displayItem: function() {
		this.textEl.setHTML(this.items[this.autoPlayCounter].header);
		$('newsticker_content').setHTML(this.items[this.autoPlayCounter].msg);

		// reset counter if it reaches the end of the data array
		if (this.autoPlayCounter+1 == this.totalItems) {
			this.autoPlayCounter = 0;
		} else {
			this.autoPlayCounter++;
		}
  }

});
Ticker.implement(new Options);

/*
* Class to manage link behaviour or archived streams
*/
var TERENA_streamArchive = new Class({
	options:{
	
	},
	
	initialize: function(containerId, options){
    // Set container div
    this.container = $(containerId);
    // Set options
    this.setOptions(options);    
    // set variables
		this.counter = {};
		
		this.dates = [
			'2008-05-19',
			'2008-05-20',
			'2008-05-21',
			'2008-05-22'
		];
		
    var url = "/TNC_Router.php";

    var req = new Ajax(url, {
    	method:'post',
    	data:{controller:'streams', action:'getArchiveM'},
    	onComplete: this.loadResults.bind(this)
    });
    req.request();	
	},
	
	loadResults: function(resp){
		this.items = Json.evaluate(resp);
		
		// build counter object
		for (var i=0, il=this.dates.length; i<il; i++) {
			// check for every date how many streams there are
			// set the internal counter object to hold data about current and total nr of streams
			// every date represented by a DOM element has its own counter property within the object
			this.counter[this.dates[i]] = { 
				current:0, 
				total:this.items[this.dates[i]].length
			};
		}
		
		this.renderNav();
	},
	
	renderNav: function(){
		// add events for every DOM element containing the streams
		var that = this;
		$$('#videostreams div.stream_item_container').each(function(el, i){
			// get date belonging to this element and set it as a property of this element
			// see next loop
			el['terena_stream_date'] = that.dates[i];
			el.addEvents({
				'mouseenter': function(e){
					var e = new Event(e);	
					// show navigation links
					el.getElements('a.stream_nav').setStyle('visibility', 'visible');
				},
				'mouseleave': function(e){
					e = new Event(e);
					// hide navigation links
					el.getElements('a.stream_nav').setStyle('visibility', 'hidden');
				}			
			});
		});
		
		// add event listeners to links
		var that = this;
		$$('#videostreams div.stream_item_container a.stream_nav').each(function(el){			
			// add actual event listener to elements, with scope correction and pass direction and date arguments as an object 
			el.addEvent('click', that.navHandler.bindWithEvent(that, {
				dir: (el.hasClass('prev'))?'prev':'next', // direction to browse archive
				date: el.parentNode.terena_stream_date, // which archive to browse (date property of parent node)
				el: el.parentNode
			}));
		});
		
	},

	navHandler: function(e, props){
		var e = new Event(e);
		e.stop();			

		// item of a particular date
		var itemday = this.items[props.date];
		// direction of this particular date
		var dir = props.dir;
		
		if (dir == 'next') {
			// reset counter if total is reached
			if (this.counter[props.date].current+1 == this.counter[props.date].total) {
				this.counter[props.date].current = -1;
			}		
			// increase counter of the date belonging to this element
			this.counter[props.date].current++;
		} else {
			// reset counter if minimum is reached
			if (this.counter[props.date].current == 0) {
				this.counter[props.date].current = this.counter[props.date].total;
			}				
			// decrease counter
			this.counter[props.date].current--;
		}
		
		// show next or previous item
		this.displayItem(itemday[this.counter[props.date].current], props.el);		
		
	},		
	
	displayItem: function(item, el){

		// get clone element and original element
		var clone = el.getElement('div.stream_clone');
		var orig = el.getElement('div.stream_orig');
		
		// set attributes and contents of elements within clone
		clone.getElements('a').setProperty('href', '/media/archive.php?stream='+item.sess_id+'&quality=hi');
		clone.getElement('img').setProperties({
			src: '/gfx/photos/archive/stream_'+item.sess_id+'.jpg',
			alt: item.title
		});
		clone.getElement('a.stream_session_title').setText(item.title);		
		
		clone.setStyle('display', 'block');
		orig.setStyle('display', 'none');

		
		// add/remove classes		
		orig.removeClass('stream_orig');
		orig.addClass('stream_clone');		
		clone.removeClass('stream_clone');
		clone.addClass('stream_orig');		
	}


});
TERENA_streamArchive.implement(new Options);


window.addEvent('domready', function() {

	//
	//Control default value of searchbox
	///
	/*
		var _el = $('searchbox');
		var _val = 'search';
		_el.value = _val;
		_el.addEvents({
			'focus': function(){
				_el.value = '';
			},
			'blur': function(){
				if($('searchbox').value){ 
					_el.value = $('searchbox').value;
				}
				else{
					_el.value = _val;
				}
			}
		});
		*/
	if ($('nextimg')) {

		var myTicker = new Ticker('newsticker', {interval:10000});
		var mySlide = new Fx.Slide('newsticker_content', {duration: 200});
		var divContent = $('newsticker_content');
		var fxContainer = new Fx.Styles('newsticker', {duration:0, wait:false});
	
		$('nextimg').addEvent('click', function(e){
			var me = new Event(e);
			me.stop();
	
			if (this.hasClass('expanded')) {
				this.removeClass('expanded');
				this.src = '/gfx/icons/next.gif';
				mySlide.slideOut().chain(function(){
					fxContainer.start({
						'border-bottom-color': '#C8C8C8'
					});
				});
			} else {
				this.addClass('expanded');
				this.src = '/gfx/icons/next_vert.gif';
				divContent.style.display = 'block';
				mySlide.slideIn()
				fxContainer.start({
					'border-bottom-color': '#F7F8F8'
				});
	
			}
		});
	
	}

	/*
	* If accordion element exists, apply Accordion class
	*/
	if ($('accordion')) {
		$$('div#accordion h2.toggler').addClass('linkify');
		var accordion = new Accordion('h2.atStart', 'p.atStart', {
			opacity: false,
			onActive: function(toggler, element){
				toggler.setStyle('color', '#ff3300');
			},

			onBackground: function(toggler, element){
				toggler.setStyle('color', '#222');
			}
		}, $('accordion'));
	}
	
	if ($('newsaccordion')) {
		$$('span.toggler').setStyle('display', 'inline');
		
		var accordion = new Accordion('span.atStart', 'div.atStart', {
			opacity: false,
			onActive: function(toggler, element){	
				
				toggler.setStyle('display', 'none');
				return false;
			},
			onBackground: function(toggler, element){
				toggler.setStyle('display', 'inline');
			}
		}, $('newsaccordion'));	
		
		// get anchor element by stream_id className. This is the anchor currently playing
		var _e = $$('div.'+window.location.hash.substring(1));
		if (_e.length != 0) {
			// Display the container of the node that has the anchor in it,
			// effectively showing the section that has the active anchor.
			accordion.display(_e[0]);	
		}
			
	}

	if ($('accordion_archive')) {
		var accordion = new Accordion('h2.atStart', 'ul.atStart', {
			opacity: false,
			onActive: function(toggler, element){
				toggler.setStyle('color', '#ff3300');
			},

			onBackground: function(toggler, element){
				toggler.setStyle('color', '#222');
			}
		}, $('accordion_archive'));

		var flashvars =
		{
			width:              '520',
			height:             '395',			
			shownavigation:     'true',
			showstop:           'true',
			showdigits:         'false',
			enablejs:           'true',
			searchbar:					'false',
			frontcolor:         '0xFFFFFF',
			backcolor:          '0x535250',
			lightcolor:         '0x000000',
			screencolor:        '0x000000',
			logo:								'/gfx/logos/terena_logo.png',
			plugins:						'sharing-1'
		};
		
		var params =
    {
			allowscriptaccess:  'always',
			allowfullscreen:    'true',
			quality:						'high'
		};
		var attributes =
		{
			id:                 'movie',
			name:               'movie',
			wmode:				'transparent' 
		};	
				
		if (swfobject.getQueryParamValue('stream')) {
			var stream = swfobject.getQueryParamValue('stream');		
			var req = new Ajax('/TNC_Router.php', {
				method:'post',
				data:{controller:'streams', action:'getStreamFile', stream:stream},
				onComplete: function(resp){
					flashvars.autostart = 'true';					
					flashvars.title = 'TNC2009 Session '+stream;
					if (Json.evaluate(resp)) {
						// stream video using TERENA streaming server, updated nov 2009						
						flashvars.file = 'tnc2009/'+Json.evaluate(resp);
						flashvars.streamer = 'rtmp%3a%2f%2fmedia.terena.org/fastplay';
						flashvars['sharing.code'] = '%3Cembed+%0Asrc%3D%22http%3A%2F%2Fdeveloper.longtailvideo.com%2Fplayer%2Ftrunk%2Fas3%2Fplayer.swf%22+%0Aflashvars%3D%22file%3Dtnc2009%2F'+Json.evaluate(resp)+'%26streamer%3Drtmp%3A%2F%2Fmedia.terena.org%2Ffastplay%26autostart%3Dtrue%22+%0Awidth%3D%22520%22+%0Aheight%3D%22395%22%0A%2F%3E';
					} else {
						// stream video using organiser streaming server
						//flashvars.file = 'rtmp%3a%2f%2fstream.tnc2009.rediris.es/recordtnc/mp4/';
						//flashvars.id = 'mp4:'+stream+'.sdp.mp4';
					}
					// only add swfobject if return is successfull
					swfobject.embedSWF('/javascript/mediaplayer/player.swf', 'mediacontent_container', '520', '395', '8.0.0', false, flashvars, params, attributes);
				}
			});
			req.request();			
		}
	
		
		// get anchor element by stream_id className. This is the anchor currently playing
		var _e = $$('#accordion_archive ul.element li a.rst_'+stream);
		if (_e.length != 0) {
			// Display the container of the node that has the anchor in it,
			// effectively showing the section that has the active anchor.
			accordion.display(_e[0].parentNode.parentNode);	
		}
		
	}


	if ($('mediadropdown')) {
		$('mediadropdown').addEvent('change', function(event){
			var ev = new Event(event);
			ev.stop();
			ev.target.form.submit();
		});
	}
	
	if ($('promovid')) {
		var flashvars =
		{
			streamer:						'rtmp://media.terena.org/fastplay',
			file:								'tnc2010/promo.mp4',
			stretching:					'exactfit',
			autostart:					'true',
			shownavigation:     'true',
			showstop:           'true',
			showdigits:         'false',
			enablejs:           'true',
			searchbar:					'false',
			frontcolor:         '0xFFFFFF',
			backcolor:          '0x535250',
			lightcolor:         '0x000000',
			screencolor:        '0x000000',
			logo:								'/gfx/logos/terena_logo.png',
		};
		
		var params =
    {
			allowscriptaccess:  'always',
			allowfullscreen:    'true'
		};
		var attributes =
		{
			id:                 'movie',
			name:               'movie',
			wmode:				'transparent'
		};	
				
		swfobject.embedSWF('/javascript/mediaplayer/player.swf', 'mediacontent_container', '576', '333', '8.0.0', false, flashvars, params, attributes);
	
	}


	if ($('medialist')) {
		var flashvars =
		{
			width:              '520',
			height:             '395',
			file:               'rtmp://130.206.241.1/livetnc/',
			image:              '/gfx/streams/presidents_keynote.jpg',
			shownavigation:     'true',
			showstop:           'true',
			showdigits:         'false',
			enablejs:           'true',
			searchbar:					'false',
			frontcolor:         '0xFFFFFF',
			backcolor:          '0x535250',
			lightcolor:         '0x000000',
			screencolor:        '0x000000'
		};
		if (swfobject.getQueryParamValue('stream')) {
			var stream_nr = swfobject.getQueryParamValue('stream');			
			// stream id is a concatenated string consisting of 'stream<number>_<hi or low>'
		  // flashvars.id = 'stream'+stream_nr+'_hi';
		  flashvars.id = swfobject.getQueryParamValue('stream')+'.sdp';
			flashvars.autostart = 'true' // uncomment if you want to show preview picture instead
		}

		var params =
    {
			allowscriptaccess:  'always',
			allowfullscreen:    'true'
		};
		var attributes =
		{
			id:                 'movie',
			name:               'movie'
		};
		// only add swfobject if there is a stream id supplied
		if (stream_nr) {
			swfobject.embedSWF('mediaplayer/mediaplayer.swf', 'mediacontent_container', '520', '395', '8.0.0', false, flashvars, params, attributes);
		}
	}
	
	// CORE feedback 
	if ($('core_feedback')) {		
	
		$$('#programme div.ratebox input.feedbackchk').each(function(el, i){
			el.addEvent('click', function(){
		    var req = new Ajax('feedback_ajax.php', {
		    	method:'post',
		    	data:{feedback:el.id},
		    	onComplete: function(r){
		    		var res = Json.evaluate(r);
		    		if (res.res) {
		    			if (res.pass) {
		    				var box = $('core_feedback_message');
		    				box.setStyle('display', 'block');
		    				box.setText("Thank you for supplying your feedback, your secret password is: '"+res.pass+"'. Please continue with the feedback");
		    			}
							var fade = new Fx.Style(el.getParent().getParent(), 'opacity', {wait:false});							
							fade.set(.2);
							fade.start(1);
		    		}
		    	}
		    });
		    req.request();
			});
		});
		
		
		
  }
	

});

