/*
#rtslib.inc /rtslib/browser.js
#rtslib.inc /rtslib/basic.js
#rtslib.inc /rtslib/html5.js
*/

// This file has tests. Please check that they are still up and running.
// Feel free to add more of them too, this module needs your love.
if (typeof RTS != 'object')
	RTS = {};

// Usually coming from rtslib.js but might be used in a standalone manner
if (typeof log === "undefined")
	log = function() {};

RTS.player = {
	tsrboutique: "https://boutique.rts.ch/commande-emission-tsr.php",
	defaults: {
		swf: RTS.basic.host + '/swf/player.swf?v=30341-145616',
		//debug: true,
		width: 640,
		height: 360,
		version: '10',
		wmode: 'transparent',
		expressInstall: RTS.basic.host + '/flash/expressInstall.swf',
		AllowScriptAccess: 'always',
		AllowFullScreen: true
	},
	keys: {
		params: 'play,loop,menu,quality,scale,salign,wmode,bgColor,base,swLiveConnect,flashvars,devicefont,AllowScriptAccess,SeamlessTabbing,AllowFullScreen,AllowNetworking'.split(','),
		attribs: 'id,name,styleclass,align'.split(','),
		reserved: 'swf,id,width,height,expressInstall'.split(',')
	},
	hasBoutique: true,
	players: {},
	streams: {},
	host: "",

	init: function(videoPlays, videoHolders) {
		// Get the cache of media that were preloaded in page
		if (typeof mediaToAdd !== 'undefined') {
			for (var i in mediaToAdd) {
				this.addStream(mediaToAdd[i]);
			}
		}

		this.bindInit(null, videoPlays, videoHolders);
	},

	// Utilisé dans PAJU
	embed: function(id, target, options) {

		var p = this.getPlayer(id);
		p.init(target);
		if (options)
			p.options = options;
		p.init();
		p.options.target = target;
		p.attribs.id = target;
		p.attribs.name = target;

		p.options.swf = RTS.basic.host + '/v/id/' + id;
		swfobject.embedSWF(p.options.swf, p.options.target,
				   p.options.width, p.options.height,
				   p.options.version, p.options.expressInstall,
				   p.vars, p.params, p.attribs);

	},

	// Bind the code for the videos
	// If only the content of a container has to be parsed, use argument (useful for dynamically loaded content)
	bindInit: function(container, videoPlays, videoHolders) {

		// Bind code to every video-play links of the page
		$(videoPlays || $('a.video-play, a.media-play', container)).live('click', function(event) {

			// Ignore right clicks (jquery live bug)
			if (event.button) return;

			var lnk = $(this),
				// Get video target
				vTarget = lnk.attr('data-video-target') || lnk.attr('data-target') || 'video',
				// and ID from link attributes
				vId = lnk.attr('data-video-id') || lnk.attr('data-id'),
				// Get some info from link
				additionalInfo = {
					'link-date': lnk.find('.date').text(),
					'link-title': lnk.find('.title').text(),
					'link-intro': lnk.find('.intro').text()
				};

			// Call the Ajax function
			RTS.player.playVideo(vId, vTarget, additionalInfo);

			return false;
		});

		// Play videos
		$(videoHolders || $('.video-player-holder', container)).each(function() {
			if (!this.id)
				this.id = "player"+new Date().valueOf()

			var vTarget = this.id,
				me = $(this);

			var initOption = {
				width: me.attr('data-video-width'),
				height: me.attr('data-video-height'),
				bigPlay: me.attr('data-video-bigplay')||true,
				bigPlayColor: me.attr('data-video-bigplaycolor')||"0xF20017",
				autoPlay: me.attr('data-video-autoplay')||false,
				showLargeButton:  me.attr('data-video-enlarge')||false
				//autoPlay:false
			};
			initOption.debug = false;

			if (t = me.attr('data-video-image')) initOption.image = t;

			var vId = me.attr('data-video-id');

			var parmId = RTS.basic.getParam('id', window.location.hash);

			if(parmId != null){
				vId = parmId;
			}

			RTS.player.playVideo(vId, vTarget, null, initOption);
		});

	},
	addStream: function(s) {

		this.streams[s.id] = s;

		if (this.current && typeof this.current.stream.id == 'undefined') {
			this.current.stream = this.streams[s.id];
		}
	},
	rebuildTargetName: function(p) {
		if (typeof(p) == 'object') {
			if (!p) return;
			if (!p.options) return;
			if (!p.options.target) return;

			//WITHOUTJQUERY
			if (!document.getElementById(p.options.target)) return;
			//if (!$('#'+p.options.target)[0]) return;
			if (p.options.target.indexOf('-') ==-1) return;

			var target = p.options.target;
			var reg = new RegExp("-","g");
			target = target.replace(reg,"_");

			//WITHOUTJQUERY
			document.getElementById(p.options.target).id = target;
			//$('#'+p.options.target)[0].id = target;
			p.options.target = target;
			p.options.name = target;
			p.options.id = target;
			p.attribs.name = target;
			p.attribs.id = target;
			p.vars.target = target;
		} else if (typeof(p) == 'string') {
			var reg = new RegExp("-","g");
			return p.replace(reg,"_");
		}
	},
	injectParentNode: function(p) {
		if (!p) return;
		if (!p.options) return;
		if (!p.options.target) return;
		//WITHOUTJQUERY
		if (!document.getElementById(p.options.target)) return;
		//if (!$('#'+p.options.target)[0]) return;

		//WITHOUTJQUERY
		var node = document.getElementById(p.options.target);
		//var node = $('#'+p.options.target)[0];
		if (!node.parentNode) return;

		var parent = node.parentNode;
		if (parent.className.indexOf('tsrplayer-parent')!=-1) return;

		var pClass = (node.className) ? ' '+node.className : '';
		var pStyle = (node.getAttribute('style')) ? node.getAttribute('style') : '';
		if (typeof(pStyle) =='object') pStyle = pStyle.cssText.toLowerCase();

		pStyle = pStyle.replace(/width *: *[a-zA-Z0-9]{0,} *;/,'')
					   .replace(/height *: *[a-zA-Z0-9]{0,} *;/,'');

		if(p.options.width == '100%' || p.options.height == '100%'){
			pStyle = pStyle+' width:100%;height:100%;';
		}

		var style = 'width:'+p.options.width+'px; height:'+p.options.height+'px; overflow:hidden;'+pStyle;
		if (style.indexOf('margin') ==-1) style += 'margin:auto;';

		var itm = $(document.createElement("div")).attr({
			"class": "tsrplayer-parent" + pClass,
			"style": style
		});


		parent.insertBefore(itm[0],node);
		//WITHOUTJQUERY
		parent.removeChild(document.getElementById(p.options.target));
		//parent.removeChild($('#'+p.options.target)[0]);
		itm[0].appendChild(node);
	},
	getPlayer: function(id) {
		var me = this;

		//id = me.rebuildTargetName(id);
		if (id && me.players[id]) {
			me.current = me.players[id];
			return me.current;
		}

		// default player
		var r = {
			options: {},
			stream: {},
			params: {},
			attribs: {},
			vars: {},
			stats: true,
			injected: false,
			inject: function(v) {
				if (!v) v = null;

				this.init();

				// options.target is required
				if (!this.options.target) {
					log('You must provide a target to inject a player.');
					return;
				}

				this.loadStream(v);

				if (this.stream && this.stream.media.length == 1 && this.stream.media[0].codec == 'h264') {
					this.options.version = '9.0.115';
				}

				RTS.player.injectPlayer(this);

				this.injected = true;
			},

			// If the player exists already, simply inject the new video in it
			// Otherwise, create the player
			play: function(vid) {

                if (!this.injected) {
                    this.inject(vid);
                    return;
                }

				// If the player doesn't exist yet in the page, create it and stop here
				if ((document.getElementById(this.options.target).tagName.toLowerCase()!='object' &&
					document.getElementById(this.options.target).tagName.toLowerCase()!='embed') ||
					(!this.injected)) {
					if (this.injected) this.options.autoPlay = true;
					this.inject(vid);
					return;
				}

                var o = swfobject.getObjectById(this.options.target);

                if (vid)
                    this.loadStream(vid);

				if(!o || typeof o.action != 'function') return false;

				// This calls player_pause and player_playing twice, until it's corrected the old method is used
				//o.action('load', [{id: vid, autoplay: true}]);

				o.change({stream: this.stream, autoPlay: true});
				RTS.player.executeCallback(this.stream);

			},
			isPlaying: function() {
				var o = swfobject.getObjectById(this.options.target);
				if(!o || typeof o.isVideoPlaying !== 'function')
					return false;
				log(this.stream);
				return o.isVideoPlaying();
			},
			init: function(v) {
				// add default options
				for (var k in me.defaults) {
					if (!this.options[k]) {
						this.options[k] = RTS.player.defaults[k]
					}
				}
				// id = name = target
				this.options.id = this.options.name = this.options.target = id;

				// set params, attribs and vars
				for (var k in this.options) {
					if ($.inArray(k, RTS.player.keys.params) > -1) {
						this.params[k] = this.options[k];
					} else if ($.inArray(k, RTS.player.keys.attribs) > -1) {
						this.attribs[k] = this.options[k];
					} else if ($.inArray(k, RTS.player.keys.reserved) == -1) {
						this.vars[k] = this.options[k];
					}
				}
			},
			loadStream: function(id) {
				if (id && id in RTS.player.streams) {
					this.stream = RTS.player.streams[id]
				}
			}
		};
		return r;
	},
	getStream: function(id) {
		var p = this.getPlayer(id);
		return p.stream;
	},
	sendToFriend: function(stream) {
		var send = $("#video-title .send");
		if(false && send.length) {
			send.click();
		} else if("lightbox" in RTS) {

			var a = $(document.createElement("a"));

			a.attr("data-width", 510)
			 .attr("data-params", "format=lightbox&sendto=show&permalink="+encodeURIComponent(document.location.href))
			 .attr("href", "?format=lightbox&sendto=show")
			 .attr("class", "send tsr-lightbox")
			 .appendTo("body");

			RTS.lightbox.init(a);

			a.click();
		}
	},
	goShopping: function(stream) {
		if (!stream) stream = this.current.stream;
		var shopLink = $("#shopLink");
		if(shopLink.length) {
			shopLink.click();
		} else {
            if ('shopLink' in stream && stream['shopLink'] != '' && stream['shopLink'] != '#') {
                window.location = stream['shopLink'];
                return false;
            }

			if (!'shopParams' in stream) {
				log('shop error: no shopParams in stream');
				return false;
			}
			var shopParams = stream.shopParams,
				form = $(document.createElement("form")),
				input = document.createElement("input");
			for(var param in shopParams) {
				if (param == 'paiement' && shopParams[param] == 'false')
					continue;
				$(input.cloneNode(false)).attr("name", param)
										 .attr("value", shopParams[param])
										 .attr("type", "hidden")
										 .appendTo(form);
			}

			form.attr("action", this.tsrboutique)
				.attr("method", "POST")
				.appendTo("body").submit();
		}
	},
	getRelated: function(stream) {
		if (!this.hasRelated(null))
			return [];
		log('get related videos: ' + RTS.player.related_videos.length);
		return RTS.player.related_videos;
	},
	hasRelated: function(stream) {
		if (typeof RTS.player.related_videos == 'undefined' || typeof RTS.player.related_videos.length == 'undefined')
			return false;
		return RTS.player.related_videos.length > 0;
	},
	hasShopping: function(stream) {
		//log('has shopping call: ' + ('shopLink' in stream && stream.shopLink != ''));
		return 'shopLink' in stream && stream.shopLink != '';
	},
	hasMail: function(stream) {
		return "lightbox" in RTS;
	},
	// hook called by the Flash player (work in progress)
	playVideoFromAS: function(stream, target) {
		target = target || "mainPlayer";
		// Needs a way to know which is the current player
		if(document.getElementById(target) && "video_id" in stream) {
			// clear cache!
			delete this.streams[stream.video_id];
			this.playVideo(stream.video_id, target);
			return true;
		} else {
			return false;
		}
	},
	playVideoFromXobixId: function(xId, target) {
		var me = this;
		$.getJSON(this.host+'/?f=json/article&id='+xId, function(data){
			var id = me.addData(data);
			// Once the stream is added, call playVideo again
			RTS.player.playVideo(id, target);
		});
	},
	/*
	Add callback function when a video is played
		fn: the anonymous function to be called
	*/
	onPlayAdd:function(fn){
		if(!this.onPlayCallback){
			this.onPlayCallback = [];
		}
		this.onPlayCallback.push(fn);
	},

	/*
	Will execute all the callbacks
		v: the video object that is played
	*/
	executeCallback:function(v){
		if(this.onPlayCallback){
			for(i=0; i < this.onPlayCallback.length; i++){
				this.onPlayCallback[i](v);
			}
		}
	},

	/*
	playVideo:      play a video in the page, creates the player if needed (if initOption is given), and load info if needed
	vId:            the ID of the video to play, will load info in AJAX if not available
	vTarget:        the ID / target of the player
	additionalInfo: Additional fields to update in HTML elements when the video is played
	initOption:     to create the player (flash object), initialization options
	*/
	playVideo: function(vId, vTarget, additionalInfo, initOption) {

		var me = this;

		if (arguments.length == 1 || !vId) {
			// this is coming from the actual player (which should call playVideoFromAS)
			return;
		}

		if(this.streams[vId]) {

			// appears too frequently...
			// log("Trying to play a vId stored in js object.");

			// Either take given size, or get the parent div's size
			var target = $("#"+vTarget),targetTagName="",w,h,v,c,t;

			if(!target.length)
				target = $("#"+vTarget.replace(/-/g, "_"));

			if(!target.length) {
				log("no target found: "+vTarget);
				return
			}

			w = $('#'+vTarget).width();
			h = w / (16/9);

			// 100%, DO NOT WANT!
			if (initOption) {
				if (initOption.width == '100%') initOption.width = null;
				if (initOption.height == '100%') initOption.height = null;
				if (initOption.width) w = initOption.width;
				if (initOption.height) h = initOption.height;
			}

			// Check if player is initalized already
			// TODO: there should be a cleaner way to do this.
			target.each(function(){
				targetTagName = this.tagName.toLowerCase()
			});

			// if (targetTagName != 'object') alert('player '+vTarget+' doesn\'t exist, create one without options.');

			// Play right away if no initOption
			if (!initOption && targetTagName == 'object') {
				RTS.player.playStream(target[0].id, vId);

			// if there is initOption, initlialize the player and inject the video
			} else {
				var p = RTS.player.getPlayer(target[0].id);
				p.options.width = w;
				p.options.height = h;
				p.options.autoPlay = true;
				if (initOption) {

					p.options.bigPlay = initOption.bigPlay;
					p.options.bigPlayColor = '0xF20017';
					p.options.autoPlay = initOption.autoPlay;
					p.options.showLargeButton = initOption.showLargeButton;
				}

				//p.options.debug = true;
				p.inject(vId);
			}

			RTS.player.onStreamSet(this.streams[vId], vTarget, additionalInfo);

		// If video is not loaded, do an AJAX request to load it, then call playVideo again
		} else {

			// appears too frequently...
			// log("Trying to play a vId with the normal way.");

			if (!('_rts_players' in window))
				window._rts_players = {};

			var p = window._rts_players[vTarget] || document.getElementById(vTarget);

			// Cas HTML5 (Pour l'instant seulement en dev)
			if(RTS.html5.isOn && p && (!('action' in p))){
				p = document.getElementById(vTarget+"_video");
			}

			if (p && 'action' in p) {
				if (!window._rts_players[vTarget]) {
					log('RTS.player.playVideo action id:' + vId + ' target: ' + vTarget);

					// cache
					window._rts_players[vTarget] = p;

					// Add listener for future video plays.
					RTS.player.addListener('player_stream_set', function(e) {
						var o = e.original || e;
						RTS.player.onStreamSet(o, vTarget, additionalInfo);
					}, p);
				}

				p.action('load', [{'id': vId, 'autoPlay': true}]);
				return;
			}

			$.getJSON(this.host+'/?f=json/article&id='+vId, function(data){
				var id = me.addData(data);
				// Once the stream is added, call playVideo again
				if (vId == id)
					RTS.player.playVideo(vId, vTarget, additionalInfo, initOption);
				else
					log('Video ID does not match, play aborted!');
			});
		}
	},

	onStreamSet: function(stream, target, additionalInfo) {
		// Get other info from the XML and insert them into elements with the
		// corresponding class that are in the same container as the player
		c = $('#' + target + '-info');
		for (t in stream)
			$('.' + t, c).html(stream[t]);

		if (additionalInfo) {
			for(var k in additionalInfo) {
				$('.' + k, c).html(additionalInfo[k]);
			}
		}

		if (c.css('display') == 'none')
			c.css('display','block');
	},

	addData: function(data) {

        if(!data || !(("video" in data && "JSONinfo" in data.video) || "audio" in data)) {
            return false;
        }

		// Get the JSON code of the video object
		var info = "video" in data ? data.video.JSONinfo : data.audio;

		RTS.player.related_videos = info.related;

		// Add the stream
		RTS.player.addStream(info);

		return info.id || info.video_id;
	},
	jsReady: function() {
		return true;
	},
	injectPlayer: function(p) {

		this.rebuildTargetName(p);
		this.injectParentNode(p);

		this.players[p.options.target] = p;
		this.current = null;

		// Callback function for swfobject
		var me = this;
		var cb = function() {me.executeCallback(p.stream);};

		swfobject.embedSWF(p.options.swf, p.options.target,
			p.options.width, p.options.height,
			p.options.version, p.options.expressInstall,
			p.vars, p.params, p.attribs, cb);


		log("RTS.player.injectPlayer, html5 isOn: " + (RTS.html5.isOn) + ". Has flash: "+RTS.browser.hasFlash+". typeof html5:"+RTS.html5);

		if( ! RTS.browser.hasFlash ){

			var posterUrl = p.stream.preview_image_url;
			var style = "margin:auto;width:"+p.options.width+"px;height:"+p.options.height+"px;";

			log("RTS.player.injectPlayer use html5");

			var videoHTML = "<div class='html5-holder' style='display:none;'>" +
				"<a href='"+p.stream.url+"' class='poster' style=\"background-image:url('"+posterUrl+"');\">" +
                	"<span class='play'></span>" +
                    "<span class='load'>" +
                    	"<img src='"+RTS.basic.host+"/img/general/ajax/video-loader.gif' width='32px' height='32px' style='width:32px;height:32px;' />" +
                    "</span>" +
                "</a>" +
                "<video id='" + p.attribs.id +"_video' style='"+ style +"' controls='controls' data-id='"+p.stream.id+"' poster='"+posterUrl+"' >" +
                "</video></div>";
			document.getElementById(p.attribs.id).innerHTML = videoHTML;
			RTS.html5.init();
		}

	},
	playStream: function(pid, vid) {
		pid = this.rebuildTargetName(pid);
		if (!pid || pid && !this.players[pid] ||
			!vid || vid && !this.streams[vid]) return;

		this.getPlayer(pid).play(vid);
	},
	setVolume: function(v) {
		RTS.basic.setCookie('tsrPlayerVolume', v, 60*60*24*365, '/', 'tsr.ch', '');
	},
	getVolume: function() {
		return RTS.basic.getCookie('tsrPlayerVolume');
	},
	setQuality: function(v) {
		RTS.basic.setCookie('tsrPlayerQuality', v, 60*60*24*365, '/', 'tsr.ch', '');
	},
	getQuality: function() {
		var v = RTS.basic.getCookie('tsrPlayerQuality');
		return v;
	},
	stats: {
		currentStream: '',
		currentMedia: null,
		statString: '',
		renommage: '',
		bcVideoId: '0-0',
		format: '',
		wsInfo: {},
		defaults: {
			/* Page */
			compte: 'tsr',
			target: 'embedVideo',
			pageGroup: 'tsrvideo.ch',
			pageName: '',
			frame: 'NOPV',
			parametre: '',
			extranet: '',
			roi: '',
			profil:''
		},
		addDefaultValues: function() {
			for (var k in this.defaults) {
				if (!this.wsInfo[k]) {
					this.wsInfo[k] = this.defaults[k];
				}
			}
		},

		// Main function, with 2 params (player target AND media id)
		register: function(pid, stream) {
			// verifs
			if(!pid) return false;
			if (typeof stream != 'object' || !stream) return false;

			var p = RTS.player.getPlayer(pid);
			if (!p.stats) {
				log('stats is false, ignore');
				return false;
			}
			// Get Player Infos
			this.wsInfo.target = pid;
			this.currentStream = stream;

			// Launch
			this.addDefaultValues();
			if (this.parse()) this.doStats();
			else log('parsing is false, no stats');
		},
		doStats: function() {
			var o = this.wsInfo;

			if (!this.hasVideoStats()) {
				log('#error# player.doStats cannot work: statistique.js?video=1 is not defined');
				return false;
			}

			log("doStats: wysistat("+[o.compte,o.frame,o.parametre,o.extranet,
									  o.renommage,o.roi,o.profil,o.statString].join(", ")+");");
			if(typeof wysistat !== "undefined")
				wysistat(o.compte, o.frame, o.parametre, o.extranet,
						 o.renommage, o.roi, o.profil, o.statString)
		},
		hasVideoStats: function() {
			if (typeof ws_loadVideoJs === 'function')
				return true;
			var scripts = $.makeArray(document.getElementsByTagName('script'));
			for (var k in scripts) {
				var s = scripts[k].src;
				if (typeof s != 'undefined' && s.indexOf('statistique.js?video=1') != -1) {
					return true;
				}
			}
			return false;
		},
		parseDate: function(dateTimeSolr) {
			if (!dateTimeSolr) return;
			dateTimeSolr = dateTimeSolr.split('T');
			var aDate = dateTimeSolr.shift().split('-');
			return aDate[2] + aDate[1] + aDate[0];
		},
		removeSpecialChars : function(s) {
			s = s || "";
			var acS = {
				a:/[áàâä]/gi,
				c:/ç/gi,
				e:/[èéêë]/gi,
				i:/[íìîï]/gi,
				o:/[óòôö]/gi,
				oe:/œ/gi,
				u:/[úùûü]/gi,
				y:/[ýÿ]/gi,
				'-':/[\/|]/gi
			};
			for (var l in acS) {
				s = s.replace(acS[l], l);
			}
			return s;
		},
		getFormatByMimeType:function (f) {
			return "WS_VIDEOTYPE_FLASH";
		},
		parse: function() {
			var s = this.currentStream,
				wi = this.wsInfo;
			wi.duration = parseInt(s.duration, 10);
			wi.broadcast_date = this.parseDate(s.broadcast_date);
			wi.title = this.removeSpecialChars(s.title);
			wi.program = this.removeSpecialChars(s.xobix_program_name);
			wi.pageGroup = s.pageGroup ? s.pageGroup : this.defaults.pageGroup;
			wi.renommage = !s.pageNathis ? wi.pageGroup : wi.pageGroup + ';' + s.pageNathis;
			wi.format = s.codec;
			wi.bcVideoId = (s.xobix_broadcast_id || s.id) + '-' + s.vid;
			wi.bitrate = s.bitrate;
			wi.statString = [wi.target,wi.title,wi.program,wi.broadcast_date,
							 wi.format,wi.duration,wi.bitrate,wi.bcVideoId].join("|");
			return !!(wi.title || s.id)
		}

	},

	// create a new uid
	getPlayerUid: function(player) {
		var $player = $(player),
			uid = $player.data('uid');

		if (!uid) {
			uid = 'rtsplayer_' + Math.floor(Math.random() * 1000) + '_' + (new Date()).getTime();
			$player.data('uid', uid);
		}

		return uid;
	},

	/**
	 * Ads an event listener to the player.
	 */
	addListener: function(key, func, player) {
		if (typeof player == "string")
			player = $("#" + player.replace(/^#/, ''));
		else
			player = $(player);

		if (!player.length)
			return;

		var uid = RTS.player.getPlayerUid(player);

		if (typeof window[uid] == 'undefined') {
			window[uid] = [];
		}
		window[uid][key] = func;

		player[0].action('addJsListener', [key, 'window.' + uid + '.' + key]);
	}
};

// Backward compatibility
if(typeof TSR === "undefined") TSR = {};
TSR.player = RTS.player;

