/**
 * Clip-Player
 *
 * @package javascript
 *
 * @copyright Copyright &copy; 2010 handgestrickt netzwerk
 * @author Stefan Jelner <stefan.jelner@gmx.de>
 * @version $Id: clipplayer.js 62 2010-03-05 16:16:03Z jelner $
 */

//Alias für FLASH zum direkten Aufruf per ExternalInterface.call
var kcClipPlayer_highlight = function(index) { kcClipPlayer.getInstance().highlight(index) };
var kcClipPlayer_setProgress = function(percent) { kcClipPlayer.getInstance().setProgress(percent) };
var kcClipPlayer_totalProgress = function(duration) { kcClipPlayer.getInstance().totalProgress(duration) };
var kcClipPlayer_clipComplete = function() { kcClipPlayer.getInstance().clipComplete() };

var kcClipPlayer = new Singleton({
	'data': null,
	'navi_ul': null,
	'video_txt_ul': null,
	'video_txt_lis': null,
	'swiff': null,
	'swiff_el': null,
	'playing': false,
	'current': 0,
	'buttons': {
		'playpause': false,
		'stop': false,
		'arrow': false
	},
	'progress': {
		'min': -244,
		'max': -12,
		'width': 246,
		'el1': false,
		'el2': false,
		'dragActive': false
	},
	'infobar': {
		'duration': 0,
		'stepEl': false,
		'curEl': false,
		'durEl': false
	},
	'volvoice': {
		'min': -86,
		'max': -8,
		'width': 87,
		'el1': false,
		'el2': false
	},
	'volmusic': {
		'min': -86,
		'max': -8,
		'width': 87,
		'el1': false,
		'el2': false
	},
	'playall': {
		'el': false,
		'value': true
	},
	'hideinactive': {
		'el': false,
		'value': false
	},

	'initialize': function() {
		/*
		 * Zuverlässige Browserweiche für IE 6+7+8
		 */
		if(Browser.Engine.trident) {
			Browser.Engine.trident4 = false;
			Browser.Engine.trident5 = false;
			Browser.Engine.trident6 = false;
			var engine = document.createElement('div');
    		engine.innerHTML = '<!--[if IE 6]>4<![endif]--><!--[if IE 7]>5<![endif]--><!--[if IE 8]>6<![endif]-->';
    		var engine = engine.innerHTML.charCodeAt(0) == 60 ? false : parseInt(engine.innerHTML);
    		if(engine) eval('Browser.Engine.trident'+engine+' = true;');
		};
	},

	'buildControls': function() {
		var _this = this;

		//Stop-Knopf
		this.buttons.stop = $$('#vidstop a')[0];
		if($chk(this.buttons.stop)) {
			this.buttons.stop.addEvent('click',function(e) {
				this.blur();
				new Event(e).preventDefault();
				if($chk(_this.swiff_el)) {
					Swiff.remote(_this.swiff_el,'stopClip');
					_this.playing = false;
					_this.togglePlayPause();
					_this.setProgress(0);
				};
			});
		};

		//Play/Pause-Knopf
		this.buttons.playpause = $$('#vidplaypause')[0];
		if($chk(this.buttons.playpause)) {
			this.buttons.playpause.getChildren()[0].addEvent('click',function(e) {
				this.blur();
				new Event(e).preventDefault();
				if($chk(_this.swiff_el)) {
					if(_this.playing) {
						Swiff.remote(_this.swiff_el,'pauseClip');
						_this.playing = false;
					} else {
						Swiff.remote(_this.swiff_el,'playClip');
						_this.playing = true;
					};
					_this.togglePlayPause();
				};
			});
		};

		//Play-Knopf über Video
		this.buttons.arrow = $('vid_start_icon');
		if($chk(this.buttons.arrow)) {
			this.buttons.arrow.addEvent('click',function(e) {
				this.blur();
				new Event(e).preventDefault();
				Swiff.remote(_this.swiff_el,'playClip');
				_this.playing = true;
				_this.togglePlayPause();
			});
		};

		//Video-Verlauf Statusbalken
		this.progress.el1 = $('vidverlauf');
		this.progress.el1.addEvent('click',function (e){
			var percent = ((new Event(e).page.x-this.getPosition().x)/(_this.progress.width/100));
			_this.setProgress(percent);
			Swiff.remote(_this.swiff_el,'seekClipPercent',percent,_this.playing);
		});
		this.progress.el2 = new Drag('vidverlaufklotz',{
			modifiers: {x: 'left', y: false},
			limit: {x: [0,(this.progress.max-this.progress.min)], y: false},
			onComplete: function(drag,e) {
				Swiff.remote(_this.swiff_el,'seekClipPercent',(drag.getStyle('left').toInt()/((_this.progress.max-_this.progress.min)/100)),_this.playing);
				_this.progress.dragActive = false;
			},
			onDrag: function(drag,e) {
				_this.progress.el1.setStyle(
					'background-position',
					(_this.progress.min+drag.getStyle('left').toInt())+'px 0px'
				);
			},
			onStart: function() { _this.progress.dragActive = true; },
			onCancel: function() { _this.progress.dragActive = false; }
		});

		//Video Informationen unter Statusbalken
		this.infobar.stepEl = $('vid_step');
		this.infobar.curEl = $('vid_current');
		this.infobar.durEl = $('vid_duration');

		//Lautstärke Stimme
		this.volvoice.el1 = $('vidvolvoice');
		this.volvoice.el1.addEvent('click',function (e){
			var percent = ((new Event(e).page.x-this.getPosition().x)/(_this.volvoice.width/100));
			_this.setVolVoice(percent);
			Swiff.remote(_this.swiff_el,'setVolVoicePercent',percent);
		});
		this.volvoice.el2 = new Drag('vidvolvoiceklotz',{
			modifiers: {x: 'left', y: false},
			limit: {x: [0,(this.volvoice.max-this.volvoice.min)], y: false},
			onComplete: function(drag,e) {
				Swiff.remote(_this.swiff_el,'setVolVoicePercent',(drag.getStyle('left').toInt()/((_this.volvoice.max-_this.volvoice.min)/100)));
			},
			onDrag: function(drag,e) {
				_this.volvoice.el1.setStyle(
					'background-position',
					(_this.volvoice.min+drag.getStyle('left').toInt())+'px 0px'
				);
			}
		});

		//Lautstärke Musik
		this.volmusic.el1 = $('vidvolmusic');
		this.volmusic.el1.addEvent('click',function (e){
			var percent = ((new Event(e).page.x-this.getPosition().x)/(_this.volmusic.width/100));
			_this.setVolMusic(percent);
			Swiff.remote(_this.swiff_el,'setVolMusicPercent',percent);
		});
		this.volmusic.el2 = new Drag('vidvolmusicklotz',{
			modifiers: {x: 'left', y: false},
			limit: {x: [0,(this.volmusic.max-this.volmusic.min)], y: false},
			onComplete: function(drag,e) {
				Swiff.remote(_this.swiff_el,'setVolMusicPercent',(drag.getStyle('left').toInt()/((_this.volmusic.max-_this.volmusic.min)/100)));
			},
			onDrag: function(drag,e) {
				_this.volmusic.el1.setStyle(
					'background-position',
					(_this.volmusic.min+drag.getStyle('left').toInt())+'px 0px'
				);
			}
		});

		//Alle Abspielen-Knopf
		this.playall.el = $('vidplayall');
		if($chk(this.playall.el)) {
			this.playall.el.checked = this.playall.value;
			this.playall.el.addEvent('click',function(e) {
				this.blur();
				_this.playall.value = this.checked;
			});
		};

		//nicht Aktive Schritte ausblenden
		this.hideinactive.el = $('vidhideinactive');
		if($chk(this.hideinactive.el)) {
			this.hideinactive.el.checked = this.hideinactive.value;
			this.hideinactive.el.addEvent('click',function(e) {
				this.blur();
				_this.hideinactive.value = this.checked;
				_this.video_txt_lis.each(function(li) {
					if(_this.hideinactive.value) {
						if(li.hasClass('aktiv')) li.setStyle('display','block');
						else li.setStyle('display','none');
					} else {
						li.setStyle('display','block');
					};
				});
			});
		};

		return this;
	},

	'buildStepNavi': function() {
		if($chk(this.data)) {
			var _this = this;

			//Navigation aufbauen
			var navi = $('schrittenavi');
			var video_text = $('vid-txt');
			if($chk(navi) && $chk(video_text)) {
				this.navi_ul = new Element('ul');
				this.video_txt_ul = new Element('ul');
				navi.adopt(this.navi_ul);
				video_text.adopt(this.video_txt_ul);

				this.data.each(function(step,n) {
					_this.navi_ul.adopt(new Element('li').adopt(new Element('a',{
						'href': '#',
						'class': _this.stepNaviClass(n),
						'events': {
							'click': function(e) {
								this.blur();
								new Event(e).preventDefault();
								_this.setStep(n);
							}
						}
					}).adopt(
						new Element('dfn').set('text','{/literal}{$lang.step}{literal} '+(n+1))
					)));
				});
			};
		};
		return this;
	},

	'clipComplete': function() {
		if(this.playall.value) {
			this.setStep((this.current+1));
		} else {
			Swiff.remote(this.swiff_el,'stopClip');
			this.playing = false;
			this.togglePlayPause();
			this.setProgress(0);
		};
	},

	'highlight': function(index) {
		var _this = this;
		if($chk(this.video_txt_lis)) {
			this.video_txt_lis.each(function(li,index2) {
				if(index == index2) {
					li.addClass('aktiv');
					if(_this.hideinactive.value) li.setStyle('display','block');
				} else {
					li.removeClass('aktiv');
					if(_this.hideinactive.value) li.setStyle('display','none');
				};
			});
		};
	},

	'loadClip': function(step,autoPlay) {
		if(!$defined(autoPlay)) autoPlay = true;
		if(
			$chk(step) &&
			$chk(this.data) &&
			step < this.data.length &&
			$chk(this.data[step]) &&
			$chk(this.data[step].movie_clip) &&
			$chk(this.data[step].background_music)
		) {
			var vid_screen = $('vid_screen');
			if($chk(vid_screen)) {
				var secs = '';
				this.data[step].timelines.each(function(timeline) {
					secs += timeline.time_sek+',';
				});
				if(secs != '') secs = secs.substr(0,(secs.length-1));
				var relLocation = location.href;
				if(relLocation.match(/\.html/i)) relLocation = relLocation.replace(/[^\/]+$/,'');
				else if(!relLocation.match(/\/$/)) relLocation += '/';
				if(this.swiff_el) {
					Swiff.remote(this.swiff_el,'loadClip',relLocation+this.data[step].movie_clip,relLocation+this.data[step].background_music,secs,((autoPlay) ? 1 : 0));
				} else {
					this.swiff = new Swiff('fileadmin/swf/movie_player.swf',{
						width: 490,
						height: 276,
						vars: {
							movie_clip: relLocation+this.data[step].movie_clip,
							background_music: relLocation+this.data[step].background_music,
							timeline: secs,
							autoplay: ((autoPlay) ? 1 : 0)
						}
					});
					vid_screen.adopt(this.swiff);
					this.swiff_el = $(this.swiff.id);
					/*
					 * IE7 hat total ein Rad ab. Erst einmal muss man das Element mit Gewalt "aktivieren", wegen
					 * irgendwelcher Lizenzeinsparungen bei M$. Dann muss man das Element erneut mit nativen
					 * DOM-Methoden abfragen. Ansonsten hat man keine ExternalInterface-Funktionalitäten.
					 *
					 * Update 29.03.2010: IE8 macht auf bestimmten Maschinen das gleiche Theater!
					 */
					if((Browser.Engine.trident5 || Browser.Engine.trident6) && this.swiff_el) {
						var params = this.swiff_el.getElementsByTagName('param');
						var innerHTML = '';
						if($chk(params)) {
							$A(params).each(function(param) { innerHTML += param.outerHTML; });
						};
						this.swiff_el.outerHTML = this.swiff_el.outerHTML.replace('>','>'+innerHTML);
						this.swiff_el = document.getElementById(this.swiff.id);
					};
				};
				if(autoPlay) this.playing = true;
				else this.playing = false;
				this.togglePlayPause();
				this.setProgress(0);
			};
		};
	},

	'setStep': function(step,autoPlay) {
		if(!$defined(autoPlay)) autoPlay = true;
		if(
			$chk(step) &&
			$chk(this.data) &&
			step < this.data.length &&
			$chk(this.data[step]) &&
			$chk(this.data[step].timelines)
		) {
			var _this = this;
			//Daten einfügen
			this.video_txt_ul.empty();
			this.data[step].timelines.each(function(timeline,n) {
				li = new Element('li').adopt(
					new Element('a',{
						events: {
							'click': function(e) {
								this.blur();
								new Event(e).preventDefault();
								Swiff.remote(_this.swiff_el,'seekClipSec',timeline.time_sek,_this.playing);
							}
						}
					}).set(
						'html',
						(n+1)+'. '+timeline.description
					)
				);
				if(n == 0) {
					li.addClass('aktiv');
					if(_this.hideinactive.value) li.setStyle('display','block');
				} else {
					if(_this.hideinactive.value) li.setStyle('display','none');
				};
				_this.video_txt_ul.adopt(li);
			});
			this.video_txt_lis = this.video_txt_ul.getChildren();
			//Aktiven Punkt oben markieren
			var lis = this.navi_ul.getChildren();
			this.data.each(function(step2,n) {
				if($chk(lis[n]) && lis[n].get('tag') == 'li') {
					var link = lis[n].getFirst();
					if($chk(link) && link.get('tag') == 'a') {
						if(n == step) link.addClass(_this.stepNaviClass(n)+'_aktiv');
						else link.removeClass(_this.stepNaviClass(n)+'_aktiv');
					};
				};
			});
			//Im Infobar Schritt-Nummer ändern
			this.infobar.stepEl.set('html',(step+1));
			//Internen Zähler ändern
			this.current = step;
			//Clip laden
			this.loadClip(step,autoPlay);
		};
		return this;
	},

	'setData': function(data) {
		if($chk(data)) this.data = data;
		return this;
	},

	'setProgress': function(percent) {
		if($chk(this.progress.el1) && $chk(this.progress.el2) && !this.progress.dragActive) {
			var progress = (((this.progress.max-this.progress.min)/100)*percent);
			this.progress.el2.element.setStyle('left',progress);
			this.progress.el1.setStyle('background-position',(this.progress.min+progress)+'px 0px');
			if(this.infobar.duration > 0) {
				this.infobar.curEl.set('html',this.time2str(((this.infobar.duration/100)*percent)));
			};
		};
	},

	'setVolMusic': function(percent) {
		if($chk(this.volmusic.el1) && $chk(this.volmusic.el2)) {
			var volmusic = (((this.volmusic.max-this.volmusic.min)/100)*percent);
			this.volmusic.el2.element.setStyle('left',volmusic);
			this.volmusic.el1.setStyle('background-position',(this.volmusic.min+volmusic)+'px 0px');
		};
	},

	'setVolVoice': function(percent) {
		if($chk(this.volvoice.el1) && $chk(this.volvoice.el2)) {
			var volvoice = (((this.volvoice.max-this.volvoice.min)/100)*percent);
			this.volvoice.el2.element.setStyle('left',volvoice);
			this.volvoice.el1.setStyle('background-position',(this.volvoice.min+volvoice)+'px 0px');
		};
	},

	'stepNaviClass': function(value) {
		return 's'+((value < 9) ? '0' : '')+(value+1);
	},

	'time2str': function(seconds) {
		seconds = parseInt(seconds);
		var minStr = String(parseInt(seconds/60));
		var secStr = String(parseInt(seconds%60));
		return ((minStr.length == 1) ? '0' : '')+minStr+':'+((secStr.length == 1) ? '0' : '')+secStr;
	},

	'togglePlayPause': function() {
		if($chk(this.buttons.playpause) && $chk(this.buttons.arrow)) {
			if(this.playing) {
				this.buttons.playpause.removeClass('vidplay');
				this.buttons.playpause.addClass('vidpause');
				this.buttons.arrow.setStyle('display','none');
			} else {
				this.buttons.playpause.addClass('vidplay');
				this.buttons.playpause.removeClass('vidpause');
				this.buttons.arrow.setStyle('display','block');
			}
		};
	},

	'totalProgress': function(duration) {
		this.infobar.duration = duration;
		this.infobar.durEl.set('html',this.time2str(duration));
	}
});
