var control_version_flash;

//on cache les select pour eviter le bug que les select sur IE6 qui ne prend pas en compte les z-index
function hidden_select(){
	var selects = document.getElementsByTagName("select");
	var length = selects.length;
	for(var i = 0; i < length ; i++){
		selects[i].style.visibility = "hidden";
	}
}

function appear_select(){
	var selects = document.getElementsByTagName("select");
	var length = selects.length;
	for(var i = 0; i < length ; i++){
		selects[i].style.visibility = "visible";
	}
}

	
var Videobox = {


	init: function (options) {
		// init default options
		this.options = Object.extend({
			resizeDuration: 400,	// Duration of height and width resizing (ms)
			initialWidth: 250,		// Initial width of the box (px)
			initialHeight: 250,		// Initial height of the box (px)
			defaultWidth: 425,		// Default width of the box (px)
			defaultHeight: 350,	// Default height of the box (px)
			animateCaption: true,	// Enable/Disable caption animation
			variable: 'file',
			navigateur: '',
			flvplayer: '/modeles/player.swf',
			//flvplayer: 'swf/flvplayer.swf'
			init: function (){
			    if(control_version_flash != undefined){
					if(!hasReqestedVersion && navigator.userAgent.match(/iPad/i) == null){
						alert('Votre flash player n\'est pas à jour. Il est possible que vous ayez des problèmes pour visionner la vidéos');
						this.variable = 'qt';//attention on doit charger d'autre variable suivant le lecteur
						this.flvplayer = '/modeles/flvlecteur.swf';
						if(navigator.userAgent.match('MSIE 6'))
							this.navigateur = 'IE6';
						else{
							this.navigateur = 'Firefox IE7';
						}
						
					}
				}
				else{
					if(navigator.userAgent.match('MSIE 6')){
						this.variable = 'qt';//attention on doit charger d'autre variable suivant le lecteur
						this.navigateur = 'IE6';
						this.flvplayer = '/modeles/flvlecteur.swf';
					}
					else{
						this.variable = 'file';
						this.navigateur = 'Firefox IE7';
						this.flvplayer = '/modeles/player.swf';
					}
				}
			}
		}, options || {});

		this.anchors = [];
		$A($$('a')).each(function(el){
			if(el.rel && el.href && el.rel.test('^vidbox', 'i')) {
				el.addEvent('click', function (e) {
          e = new Event(e);
          e.stop();
          this.click(el);
				}.bind(this));
				this.anchors.push(el);
			}
    }, this);

		this.overlay = new Element('div').setProperty('id', 'lbOverlay').injectInside(document.body);
		
		this.topContainer = new Element('div').setProperty('id', 'lbTopContainer').setStyle('display', 'none').injectInside(document.body);
		this.top = new Element('div').setProperty('id', 'lbTop').injectInside(this.topContainer);
		new Element('a').setProperties({id: 'lbCloseLink', href: '#'}).injectInside(this.top).onclick = this.overlay.onclick = this.close.bind(this);
		this.caption = new Element('div').setProperty('id', 'lbCaption').injectInside(this.top);
		this.number = new Element('div').setProperty('id', 'lbNumber').injectInside(this.top);
		
		this.center = new Element('div').setProperty('id', 'lbCenter').setStyles({width: this.options.initialWidth+'px', height: this.options.initialHeight+'px', marginLeft: '-'+(this.options.initialWidth/2)+'px', display: 'none'}).injectInside(document.body);

		/*this.bottomContainer = new Element('div').setProperty('id', 'lbBottomContainer').setStyle('display', 'none').injectInside(document.body);
		this.bottom = new Element('div').setProperty('id', 'lbBottom').injectInside(this.bottomContainer);*/
		//new Element('a').setProperties({id: 'lbCloseLink', href: '#'}).injectInside(this.bottom).onclick = this.overlay.onclick = this.close.bind(this);
		/*this.caption = new Element('div').setProperty('id', 'lbCaption').injectInside(this.bottom);
		this.number = new Element('div').setProperty('id', 'lbNumber').injectInside(this.bottom);*/
		//new Element('div').setStyle('clear', 'both').injectInside(this.bottom);

		var nextEffect = this.nextEffect.bind(this);
		this.fx = {
			overlay: this.overlay.effect('opacity', {duration: 500}).hide(),
			center: this.center.effects({duration: 500, transition: Fx.Transitions.sineInOut, onComplete: nextEffect}),
			//bottom: this.bottom.effect('margin-top', {duration: 400})
			top: this.top.effect('margin-top', {duration: 400})
		};

	},

	click: function(link) {
	
     		return this.open (link.href, link.title, link.rel);

	},
	open: function(sLinkHref, sLinkTitle, sLinkRel) {
		this.href = sLinkHref;
		this.title = sLinkTitle;
		this.rel = sLinkRel;
		this.position();
		this.setup();
		this.video(this.href);
		this.top = Window.getScrollTop() + (Window.getHeight() / 15);
		this.center.setStyles({top: this.top+'px', display: ''});
		//pour IE il n'arrive pas à prendre en compte Window.getScrollTop() ni Window.getHeight() donc sa s'affiche tous en haut il faut donc remonter dans la page
		if(this.top == 0)
			window.scrollTo(0,0);
		this.fx.overlay.start(0.8);
		this.step = 1;
		this.center.setStyle('background','#fff url(loading.gif) no-repeat center');
		this.caption.innerHTML = this.title;
		var size_final = parseInt(this.options.contentsHeight) + 50;
		this.fx.center.start({'height': [size_final]});
	},

	setup: function(){
		var aDim = this.rel.match(/[0-9]+/g);
		//si dans rel on as video alors on charge avec l'ip du serveur vidéo sinon on charge directement l'url
		if(this.rel.match(/videov2/))
			this.options.type = 'videov2';
		else{
			if(this.rel.match(/video/))
				this.options.type = 'video';
			else{
				if(this.rel.match(/xml/))
					this.options.type = 'xml';
				else{
					if(this.rel.match(/html5/))
						this.options.type = 'html5';
					else
						this.options.type = 'url';
				}
			}
		}
		this.options.contentsWidth = (aDim && (aDim[0] > 0)) ? aDim[0] : this.options.defaultWidth;
		this.options.contentsHeight = (aDim && (aDim[1] > 0)) ? aDim[1] : this.options.defaultHeight;

	},

	position: function(){
    	var my_navigateur = '';
		 if(navigator.userAgent.match('MSIE 6'))
			my_navigateur = 'IE6';
		else{
			if(navigator.userAgent.match('MSIE 7'))
				my_navigateur = 'IE7';
			else
				my_navigateur = 'autre';
		}
		if(my_navigateur == 'IE6' || my_navigateur == 'IE7'){
			this.overlay.setStyles({'top': window.getScrollTop()+'px', 'height': window.screen.height+'px'});
		}
		else
    		this.overlay.setStyles({'top': window.getScrollTop()+'px', 'height': window.getHeight()+'px'});
	},

	video: function(sLinkHref){
		if (sLinkHref.match(/youtube\.com\/watch/i)) {
      this.flash = true;
			var hRef = sLinkHref;
			var videoId = hRef.split('=');
			this.videoID = videoId[1];
			this.so = new SWFObject("http://www.youtube.com/v/"+this.videoID, "flvvideo", this.options.contentsWidth, this.options.contentsHeight, "0");
			this.so.addParam("wmode", "transparent");
		}
		else if (sLinkHref.match(/metacafe\.com\/watch/i)) {
      this.flash = true;
			var hRef = sLinkHref;
			var videoId = hRef.split('/');
			this.videoID = videoId[4];
			this.so = new SWFObject("http://www.metacafe.com/fplayer/"+this.videoID+"/.swf", "flvvideo", this.options.contentsWidth, this.options.contentsHeight, "0");
			this.so.addParam("wmode", "transparent");
		}
		else if (sLinkHref.match(/google\.com\/videoplay/i)) {
      this.flash = true;
			var hRef = sLinkHref;
			var videoId = hRef.split('=');
			this.videoID = videoId[1];
			this.so = new SWFObject("http://video.google.com/googleplayer.swf?docId="+this.videoID+"&hl=en", "flvvideo", this.options.contentsWidth, this.options.contentsHeight, "0");
			this.so.addParam("wmode", "transparent");
		}
		else if (sLinkHref.match(/ifilm\.com\/video/i)) {
		  this.flash = true;
			var hRef = sLinkHref;
			var videoId = hRef.split('video/');
			this.videoID = videoId[1];
			this.so = new SWFObject("http://www.ifilm.com/efp", "flvvideo", this.options.contentsWidth, this.options.contentsHeight, "0", "#000");
			this.so.addVariable("flvbaseclip", this.videoID+"&");
			this.so.addParam("wmode", "transparent");
		}
		else if (sLinkHref.match(/\.mov/i) && 0) {
		  this.flash = false;
			if (navigator.plugins && navigator.plugins.length) {
          this.other ='<object id="qtboxMovie" type="video/quicktime" codebase="http://www.apple.com/qtactivex/qtplugin.cab" data="'+sLinkHref+'" width="'+this.options.contentsWidth+'" height="'+this.options.contentsHeight+'"><param name="src" value="'+sLinkHref+'" /><param name="scale" value="aspect" /><param name="controller" value="true" /><param name="autoplay" value="true" /><param name="bgcolor" value="#000000" /><param name="enablejavascript" value="true" /></object>';
			} else {
				this.other = '<object classid="clsid:02BF25D5-8C17-4B23-BC80-D3488ABDDC6B" codebase="http://www.apple.com/qtactivex/qtplugin.cab" width="'+this.options.contentsWidth+'" height="'+this.options.contentsHeight+'" id="qtboxMovie"><param name="src" value="'+sLinkHref+'" /><param name="scale" value="aspect" /><param name="controller" value="true" /><param name="autoplay" value="true" /><param name="bgcolor" value="#000000" /><param name="enablejavascript" value="true" /></object>';
			}
		}
		else if (sLinkHref.match(/\.wmv/i) || sLinkHref.match(/\.asx/i)) {
		this.flash = false;
		 this.other = '<object NAME="Player" WIDTH="'+this.options.contentsWidth+'" HEIGHT="'+this.options.contentsHeight+'" align="left" hspace="0" type="application/x-oleobject" CLASSID="CLSID:6BF52A52-394A-11d3-B153-00C04F79FAA6"><param NAME="URL" VALUE="'+sLinkHref+'"><param><param NAME="AUTOSTART" VALUE="false"></param><param name="showControls" value="true"></param><embed WIDTH="'+this.options.contentsWidth+'" HEIGHT="'+this.options.contentsHeight+'" align="left" hspace="0" SRC="'+sLinkHref+'" TYPE="application/x-oleobject" AUTOSTART="false"></embed></object>'
		}
		else if (sLinkHref.match(/\.flv/i) || 1) {
		 this.flash = false;
		 //this.so = new SWFObject(this.options.flvplayer+"?file="+sLinkHref, "flvvideo", this.options.contentsWidth, this.options.contentsHeight, "0", "#000");
		 this.options.init();
		 var bg = '';
		 //on regarde si on as le javascript qui vérifie la version de flash et en fonction de la version de flash on charge un lecteur différent
		 if(control_version_flash != undefined || navigator.userAgent.match(/iPad/i) != null){
			if(!hasReqestedVersion && navigator.userAgent.match(/iPad/i) == null){
			 //on vas devoir découper le lien pour savoir quel dossier et quel fichier on doit charger suivant le type de navigateur
				var fichier = sLinkHref.split('/');
				sLinkHref = this.options.variable+'='+fichier[5]+"&doss="+fichier[3];
				bg = 'bgcolor="#AAAAAA"';
			 }
			 else{
			 	/*on reagrde l'option passé si c'est différent de video alors on charge directement le chemin de la vidéos sinon on récupère le chemin de la vidéos et on charge par rapport au serveur
				 c'est une petit sécurité: au lieu de mettre le chemin directe car si mootool a ma été importé on peut télécharger directement le fichier*/
				//on regarde si on veux faire passer un id de page
				switch(this.options.type){
					case 'videov2 html5':
					case 'videov2':
						this.final_player = this.options.flvplayer;
						//on récupère l'id du fichier à charger
						var fichier = sLinkHref.split('?');
						lien = 'ajax/ajax_get_html_load_file_imedia.php?id_article='+fichier[1];
						xhr_object.open("GET", lien, false);
	  					xhr_object.send(null);
	  					var fichier_name = xhr_object.responseText;
						var reg_fich = new RegExp("(\r\n|\r|\n| )", "g" );
						fichier_name = fichier_name.replace(reg_fich,'');
						if(navigator.userAgent.match('MSIE')){//si c'est IE on charge un autre lecteur car parfois l'image de la videos ne se lance pas
							this.final_player = '/modeles/flvplayer';
							sLinkHref = "flv="+fichier[0]+fichier_name+'&amp;showstop=1&amp;showvolume=1&amp;showtime=2&amp;showfullscreen=1&amp;showiconplay=1&amp;autoplay=1&amp;width=750&amp;height=422&margin=0';
						}
						else
							sLinkHref = this.options.variable+"="+fichier[0]+fichier_name+'&backcolor=ffffff&frontcolor=000099&screencolor=FFFFFF&controlbar=over';
						break;
					case 'xml':
						this.final_player = '/modeles/lecteur_chapitre.swf';
						var donne = sLinkHref.split('&');
						var fichier = donne[0].split('/');
						var xml = donne[1];
						sLinkHref = this.options.variable+'=http://videos1.santor.net/'+fichier[3];
						if(fichier[4] != '')
							sLinkHref = sLinkHref+'/'+fichier[4];
						if(fichier[5] != '')
							sLinkHref = sLinkHref+'/'+fichier[5];
						sLinkHref = sLinkHref+'&'+xml+'&width='+this.options.contentsWidth+'&height='+this.options.contentsHeight;
						this.options.contentsHeight = parseInt(this.options.contentsHeight) + 30;//+30 pour la barre de control
						break;
					case 'video':
					case 'html5':
						this.final_player = this.options.flvplayer;
						var fichier = sLinkHref.split('/');
						sLinkHref = 'http://videos1.santor.net/'+fichier[3];
						var fichier_sLinkHref = 'http://videos1.santor.net/'+fichier[3];
						if(fichier[4] != ''){
							sLinkHref = sLinkHref+'/'+fichier[4];
							fichier_sLinkHref = fichier_sLinkHref+'/'+fichier[4];
						}
						if(fichier[5] != ''){
							sLinkHref = sLinkHref+'/'+fichier[5];
							fichier_sLinkHref = fichier_sLinkHref+'/'+fichier[5];
						}
						if(navigator.userAgent.match('MSIE')){//si c'est IE on charge un autre lecteur car parfois l'image de la videos ne se lance pas
							this.final_player = '/modeles/flvplayer';
							sLinkHref = "flv="+sLinkHref+'&amp;showstop=1&amp;showvolume=1&amp;showtime=2&amp;showfullscreen=1&amp;showiconplay=1&amp;autoplay=1&amp;width=750&amp;height=422&margin=0';
						}
						else
							sLinkHref = this.options.variable+'='+sLinkHref+'&backcolor=ffffff&frontcolor=000099&screencolor=FFFFFF&controlbar=over';
						break;
					case 'url':
					default:
						sLinkHref = this.options.variable+'='+sLinkHref+'&backcolor=ffffff&frontcolor=000099&screencolor=FFFFFF&controlbar=over';
						break;
				}//fin switch
				bg = 'wmode="transparent"';
			}//fin version flash correcte
		 }//fin controlversion flash existe
		 else{
			 if(this.options.navigateur == 'IE6'){
			 //on vas devoir découper le lien pour savoir quel dossier et quel fichier on doit charger suivant le type de navigateur
				var fichier = sLinkHref.split('/');
				sLinkHref = this.options.variable+'='+fichier[5]+"&doss="+fichier[3];
				bg = 'bgcolor="#AAAAAA"';
			 }
			 else{
				if(this.options.type != 'video')
					sLinkHref = this.options.variable+'='+sLinkHref+'&backcolor=ffffff&frontcolor=000099&screencolor=FFFFFF&controlbar=over';
				else{
					var fichier = sLinkHref.split('/');
					sLinkHref = this.options.variable+'=http://videos1.santor.net/'+fichier[3];
					if(fichier[4] != '')
						sLinkHref = sLinkHref+'/'+fichier[4];
					if(fichier[5] != '')
						sLinkHref = sLinkHref+'/'+fichier[5];
					sLinkHref = sLinkHref+'&backcolor=ffffff&frontcolor=000099&screencolor=FFFFFF&controlbar=over';
				}
				bg = 'wmode="transparent"';
			}
		}
		if(this.options.type.match('html5')){
			var  reg=new  RegExp("(.flv)", "g");
			fichier_sLinkHref = fichier_sLinkHref.replace(reg,'.mov');
			this.other = '<video controls autoplay id="player_ipad" width="'+this.options.contentsWidth+'" height="'+this.options.contentsHeight+'"><source src="'+fichier_sLinkHref+'" type="video/quicktime"></video>';
		}
		else{
		 	this.other =  '<object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" codebase="http://fpdownload.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=8,0,0,0" name="startflv" width="'+this.options.contentsWidth+'" height="'+this.options.contentsHeight+'" align="middle"><param name="allowScriptAccess" value="always"><param name="movie" value="'+this.final_player+'"><param name="flashvars" value="'+sLinkHref+'&autostart=true"><param name="quality" value="high"><embed src="'+this.final_player+'" allowfullscreen="true" allowscriptaccess="always" flashvars="'+sLinkHref+'&autostart=true" '+bg+' quality="high" name="startflv" type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/go/getflashplayer" width="'+this.options.contentsWidth+'" height="'+this.options.contentsHeight+'" align="center"></embed></object>'
			if(this.options.navigateur == 'IE6'){
				hidden_select();
			}
		}
		}
		else {
		  this.flash = true;
			this.videoID = sLinkHref;
			this.so = new SWFObject(this.videoID, "flvvideo", this.options.contentsWidth, this.options.contentsHeight, "0");
		}
	},

	nextEffect: function(){
		switch (this.step++){
		case 1:
			this.fx.center.start({'width': [this.options.contentsWidth], 'marginLeft': [this.options.contentsWidth/-2]});
			break;
			this.step++;
		case 2:
			this.center.setStyle('background','#fff');
			this.flash ? this.so.write(this.center) : this.center.setHTML('<div style="margin-top:50px;">'+this.other+'</div>') ;
			//this.bottomContainer.setStyles({top: (this.top + this.center.clientHeight)+'px', height: '0px', marginLeft: this.center.style.marginLeft, width: this.options.contentsWidth+'px',display: ''});
			this.topContainer.setStyles({top: (this.top)+'px', height: '0px', marginLeft: this.center.style.marginLeft, width: this.options.contentsWidth+'px',display: 'block'});
			if (this.options.animateCaption){
				/*this.fx.bottom.set(-this.bottom.offsetHeight);
				this.bottomContainer.style.height = '';
				this.fx.bottom.start(0);*/
				/*if(this.top.offsetHeight == 'NaN')
					this.top.offsetHeight = 0;*/
				this.fx.top.set(-this.top.offsetHeight);//IE ne prend pas en compte this.top.offsetHeight malgré la ligne précédent toujours erreur (qui n'est pas critique, sa marche)
				this.topContainer.style.height = '';
				this.fx.top.start(0);
				break;
			}
			//this.bottomContainer.style.height = '';
			this.topContainer.style.height = '';
			this.step++;
		}
	},

	close: function(){
		this.fx.overlay.start(0);
		//this.center.style.display = this.bottomContainer.style.display = 'none';
		this.center.style.display = this.topContainer.style.display = 'none';
		this.center.innerHTML = '';
		if(this.options.navigateur == 'IE6'){
			appear_select();
		}
		return false;
	}

};


window.addEvent('domready', Videobox.init.bind(Videobox));