
if(!this.JSON){JSON={};}
(function(){function f(n){return n<10?"0"+n:n;};if(typeof Date.prototype.toJSON!=="function"){Date.prototype.toJSON=function(_1){return this.getUTCFullYear()+"-"+f(this.getUTCMonth()+1)+"-"+f(this.getUTCDate())+"T"+f(this.getUTCHours())+":"+f(this.getUTCMinutes())+":"+f(this.getUTCSeconds())+"Z";};String.prototype.toJSON=Number.prototype.toJSON=Boolean.prototype.toJSON=function(_2){return this.valueOf();};}
var cx=/[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,_3=/[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,_4,_5,_6={"\b":"\\b","\t":"\\t","\n":"\\n","\f":"\\f","\r":"\\r","\"":"\\\"","\\":"\\\\"},_7;function _8(_9){_3.lastIndex=0;return _3.test(_9)?"\""+_9.replace(_3,function(a){var c=_6[a];return typeof c==="string"?c:"\\u"+("0000"+a.charCodeAt(0).toString(16)).slice(-4);})+"\"":"\""+_9+"\"";};function _a(_b,_c){var i,k,v,_d,_e=_4,_f,_10=_c[_b];if(_10&&typeof _10==="object"&&typeof _10.toJSON==="function"){_10=_10.toJSON(_b);}
if(typeof _7==="function"){_10=_7.call(_c,_b,_10);}
switch(typeof _10){case"string":return _8(_10);case"number":return isFinite(_10)?String(_10):"null";case"boolean":case"null":return String(_10);case"object":if(!_10){return"null";}
_4+=_5;_f=[];if(Object.prototype.toString.apply(_10)==="[object Array]"){_d=_10.length;for(i=0;i<_d;i+=1){_f[i]=_a(i,_10)||"null";}
v=_f.length===0?"[]":_4?"[\n"+_4+_f.join(",\n"+_4)+"\n"+_e+"]":"["+_f.join(",")+"]";_4=_e;return v;}
if(_7&&typeof _7==="object"){_d=_7.length;for(i=0;i<_d;i+=1){k=_7[i];if(typeof k==="string"){v=_a(k,_10);if(v){_f.push(_8(k)+(_4?": ":":")+v);}}}}else{for(k in _10){if(Object.hasOwnProperty.call(_10,k)){v=_a(k,_10);if(v){_f.push(_8(k)+(_4?": ":":")+v);}}}}
v=_f.length===0?"{}":_4?"{\n"+_4+_f.join(",\n"+_4)+"\n"+_e+"}":"{"+_f.join(",")+"}";_4=_e;return v;}};if(typeof JSON.stringify!=="function"){JSON.stringify=function(_11,_12,_13){var i;_4="";_5="";if(typeof _13==="number"){for(i=0;i<_13;i+=1){_5+=" ";}}else{if(typeof _13==="string"){_5=_13;}}
_7=_12;if(_12&&typeof _12!=="function"&&(typeof _12!=="object"||typeof _12.length!=="number")){throw new Error("JSON.stringify");}
return _a("",{"":_11});};}
if(typeof JSON.parse!=="function"){JSON.parse=function(_14,_15){var j;function _16(_17,key){var k,v,_18=_17[key];if(_18&&typeof _18==="object"){for(k in _18){if(Object.hasOwnProperty.call(_18,k)){v=_16(_18,k);if(v!==undefined){_18[k]=v;}else{delete _18[k];}}}}
return _15.call(_17,key,_18);};cx.lastIndex=0;if(cx.test(_14)){_14=_14.replace(cx,function(a){return"\\u"+("0000"+a.charCodeAt(0).toString(16)).slice(-4);});}
if(/^[\],:{}\s]*$/.test(_14.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g,"@").replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g,"]").replace(/(?:^|:|,)(?:\s*\[)+/g,""))){j=eval("("+_14+")");return typeof _15==="function"?_16({"":j},""):j;}
throw new SyntaxError("JSON.parse");};}})();

window.is_in_array=function(arr,elt){var len=arr.length;var from=Number(arguments[2])||0;from=(from<0)?Math.ceil(from):Math.floor(from);if(from<0)from+=len;for(;from<len;from++)
{if(from in arr&&arr[from]===elt)return from;};return-1;}

window.object_clone = function(obj) {var newObj = (this instanceof Array) ? [] : {};for (i in obj) {if (obj[i] && typeof obj[i] == "object") {newObj[i] = object_clone(obj[i]);}else {newObj[i] = obj[i];}}return newObj;};

window.mmmGetWindowSize=function() {
	var myWidth = 0, myHeight = 0;
	if( typeof( window.innerWidth ) == 'number' ) {
		myWidth = window.innerWidth;
		myHeight = window.innerHeight;
	} 
	else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
		myWidth = document.documentElement.clientWidth;
		myHeight = document.documentElement.clientHeight;
	}
	else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
		myWidth = document.body.clientWidth;
		myHeight = document.body.clientHeight;
	}
	return [ myWidth , myHeight ];
}


window.mmmGetScrollXY=function() {
	var scrOfX = 0, scrOfY = 0;
	if( typeof( window.pageYOffset ) == 'number' ) {
		scrOfY = window.pageYOffset;
		scrOfX = window.pageXOffset;
	}
	else if( document.body && ( document.body.scrollLeft || document.body.scrollTop ) ) {
		scrOfY = document.body.scrollTop;
		scrOfX = document.body.scrollLeft;
	}
	else if( document.documentElement && ( document.documentElement.scrollLeft || document.documentElement.scrollTop ) ) {
		scrOfY = document.documentElement.scrollTop;
		scrOfX = document.documentElement.scrollLeft;
	}
	return [ scrOfX, scrOfY ];
}



window.thisMovie=function(swf) {
	if(navigator.appName.indexOf("Microsoft") != -1) {
		return window[swf];
	} else {
		return document[swf];
	}
}

window.sortByNumber=function(a, b) {
    var x = a[0];
    var y = b[0];
    return ((x < y) ? -1 : ((x > y) ? 1 : 0));
}

window.sortByBitrateAscending=function(a, b) {
    var x = a.bitrate;
    var y = b.bitrate;
    
    return ((x < y) ? -1 : ((x > y) ? 1 : 0));
}

window.sortByBitrateDescending=function(a, b) {
    var x = a.bitrate;
    var y = b.bitrate;
    
    return ((x > y) ? -1 : ((x < y) ? 1 : 0));
}

window.external_objects={
	oImgDebit:null,
	oImgPing:null,
	oImgVisitDump:null,
	oImgDump:null,
	oIdentityScr:null,
	aPrebuffering:{
		0:15000,
		256:11000,
		512:8000,
		768:6000,
		1024:5000,
		1500:4000,
		2500:3000,
		3000:2000
	}
};


window.mmmVisitData={"nFailTime": 20000, "sDebitF": "debit_large.jpg", "nRealBitrate": 0, "sClientName": "onedior", "nVideoVer": 1, "nBwLimit": 512, "sPingF": "ping.gif", "aCDNs": [{"host": "cdnet.massmotionmedia.com", "name": "cdnet"}, {"host": "ec.massmotionmedia.com", "name": "ec"}, {"host": "level3.massmotionmedia.com", "name": "level3"}, {"host": "cc.massmotionmedia.com", "name": "cc"}, {"host": "webvideo.massmotionmedia.com", "name": "mmm"}], "sRadarCDN": "", "nBufferMultiplier": 1, "nPerfDuration": 3000, "vt_id": Math.round(Math.random()*101111000), "uPerf": "perf", "sCurrentCDN": "", "nPerfDelay": 1000, "uTracking": "http://webvideo.massmotionmedia.com", "sStatsVersion": "1", "nLatency": 0, "uRadarPath": "http://wwcache.massmotionmedia.com/onedior/player/js/radar.html", "nVisitDuration": 0, "nDebitSize": 84338, "v_id": 0, "sStreamMode": "str", "nMainVer": 1, "sBackupCDN": "level3", "nCheckTimeout": 10000, "uBase": "http://wwcache.massmotionmedia.com", "nBitrate": 0, "bBkUsed": false, "uRefVideo": "projects", "nMultiplier": 1, "uTrackingScript": "stats/tracking_v2.mmm", "nFailDt": 50000, "aVideos": [], "nPerfLevel": 50, "aVidLevel": null, "nBufferTime": 5000};

var BTN_PLAY_W = 75; //should be moved to window.mmmVisitData ?
var BTN_PLAY_H = 75;

window.utilsMMM=function()
{
	this.stats_ua_browser={
		'Ipad' : ['.*(Ipad).*'],
		'Ipod' : ['.*(Ipod).*'],
		'Iphone' : ['.*(Iphone).*'],
		'IE6' : ['.*(MSIE 6).*'],
		'IE7' : ['.*(MSIE 7).*'],
		'IE8' : ['.*(MSIE 8).*'],
		'IE9' : ['.*(MSIE 9).*'],
		'Opera Mobile' : ['.*Opera Mobi.*'],
		'Opera' : ['.*Opera.*'],
		'Firefox 2' : ['.*Firefox/2.*'],
		'Firefox 3' : ['.*Firefox/3.*'],
		'Firefox 4' : ['.*Firefox/4.*'],
		'Firefox' : ['.*Firefox.*'],
		'Netscape' : ['.*Netscape.*'],
		'Chrome' : ['.*(Chrome).*'],
		'Safari' : ['.*(Safari|Camino).*'],
		'Konqueror' : ['.*Konqueror.*'],
		'Other' : ['.*']
	}

	this.stats_ua_os={
		'Ipad' : ['.*Ipad.*'],
		'Ipod' : ['.*(Ipod).*'],
		'Iphone' : ['.*(Iphone).*'],
		'Mac' : ['.*(Mac).*'],
		'Linux' : ['.*(Linux).*'],
		'Windows Seven 64' : ['.*(Windows NT 6.1; WOW64).*'],
		'Windows Seven' : ['.*(Windows NT 6.1).*'],
		'Windows Vista' : ['.*(Windows NT 6.0; WOW64).*'],
		'Windows Vista' : ['.*(Windows NT 6.0).*'],
		'Windows XP 64' : ['.*(Windows NT 5.2).*'],
		'Windows XP' : ['.*(Windows NT 5.1).*'],
		'Windows 2000' : ['.*(Windows NT 5.0).*'],
		'Windows Other' : ['.*(Windows).*']
	}
                
                
   this.get_computer_data=function(){
		
		var mmm_ua=navigator.userAgent;
		
		for (var r_browser in this.stats_ua_browser) {
			var rules=this.stats_ua_browser[r_browser];
			var found=0;
			for (var r in rules) {
			    var rule=new RegExp(rules[r],'i');
			    if (mmm_ua.match(rule)) {
			      found=1;
			      this.browser=r_browser;
			      break;
			    }
			}
			if (found) break;
		}


		for (var r_os in this.stats_ua_os) {
			var rules=this.stats_ua_os[r_os];
			var found=0;
			for (var r in rules) {
			    var rule=new RegExp(rules[r],'i');
			    if (rule.test(mmm_ua)) {
			      found=1;
			      this.os=r_os;
			      break;
			    }
			}
			if (found) break;
		}
		
		this.screen_width=window.screen.width;
		this.screen_height=window.screen.height;
		
		s='Current Device:\n';
		for (var p in this._currentDevice)
		{
		  s+='\t'+p+' : '+this._currentDevice[p]+'\n';
		}
		
		s+='Computer detection:'+'\n'
		+'------------------------------'+'\n'
		+'\t browser='+this.browser+'\n'
		+'\t os='+this.os+'\n'
		+'\t device='+this.device+'\n'
		+'\t screen_width='+this.screen_width+'\n'
		+'\t screen_height='+this.screen_height+'\n'
		+'------------------------------'+'\n';
		if (window.console) this.log(s);
		//else alert(s);
		
	}
  
  
	this.fFlashVersion=0;
	this.check_swf = function () {var mmm_ua = navigator.userAgent; try {mmm_ua = (navigator.mimeTypes && navigator.mimeTypes["application/x-shockwave-flash"]) ? navigator.mimeTypes["application/x-shockwave-flash"].enabledPlugin : 0;}catch(e) {} if (mmm_ua) { try {this.fFlashVersion = parseFloat(mmm_ua.description.match("([0-9]+\.[0-9]+)"));}catch(e){}}else{try{var ax = new ActiveXObject('ShockwaveFlash.ShockwaveFlash');var version = ax.GetVariable("$version");this.fFlashVersion = parseFloat(version.match("([0-9]+\,[0-9]+),")[1].replace(',','.'));}catch(e) {}}};  
  
	this.getUrlVars =  function() {
		var prm = new Array();
		var tmp = unescape(window.location.search).substr(1).split("&");
		var inter;
		for ( i=0; i<tmp.length; i++){
			inter=tmp[i].indexOf("=");
			if ( inter>=0 ){prm[tmp[i].substr(0,inter)]=tmp[i].substr(inter+1)} else { prm[tmp[i]]="";}
		}
		return prm;
	}
	
	this.reqFlashVersion=9.0;
	this.buildPlayer = function (idTarget,idVideo,w,h,html5Params,swfFile,flashvars,embedParams,attributes){
        //document.getElementById('log').innerHTML = this.device ;
		if( this.device == 'computer'){
		
			this.check_swf();
			if (this.fFlashVersion>=this.reqFlashVersion) {			
			      if(typeof idVideo != "undefined" && idVideo!=""){
				      if(!flashvars)flashvars 	= {};
				      flashvars.idVideo			= idVideo;
			      }		
			      this.buildFlashContext(idTarget,swfFile,w,h,flashvars,embedParams,attributes);
			}
			else {
			      this.buildHTML5Context(idTarget,idVideo,w,h,html5Params);
			}
			
		}else if ( this.device == 'winPhone' || this.device == 'blackberry' ){
            this.buildPhoneContext(idTarget,idVideo,w,h,html5Params);
        }else{ // mobiles et tablettes
			this.buildHTML5Context(idTarget,idVideo,w,h,html5Params);
		}
				
	}
	
	this.buildFlashContext = function(idTarget,swfFile,w,h,flashvars,params,attributes){
		this._isHTML5		= false;
		window.user_poster  = false;
				
		this.log("buildFlashContext");
		
		var divPlayer 		= document.createElement('div');
		divPlayer.id 		= "playerMMM";
		
		var playerTarget	= document.getElementById(idTarget);	
		//delete player
		while (playerTarget.hasChildNodes())
			playerTarget.removeChild(playerTarget.firstChild);
		
		playerTarget.appendChild(divPlayer);
		
		if(!flashvars)flashvars 	= {};
		if(!params)params 			= {};
		if(!attributes)attributes 	= {};
		
				
		if(typeof(flashvars.poster) != "undefined"){
			window.user_poster = flashvars.poster;
		}
		
		if(attributes.id){
			if(attributes.id==idTarget)attributes.id+='fl';
			this._idTarget		= attributes.id;
			attributes.name		= attributes.id;
		}else{
			this._idTarget		= idTarget;
		}
		
		try{
		    for(property in flashvars){
				if( (flashvars[property].indexOf('"') !=-1) || (flashvars[property].indexOf('&') !=-1) || (flashvars[property].indexOf('=') !=-1)   ){
				    flashvars[property]=encodeURIComponent(flashvars[property]);
				}
		    }
		}
		catch(e){
		  this.log("buildFlashContext error: "+e);
		}
		//flashvars.debug		= "0";
		flashvars.jsobject	= this._name;
		flashvars.version	= "1";
		flashvars.account	= this._account;
		flashvars.domainUrl	= mmmVisitData.uBase;	
		
		//params.wmode			= "opaque";
		params.allowFullscreen	= "true";
		params.allowScriptAccess = "always";
		
		if(typeof(params.bgcolor) == "undefined"){
            params.bgcolor="000000";
        }
		//attributes.id		= "videoplayer";
		//attributes.name		= "videoplayer";
		
		swfobject.embedSWF(swfFile, divPlayer.id, w,h, "9.0.0", "swf/expressInstall.swf", flashvars, params, attributes);

		
	}
	
	this.buildPhoneContext = function(idTarget,idVideo,w,h,params) {
        
        var  dDiv = document.createElement("div");
        
        dDiv.setAttribute("id","playerContenerMMM");
        
        this._paramsHTML5   = params;
        this._idTarget      = idTarget;
        
        this._idVideo       = idVideo;
        this._videoWidth    = w;
        this._videoHeight   = h;
        
        var oVideoInfo      = JSON.parse(this.get_video(this._idVideo));
        var _poster = mmmVisitData.uBase+'/'+this._account+'/player/placeholder.gif' ;
        
        if(typeof oVideoInfo.poster != "undefined"){           
            if(oVideoInfo.poster != "")
              _poster = oVideoInfo.poster ;
        }
        
        if(typeof params != "undefined"){
            if(typeof params.poster != "undefined")
               if(params.poster != "")
                   _poster = params.poster;
        }

        if( typeof w != 'string'){
	        w += 'px' ;
            h += 'px' ;
    	}
    	
        this.log("buildPhoneContex() -> idVideo == "+this._idVideo+", poster == "+_poster);
        
        var playerTarget = document.getElementById(idTarget); 
        //delete player
        while (playerTarget.hasChildNodes())
            playerTarget.removeChild(playerTarget.firstChild);
        
        playerTarget.appendChild(dDiv);
        
        var _btnPlayWidth = BTN_PLAY_W / 2;
        var _btnPlayHeight = BTN_PLAY_H / 2;
       
        var _playerTop = playerTarget.offsetTop ;
        var _playerLeft = playerTarget.offsetLeft ;
        var _playerWidth = playerTarget.offsetWidth ;
        var _playerHeight = playerTarget.offsetHeight ;
       
        var _posX = _playerLeft + (_playerWidth/2) - _btnPlayWidth ;
        var _posY = _playerTop + (_playerHeight/2) - _btnPlayHeight ;

        var _imgPlayStyle = "position:absolute;top:"+_posY+"px;left:"+_posX+"px;z-index:2;border:none;" ;
        var _imgPlaySrc = mmmVisitData.uBase+'/'+this._account+'/player/btn_play.png';
       
       // var _imgPlayStyle = "position:absolute;top:50%;left:50%;margin:-78.5px 0 0 -78.56px;z-index:2;border:none;" ;
        
        if (this.device == 'winPhone')  {
         //   dDiv.innerHTML = '<a href="' + oVideoInfo.link + '"><img src="'+_imgPlaySrc+'" style="'+_imgPlayStyle+'"/><img border="0" src="' + _poster + '" /></a>' ;
        	dDiv.innerHTML = '<a href="' + oVideoInfo.link + '" style="background: transparent url(\'' + _poster + '\') left top no-repeat;width:'+_playerWidth+'px;height:'+_playerHeight+'px;" /><div style="background: transparent url(\''+_imgPlaySrc+'\') center center no-repeat;width:'+_playerWidth+'px;height:'+_playerHeight+'px;">&nbsp;</div></a>' ;
        } else {
            var _imgPlay = document.createElement('img');
            _imgPlay.setAttribute('src', _imgPlaySrc);
            _imgPlay.setAttribute('style', _imgPlayStyle);
            dDiv.appendChild(_imgPlay);
            dDiv.setAttribute("style", "width:"+w+";height:"+h+";background:transparent url("+_poster+") center center no-repeat;"); 
            dDiv.addEventListener('click', function() {
                window.location.href = oVideoInfo.link ;
            }, true);
        }
    }
	
	this.buildHTML5Context = function(idTarget,idVideo,w,h,params){
		
		window.user_poster = false;
		
		this.log("buildHTML5Context " + idTarget);
		this._isHTML5		= true;
		
		this._paramsHTML5 	= params;
		
		this._idTarget		= idTarget;
		
		this._idVideo		= idVideo;
		this._videoWidth	= w;
		this._videoHeight	= h;
		
		
		if(typeof MP_MMM == "undefined"){
			if(typeof timerCheckHtml5Player != "undefined"){
				this.log('WARNING : attempt to create another HTML5 player');
			}else{
				this.appendScriptTo("head",mmmVisitData.uBase+'/'+this._account+'/player/js/MediaPlayerMMM.js');
				this.appendScriptTo("head",mmmVisitData.uBase+'/'+this._account+'/player/js/ttm2.js');
				timerCheckHtml5Player	=	setInterval(this._name+'.launchHTML5Player()', 100);
			}
		}else{
			this.launchHTML5Player();
		}		
	}
		
	
	this.launchHTML5Player = function(forceQuality, newSubtitleURL){
        //console.log(ttm2_loaded);
		if( typeof MP_MMM != "undefined" && typeof ttm2_loaded != "undefined" ){
			
			this.log("launchHTML5Player " + this._idVideo+"  "+ this._idTarget);
			window.clearInterval(timerCheckHtml5Player);
	 
			var oVideoInfo      = JSON.parse(this.get_video(this._idVideo,forceQuality));	
			MP_MMM.createPlayer(this._idTarget,
								this._videoWidth,
								this._videoHeight,
								oVideoInfo.link+"?"+oVideoInfo.params,
								this._paramsHTML5,
								{
									quality 	: oVideoInfo.quality,
									bufferTime 	: oVideoInfo.bufferTime,
									poster		: oVideoInfo.poster,
									json		: oVideoInfo.json
								});
								
			//gestion des sous-titre		
			if( (typeof this._paramsHTML5.subtitleURL != "undefined") && (typeof this._paramsHTML5.subtitleFCT == "function")  ){
				var caption = new mmm_Caption();    
				if( typeof newSubtitleURL != "undefined" ){
					this._paramsHTML5.subtitleURL = newSubtitleURL;
				}
				caption.src = this._paramsHTML5.subtitleURL;
				var tempParams = this._paramsHTML5;
				
				function update(e) {
					var regions = caption.mmm_ttml_parser.getRegions();
					for( var i=0; i< regions.length;  i++){
						tempParams.subtitleFCT( caption.getCues(e.target.currentTime*1000, getIdAttribute(regions[i])), getIdAttribute(regions[i]) );
    			}
    		}
    		caption.make_caption(
    			0, //desactivation du tick
    			function() {  //callback de start
    				MP_MMM._media.addEventListener('timeupdate', update );
    			},
    			function(){} //callback update
    		);
		 }
		 
		 var lfixPoster = false;
		 if( typeof this._paramsHTML5.fixPoster != "undefined"){
		 	lfixPoster = !!this._paramsHTML5.fixPoster;
		 }
		 
		 if (lfixPoster && (this.device == 'iPad'||this.device == 'android'||this.device == 'tablet') ) {
            document.getElementById(this._idTarget).setAttribute('style', 'display:none;position:relative;z-index:1;border:1px solid #f00');
            var _imgPlaySrc = mmmVisitData.uBase+'/'+this._account+'/player/btn_play.png';
            var _imgPlayStyle = "position:absolute;top:50%;left:50%;margin:-78.5px 0 0 -78.56px;z-index:30;border:none;" ;
            var _self = this ;
            var dDiv = document.createElement('div');
            var dImgPlay = document.createElement('img');
            var _target = document.getElementById(this._idTarget) ;
            var _video = MP_MMM._media ;
            dImgPlay.setAttribute('src', _imgPlaySrc);
            dImgPlay.setAttribute('style', _imgPlayStyle);
            dDiv.appendChild(dImgPlay);
            dDiv.setAttribute("style", "position:absolute;top:0;left:0;z-index:299;width:"+this._videoWidth+"px;height:"+this._videoHeight+"px;background:transparent url("+oVideoInfo.poster+") center center no-repeat;");
            
            MP_MMM._media.addEventListener('click', function(e) {
                MP_MMM._media.play();
            });
            
            dImgPlay.addEventListener('click', function(e) {
                _target.parentNode.removeChild(dDiv);
                _target.setAttribute('style', 'display:block;');
                
                var evt = document.createEvent("MouseEvents");
                    evt.initMouseEvent("click", true, true, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
                
                MP_MMM._media.dispatchEvent(evt);
                
            }, false);
            
            document.getElementById(this._idTarget).parentNode.appendChild(dDiv);
         }
         
		}else{
			this.log("buildHTML5Context MP_MMM is not defined");
		}
	}
		
	this.getMediaPlayer = function (){
		
		if(this._isHTML5){
			if(typeof MP_MMM != "undefined"){
				return MP_MMM._media;
			}else{
				return undefined;
			}
		}else{
			thisMovie(this._idTarget);
		}
		
	}
	
	this.getCurrentTime = function (){
		
		if(this._isHTML5){
			if(typeof MP_MMM != "undefined"){
				return MP_MMM._media.currentTime;
			}else{
				return undefined;
			}
		}else{
			thisMovie(this._idTarget);
		}
		
	}
	
	this.addEventListener = function(type ,func){
		this._aListener.push({type:type,func:func});	
	}
	
	this.removeEventListener  = function(type ,func){
		for ( i=0; i<this._aListener.length; i++)
		{
			if(this._aListener[i].type==type && this._aListener[i].func==func);
		}
	}
	
	this.dispatchEvent = function (type,e){
		for ( i=0; i<this._aListener.length; i++)
		{
			if(this._aListener[i].type==type)this._aListener[i].func(e);
		}
	}
	
	this.play = function(){
		
		if(this._isHTML5){
			MP_MMM._media.play();
		}else{
			thisMovie(this._idTarget).playVideo();
		}
	}
	
	this.pause = function(){
		
		if(this._isHTML5){
			MP_MMM._media.pause();
		}else{
			var tmp = thisMovie(this._idTarget); //? pk tmp ?
			tmp.pause();
		}
	}
	
	this.playPause  = function(){
		
		//alert('playPause this._isHTML5 ' + this._isHTML5 );
		
		if(this._isHTML5){
			if(MP_MMM._media.paused){
				MP_MMM._media.play();
			}else{
				MP_MMM._media.pause();
			}
		}else{
			thisMovie(this._idTarget).playPause();
		}
	}
	
	this.rewind = function (){
		if(this._isHTML5){
			MP_MMM._media.pause();
			MP_MMM._media.currentTime = 0.0;
		}else{
			thisMovie(this._idTarget).rewindVideo();
		}
	}
	
	this.replay = function (){
		if(this._isHTML5){
			MP_MMM._media.pause();
			MP_MMM._media.currentTime = 0.0;
			MP_MMM._media.play();
		}else{
			thisMovie(this._idTarget).replay();
		}
	}
	
	this.seek = function (val){//float
		if(this._isHTML5){
			MP_MMM._media.pause();
			MP_MMM._media.currentTime = val.toFixed(2);
			MP_MMM._media.play();
		}else{
			thisMovie(this._idTarget).seek(val*1000);
		}
	}
	
	this.changeVideo = function(idVideo,autoStart,forceQuality, subtitleURL){
		
		this._idVideo					= idVideo;
		if(this._isHTML5){
			this._paramsHTML5.autoStart = autoStart;
			this.launchHTML5Player(forceQuality, subtitleURL);
		}else{
			thisMovie(this._idTarget).changeVideo(idVideo,autoStart,forceQuality, subtitleURL);
		}
	}	
	
	this.close = function(fJsFunc){
		if(this._isHTML5){
			this.removePlayer();
		}else{
			thisMovie(this._idTarget).close(fJsFunc);
		}
	}
	
	this.mute = function(){
		if(this._isHTML5){
			MP_MMM._media.muted   = true;
		}else{
			thisMovie(this._idTarget).mute();
		}
	}
	
	this.volume = function(val){
		if(this._isHTML5){
			MP_MMM._media.muted   = false;	
			MP_MMM._media.volume  = val;
		}else{
			thisMovie(this._idTarget).volume(val*100);
		}
	}
	
	this.soundMute = function(){
		if(this._isHTML5){
			if(MP_MMM._media.muted){
				MP_MMM._media.muted   = false;
				//MP_MMM._media.volume  = 1;
			}else{
				MP_MMM._media.muted   = true;
				//MP_MMM._media.volume  = 0;
			}
		}else{
			thisMovie(this._idTarget).soundMute();
		}
	}
	
	this.removePlayer = function(){
		var target     = document.getElementById(this._idTarget);
		if(!this._isHTML5)target         = target.parentNode;
		while (target.hasChildNodes())
		    target.removeChild(target.firstChild);
	}	
	
	this.appendScriptTo = function(idTarget,scriptUrl){
		var headID 			= document.getElementsByTagName(idTarget)[0];         
		var newScript	 	= document.createElement('script');
		newScript.type 		= 'text/javascript';
		newScript.src 		= scriptUrl+'?rnd='+Math.round(Math.random()*109990000);
		headID.appendChild(newScript);
		return newScript;
	}
	
}


window.playlistMMM=function()
{
	this.getProjectList = function (){
		var aList = new Array();
		var prop;
		for (prop in PLAYLIST_MMM_DATA){
			var val = PLAYLIST_MMM_DATA[prop].project;
			//if(aList.indexOf(val)==-1)
			if (is_in_array(aList,val)<0) aList.push(val);
		}
		return aList;
	}
	
	this.getResourceList = function (project){
		var aList = new Array();
		var prop;
		for (prop in PLAYLIST_MMM_DATA){
			if (typeof project == "undefined" || project == PLAYLIST_MMM_DATA[prop].project) {
				var val = PLAYLIST_MMM_DATA[prop].id;
				//if(aList.indexOf(val)==-1)aList.push(val);
				if (is_in_array(aList,val)<0) aList.push(val);
			}
		}
		return aList;
	}
	
	this.getPublicationList = function (id){
		var aList = new Array();
		var prop;
		var quality;
		var filename;
		for (prop in PLAYLIST_MMM_DATA){
			if (typeof id == "undefined" || id == PLAYLIST_MMM_DATA[prop].id) {
				for (quality in PLAYLIST_MMM_DATA[prop].qualities){
					filename = PLAYLIST_MMM_DATA[prop].qualities[quality].filename;
					//if(aList.indexOf(filename)==-1)aList.push({label:filename,quality:quality});
					if (is_in_array(aList,filename)<0)aList.push({label:filename,quality:quality});
				}	
			}
		}
		return aList;
	}
	
	this.getVideosByDevice = function(id)
	{
		var aList = new Array();
		var aResult = new Array();
		
		var aListFallback = new Array();
		var aResultFallback = new Array();
		var prop;
		var quality;
		var q;
		var videoId;
		
		for (prop in PLAYLIST_MMM_DATA){
			if (typeof id == "undefined" || id == PLAYLIST_MMM_DATA[prop].id) {
				for (q in PLAYLIST_MMM_DATA[prop].quality_profile_list){
					quality=PLAYLIST_MMM_DATA[prop].quality_profile_list[q];
					videoId=quality.video;
					var obj=object_clone(PLAYLIST_MMM_DATA[prop].videos[videoId]);
					obj.quality=quality.label;
					obj.quality_id=q;
							
					if( quality.device == "fallback"){
						if (is_in_array(aListFallback,videoId)<0){
							aListFallback.push(videoId);							
							aResultFallback.push(obj);
						}
					}
					
					if (eval('this._currentDevice.'+quality.device)) {					
						if (is_in_array(aList,videoId)<0){
							aList.push(videoId);							
							aResult.push(obj);
						}
					}
				}
			}
		}
		
		return aResult.length == 0
			? aResultFallback
			: aResult;
	
	}
	
	this.mediaPropertiesByQuality = function(id)
	{
		var res=this.getVideosByDevice();
		return JSON.stringify(res)
	}

}



window.mmmRightNow=function()
{
	time = new Date();
	return time.getTime();
}

window.debugMMM=function()
{
	
	this.log = function(message){
		try{
			if(typeof LOG_MMM != "undefined")LOG_MMM.log(message);
			else {
				if (window.console) window.console.log(message);
			}
		}catch(e){}
	}
		
}

window.mmmDebugParams=function()
{
	mmmVisitData.oDebugParams={"tester":"unknown","cdn":"","buffer":0,"debug":0,"quality":"","video":"","streaming":0};
	var sDbgWhat="debug_params=";
	try {
		var fpos=window.location.search.substr(1).indexOf(sDbgWhat);
		
		if (fpos>=0) {
			var s=fpos+sDbgWhat.length;
			var e=window.location.search.substr(s).indexOf('&');
			if (e<0) e=window.location.search.length-1;
			else e=e-1;
			var what=unescape(window.location.search.substr(1).substr(s,e));			
			try {
				var oRes=JSON.parse(what);
			}
			catch(e){alert('debug_parames error : parametre non reconnu');}
			
			
			if (oRes.cdn!==undefined) mmmVisitData.oDebugParams.cdn=oRes.cdn;
			if (oRes.tester!==undefined) mmmVisitData.oDebugParams.tester=oRes.tester;
			if (oRes.buffer!==undefined) mmmVisitData.oDebugParams.buffer=oRes.buffer;
			if (oRes.debug!==undefined) mmmVisitData.oDebugParams.debug=oRes.debug;
			if (oRes.quality!==undefined) mmmVisitData.oDebugParams.quality=oRes.quality;
			if (oRes.video!==undefined) mmmVisitData.oDebugParams.video=oRes.video;
			if (oRes.streaming!==undefined) mmmVisitData.oDebugParams.streaming=oRes.streaming;
			
			if (mmmVisitData.oDebugParams.cdn!="") {
				for (var i=0;i<this.aCDNs.length;i++){
					if (this.aCDNs[i].name==mmmVisitData.oDebugParams.cdn) 
					{
						mmmVisitData.uBase='http://'+this.aCDNs[i].host;
						//this.uRefVideo=mmmVisitData.uBase+'/'+mmmVisitData.sClientName+'/movies/ID';
						mmmVisitData.sCurrentCDN=mmmVisitData.oDebugParams.cdn;
						this.nCurrentPos=i+1;
						break;
					}
				}				
			}
		}
	}
	catch(e){
	}
}



window.mmmIdentity=function()
{
	this.sIdentityScrId='scrMmmIdentity';
	this.uIdentityScr='identity.js';
	
	this.checkCDN = function ()
	{
		var redirect=mmmVisitData.uBase+'/'+mmmVisitData.uPerf+'/'+this.uIdentityScr+'?rnd='+mmmRightNow();
		var iframe=this.appendScriptTo('head',redirect);
		external_objects.oIdentityScr=iframe;
	}
}

window.setIdentity=function(sName)
{
	mmmVisitData.sRadarCDN=sName;
	if (!mmmVisitData.bBkUsed)
		mmmVisitData.sCurrentCDN=sName;
}

window.mmmRadar=function()
{
	this.startRadar = function ()
	{
		
		var iframe=null;
		iframe = document.createElement("IFRAME");
		iframe.setAttribute('src',mmmVisitData.uRadarPath);
		iframe.setAttribute('border','0');
		iframe.setAttribute('frameborder','0');
		iframe.setAttribute('hspace','0');
		iframe.setAttribute('vspace','0');
		iframe.id='cdxradar';
		iframe.name='cdxradar';
		iframe.style.width='0px';
		iframe.style.height='0px';
		iframe.style.margin='0';
		iframe.style.position='absolute';
		iframe.style.bottom='0px';
		iframe.style.right='0px';
		iframe.style.zIndex=0;
		iframe.style.background='transparent';
		document.body.appendChild(iframe);
	}
}



window.mmmMediaPrebuffering=function ()
{
	//prebuffering
	
	mmmVisitData.nFailTime=mmmVisitData.nBufferTime+mmmVisitData.nFailDt;
	
	this.computeBufferTime = function ()
	{
		external_objects.aPrebufferingLevels=new Array();
		for (var seuil in external_objects.aPrebuffering) {
			external_objects.aPrebufferingLevels.push(seuil);
		}
		external_objects.aPrebufferingLevels=external_objects.aPrebufferingLevels.sort(function(a,b){return b - a});
		for (var i in external_objects.aPrebufferingLevels) {
			var seuil=external_objects.aPrebufferingLevels[i];
			//alert(seuil);
			if (seuil<=this.nBitrate) {
				mmmVisitData.nBufferTime=external_objects.aPrebuffering[seuil];
				break;
			}
		}
		mmmVisitData.nBufferTime*=mmmVisitData.nBufferMultiplier;
	};
	
	
};

window.mmmCheck=function()
{
	this.aCDNs=mmmVisitData.aCDNs;
	//mmmVisitData.nDebitSize=20447;
	//this.sDebitF="debit.jpg";
	
	this.iCheckTimeout=null;
/*	if (mmmVisitData.oDebugParams.cdn=="")*/
		this.iCheckTimeout=window.setTimeout(this._name+'.CalTimeout()',mmmVisitData.nCheckTimeout);
	
	this.start_ping = function ()
	{
		mmmVisitData.tPing=mmmRightNow();
		external_objects.oImgPing = new Image();
		external_objects.oImgPing.src=mmmVisitData.uBase+'/'+mmmVisitData.uPerf+'/'+mmmVisitData.sPingF+'?rnd='+mmmVisitData.tPing;
		external_objects.oImgPing.onload = function()
		{
			CTRL_MMM.CalPing();
		};
	}
	this.start_debit = function ()
	{
		
		mmmVisitData.tVideo=mmmRightNow();
		external_objects.oImgDebit = new Image();
		external_objects.oImgDebit.src=mmmVisitData.uBase+'/'+mmmVisitData.uPerf+'/'+mmmVisitData.sDebitF+'?rnd='+mmmVisitData.tVideo;
		external_objects.oImgDebit.onload = function()
		{
			CTRL_MMM.CalSp();
		};
	}
	
	this.CalTimeout = function ()
	{
		for (var i=0;i<this.aCDNs.length;i++){
			if (this.aCDNs[i].name==mmmVisitData.sBackupCDN) 
			{
				mmmVisitData.bBkUsed=true;
				mmmVisitData.sCurrentCDN=mmmVisitData.sBackupCDN;
				this.nCurrentPos=i+1;
				mmmVisitData.uBase='http://'+this.aCDNs[i].host;
				//this.uRefVideo=mmmVisitData.uBase+'/'+mmmVisitData.sClientName+'/movies/ID';
				mmmVisitData.nLatency=-1;
				mmmVisitData.nBitrate=-1;
				
				try{external_objects.oImgPing.onload = null;}catch(e){}
				try{external_objects.oImgDebit.onload = null;}catch(e){}
				try{external_objects.oImgPing=null;}catch(e){}
				try{external_objects.oImgDebit=null;}catch(e){}
				
				this.start_ping();
				
				break;
			}
		}
	}
	
	this.CalPing = function ()
	{
			
		try {if (mmmVisitData.nLatency==0) window.clearTimeout(this.iCheckTimeout);}catch(e) {}
		var timeStart = mmmVisitData.tPing;
		var timeEnd=mmmRightNow();
		
		mmmVisitData.nLatency=timeEnd-timeStart;
		if (mmmVisitData.nLatency<0) mmmVisitData.nLatency=0;
		this.start_debit();

	}

	this.CalSp = function ()
	{
		try {if (mmmVisitData.nBitrate==0) window.clearTimeout(this.iCheckTimeout);}catch(e) {}
		var timeStart2 = mmmVisitData.tVideo;
		var timeEnd2 = mmmRightNow();
		var timeElapsed =timeEnd2 - timeStart2;
		if (timeElapsed>mmmVisitData.nLatency)
		    timeElapsed-=mmmVisitData.nLatency;
			
		
		timeElapsed /= 1000.0;
		if (timeElapsed<=0) {
		  mmmVisitData.nBitrate = 0;
		}
		else {
		  mmmVisitData.nBitrate = parseInt(mmmVisitData.nMultiplier*mmmVisitData.nDebitSize*8/(1024.0*timeElapsed));
		}
		this.log('CalSp '+mmmVisitData.nDebitSize+'*8/1024*(('+timeEnd2+' - '+timeStart2+')/1000) = '+mmmVisitData.nBitrate);
		
		mmmVisitData.nRealBitrate=mmmVisitData.nBitrate;
		
		if (mmmVisitData.uRadarPath!='')
			this.startRadar();
		mmmVisitData.tVisitStarted=mmmRightNow();
		//this.startDebug();
		
		CTRL_MMM.onBitrate();//TODO ??
	}

	this.startCheck = function () {
		
		this.start_ping();
//		this.start_debit();
	}
}

window.mmmVideo=function(_name,id,pos,forcedQuality)
{
	this._name=_name;
	this.sVideoId=id;
	this.nVisitPosition=pos;
	if ((forcedQuality==null)||(forcedQuality=='undefined')) this.sForcedQuality='';
	else this.sForcedQuality=forcedQuality;
	
	if (mmmVisitData.oDebugParams.quality!='') {
		this.sForcedQuality=mmmVisitData.oDebugParams.quality;
	}
	if (mmmVisitData.oDebugParams.video!='') {
		this.sVideoId=mmmVisitData.oDebugParams.video;
	}
	


	this.nBitrate=mmmVisitData.nBitrate;
	
	this.nVHeight=0;
	this.nVWidth=0;
	this.nVLength=0;
	
	this.aSeeks=new Array();
	this.aTrackingEvents=new Array();
	
	this.nVideoDuration=0;
	this.tVStarted=0;
	this.nVideoDownloadCompleted=-1;
	
	this.nVideoCompletion={'0':0,'25':0,'50':0,'75':0,'100':0};
	this.nVideoDelta=2000;
	
	//prebuffering
	mmmMediaPrebuffering.call(this);

	//debug
	debugMMM.call(this);
	
	
	this.start = function ()
	{
		this.tVStarted=mmmRightNow();
		this.nVisitTime=mmmRightNow()-mmmVisitData.tVisitStarted;
		
		this.computeBufferTime();
		if (mmmVisitData.oDebugParams.buffer>0) mmmVisitData.nBufferTime=mmmVisitData.oDebugParams.buffer;
		
// 		this.log("buffertime : "+mmmVisitData.nBufferTime);
		
		mmmVisitData.nFailTime=mmmVisitData.nBufferTime+mmmVisitData.nFailDt;
		
		try {
			if (PLAYLIST_MMM_DATA[this.sVideoId] === undefined)
				return {do_query:'NONE'};
		}
		catch(e) {return {do_query:'NONE'}; }
		this.sVideoQuality='';
		this.nBwLimit=mmmVisitData.nBwLimit;
		
		this.qualities=new Array();
		this.qualities=CTRL_MMM.getVideosByDevice(this.sVideoId);
		
	//	this.qualities=this.qualities.sort(sortByNumber).reverse();
		this.qualities=this.qualities.sort(sortByBitrateDescending);	
 //		this.log(this.qualities);
 
		if ((this.sForcedQuality=='')||(this.qualities.length<=this.sForcedQuality)) {
			for (var qual in this.qualities) {
				if (this.qualities[qual].bitrate<=this.nBitrate) {
					this.sVideoQuality=qual;
					break;
				}
			}
			if ((this.sVideoQuality=='')||(this.sVideoQuality==null)) {
				for (var qual in this.qualities) 
					this.sVideoQuality=qual;
			}
		}
		else {
		    this.sVideoQuality=this.sForcedQuality;
		}
 		
  		this.log("videoquality : "+this.sVideoQuality);
		
		this.uBase=mmmVisitData.uBase+'/'+mmmVisitData.sClientName+'/'+mmmVisitData.uRefVideo+'/'+ PLAYLIST_MMM_DATA[this.sVideoId].id;
//  		this.log("video.start uBase="+this.uBase);
		
		this.sVFName=this.qualities[this.sVideoQuality].filename;
 		this.log("video.start sVFName="+this.sVFName);
		
		PLAYLIST_MMM_DATA[this.sVideoId].qualities=this.qualities;
		this.uVideo=this.uBase+'/videos/'+ this.sVFName;

		try{
		  if (mmmVisitData.sCurrentCDN!=''){
			var reg=/^(http:\/)?\/?([^:\/\s]+)((\/\w+)*\/)/;
			var sHost='';
			var m=this.uVideo.match(reg);
			if (m) {
				sHost=m[2];
			}
			if (sHost!='') {
				for (var i=0;i<mmmVisitData.aCDNs.length;i++){
					if (mmmVisitData.aCDNs[i].name==mmmVisitData.sCurrentCDN) {
			  
					    var url=mmmVisitData.aCDNs[i].host;
					    var reg=new RegExp("("+sHost+")", "g");
					    this.uVideo=this.uVideo.replace(reg,""+url+"");
					}
				}
			}
		  }
		}
		catch(e){this.log('video.start CDN-direct URL error : '+e);}
		
		this.uPoster='';
		if (PLAYLIST_MMM_DATA[this.sVideoId].poster != null) {
			if (PLAYLIST_MMM_DATA[this.sVideoId].poster.substring(0,7)=='http://') {
				this.uPoster=PLAYLIST_MMM_DATA[this.sVideoId].poster;
			}
			else {
				if(PLAYLIST_MMM_DATA[this.sVideoId].poster!=""){
					this.uPoster=this.uBase+'/datas/'+PLAYLIST_MMM_DATA[this.sVideoId].poster;
				}else{
					if(window.user_poster){//SI PAS DE POSTER ET QU'UN POSTER A ETE DEFINIE EN FLASHVARS
						this.uPoster=window.user_poster;
					}
				}
			}
		}

		this.log("video.start uPoster="+this.uPoster);
		this.mode=mmmVisitData.sStreamMode;
		if (CTRL_MMM._isHTML5) {
			this.mode="pgd";
		}
		
		this.seek_param='';
		this.params=''
		//alert(mmmVisitData.oDebugParams.streaming);
		if (mmmVisitData.oDebugParams.streaming==1) {
		      this.mode='str';
		      this.seek_param='start';
		}
		
		if (this.mode!='pgd') {
// 			this.params='visiteid='+mmmVisitData.vt_id+'&idhdprefix=9726051&mode='+this.mode+'&bufferTime='+mmmVisitData.nBufferTime;
			if (mmmVisitData.sCurrentCDN=='ec') {this.seek_param='ec_seek';}
			else {this.seek_param='start';}
			this.params='mode='+this.mode;
		}
		else {
			this.params='mode='+this.mode;
		}
			
		this.params+="&version="+mmmVisitData.nVideoVer;
		var res={json:JSON.stringify(PLAYLIST_MMM_DATA[this.sVideoId]),link:this.uVideo,poster:this.uPoster,params:this.params,quality:this.sVideoQuality,bufferTime:mmmVisitData.nBufferTime,performanceDelay:mmmVisitData.nPerfDelay,performanceDuration:mmmVisitData.nPerfDuration,performanceLevel:mmmVisitData.nPerfLevel,failureDelay:mmmVisitData.nFailDt,cdn:mmmVisitData.sCurrentCDN,seekParamName:this.seek_param};
		this.log("video.start res="+res);
		return res;
	};
	
	this.computeCompletion = function (caller,id,quality,flv_position,nVideoDelta)
	{
		var sType='COMPLETION';

		try {
// 			this.log('computeCompletion('+id+','+quality+','+flv_position+'), duration = '+parseInt(PLAYLIST_MMM_DATA[this.sVideoId].qualities[this.sVideoQuality].duration*1) +', seeks='+this.aSeeks.length);
			
			if (this.aSeeks.length!=1) return;
			
			if (!this.nVideoCompletion['100']) {
				if ((!this.nVideoCompletion['0']) && (flv_position<=nVideoDelta) && (flv_position!=0))
				{
					this.nVideoCompletion['0']=1;
					this.aTrackingEvents.push({nPos:flv_position,sEvent:sType,sV:'0'});
					caller.tracking_evt(id,quality,flv_position,sType,'0');
				}
				var quarter=parseInt(PLAYLIST_MMM_DATA[this.sVideoId].qualities[this.sVideoQuality].duration*1)/4;
				if ((!this.nVideoCompletion['25']) && (quarter-nVideoDelta<=flv_position) && (flv_position<=quarter+nVideoDelta))
				{
					this.nVideoCompletion['25']=1;
					this.aTrackingEvents.push({nPos:flv_position,sEvent:sType,sV:'25'});
					caller.tracking_evt(id,quality,flv_position,sType,'25');
				}
				
				var half=parseInt(PLAYLIST_MMM_DATA[this.sVideoId].qualities[this.sVideoQuality].duration*1)/2;
				if ((!this.nVideoCompletion['50']) && (half-nVideoDelta<=flv_position) && (flv_position<=half+nVideoDelta))
				{
					this.nVideoCompletion['50']=1;
					this.aTrackingEvents.push({nPos:flv_position,sEvent:sType,sV:'50'});
					caller.tracking_evt(id,quality,flv_position,sType,'50');
					
				}
				
				var tri=parseInt(PLAYLIST_MMM_DATA[this.sVideoId].qualities[this.sVideoQuality].duration*1)*3/4;
				if ((!this.nVideoCompletion['75']) && (tri-nVideoDelta<=flv_position) && (flv_position<=tri+nVideoDelta))
				{
					this.nVideoCompletion['75']=1;
					this.aTrackingEvents.push({nPos:flv_position,sEvent:sType,sV:'75'});
					caller.tracking_evt(id,quality,flv_position,sType,'75');
					
				}
				
				if (flv_position>=parseInt(PLAYLIST_MMM_DATA[this.sVideoId].qualities[this.sVideoQuality].duration*1)-nVideoDelta)
				{
					this.nVideoCompletion['100']=1;
					this.aTrackingEvents.push({nPos:flv_position,sEvent:sType,sV:'100'});
					caller.tracking_evt(id,quality,flv_position,sType,'100');
					
				}
			}
		}
		catch(e) {this.log('computeCompletion error: '+e);}
	};
	
}

window.trackingMMM=function()
{
	this.oVisit=mmmVisitData;
	//this.oVisit.uRefVideo=this.oVisit.sClientName+'/movies/';
	//this.oVisit.uRefVideo=this.oVisit.sClientName+'/projects';
	this.nCurrentPos=-1;
	this.bNetLag=false;
	
	this.do_tracking= function()
	{
// 		this.log("do_tracking length="+arguments.length);
		var params='vt_id='+mmmVisitData.vt_id;
		var player='flash';
		if (this._isHTML5) player="html5";
		params+='&player='+player;
		var cdn=mmmVisitData.sCurrentCDN;
		if (cdn=='') cdn='other'
		params+='&cdn='+cdn;
		params+='&device='+this.device;
		params+='&os='+this.os;
		params+='&browser='+this.browser;
		params+='&screen_width='+this.screen_width;
		params+='&screen_height='+this.screen_height;
		params+='&domain='+window.location.hostname;
		params+='&playlist='+this.playlist;
		
		params+='&tracker=';
		
		params+=arguments[0]+';'; //eventType
		params+=PLAYLIST_MMM_DATA[arguments[1]].id_mmm+';'; //ressource id
		params+=PLAYLIST_MMM_DATA[arguments[1]].qualities[arguments[2]].quality_id+';'; //ressource content
		params+=PLAYLIST_MMM_DATA[arguments[1]].qualities[arguments[2]].quality+';'; //quality string
		params+=PLAYLIST_MMM_DATA[arguments[1]].qualities[arguments[2]].id_mmm; // video ID
		for(var j=3;j<arguments.length;j++){
			params+=';';
			params+=arguments[j];
		}
// 		this.log("do_tracking : params="+params);
		try {
			var url=this.oVisit.uTracking+'/'+this.oVisit.sClientName+'/'+this.oVisit.uTrackingScript+'?'+params;
		}
		catch(e) {}
		this.log("do_tracking : "+url);
		var trackIMG=new Image();
		trackIMG.width=0;
		trackIMG.height=0;
		trackIMG.src=url;
	};
	
	
		
	this.get_video = function (id,forcedQuality)
	{
// 		if (this.oVisit.oDebugParams.quality!="") {forcedQuality=this.oVisit.oDebugParams.quality;}
// 		if (this.oVisit.oDebugParams.video!="") {id=this.oVisit.oDebugParams.video;}
		
		this.log("get_video. " + id+"  "+forcedQuality);
		
		var oVideo=new mmmVideo(this._name+'.oVisit.aVideos',id,this.oVisit.aVideos.length,forcedQuality)
		this.oVisit.aVideos.push(oVideo);
		var res=JSON.stringify(oVideo.start());
						
		return res;
	};
	
	this.init_flash =  function(flashdata)
	{
		var myObj ={version:mmmVisitData.nVideoVer, bwLimit:mmmVisitData.nBwLimit, latency:mmmVisitData.nLatency, bandwidth:mmmVisitData.nBitrate};
		this.log("init_flash. " + flashdata.substring(0,10)+" return :: "+JSON.stringify(myObj));
		//this.do_tracking('INIT',escape(flashdata))
		return JSON.stringify(myObj);
	}
	
	
	
	this.seek_evt = function(id,quality,from,to)
	{
		var oVideo=this.get_video_object(id,quality);
		if (oVideo._name=='') return;
		this.log('seek_evt. from='+from+' , to='+to);
		this.oVisit.nVisitDuration=mmmRightNow()-this.oVisit.tVideo;
		oVideo.nVideoDuration=mmmRightNow()-oVideo.tVStarted;
		if (oVideo.aSeeks.length!=1) {
			var last=oVideo.aSeeks[oVideo.aSeeks.length-1];
 			last['nT']=from;
			last['nTime']=from-last['nF'];
		}
		else {
			if ((quality=='')||(quality=='QUALITY')) {
				quality=oVideo.sVideoQuality;
			}
		  	this.do_tracking('SEEK',id,quality,Math.round(to/1000));

		}
		oVideo.aSeeks.push({nF:to,nT:0,nTime:0});
	}
	
	this.top_flv_evt = function(id,quality,position)
	{
		var oVideo=this.get_video_object(id,quality);
		if (oVideo._name=='') return;
		this.oVisit.nVisitDuration=mmmRightNow()-this.oVisit.tVideo;
		oVideo.nVideoDuration=mmmRightNow()-oVideo.tVStarted;
		if (oVideo.aSeeks.length!=1) {
			var last=oVideo.aSeeks[oVideo.aSeeks.length-1];
			last['nT']=position;
			last['nTime']=position-last['nF'];
		}
		if ((quality=='')||(quality=='QUALITY')) {
			quality=oVideo.sVideoQuality;
		}
		oVideo.computeCompletion(this,id,quality,position,oVideo.nVideoDelta);
	}
	
	// pour les completion swf
	this.top_swf_evt = function(id, quality, positionExpressedAsPercentage)
	{
// 		this.log('top_swf_evt ('+id+','+quality+','+positionExpressedAsPercentage+')');
		
		var oVideo=this.get_video_object(id,quality);
		if (oVideo._name=='') return;
		this.log(oVideo);
		
		if ((positionExpressedAsPercentage==0)&&(oVideo.aSeeks.length==0)) {
		  this.do_tracking('PERF_VIDEO',id,quality,mmmVisitData.nLatency,mmmVisitData.nBitrate);
		  oVideo.aSeeks.push({nF:0,nT:0,nTime:0});
		  this.do_tracking('START_VIDEO',id,quality,0,'');
		}
		this.oVisit.nVisitDuration=mmmRightNow()-this.oVisit.tVideo;
		oVideo.nVideoDuration=mmmRightNow()-oVideo.tVStarted;
		if (oVideo.aSeeks.length!=1) {
			var last=oVideo.aSeeks[oVideo.aSeeks.length-1];
			last['nT']=positionExpressedAsPercentage;
			last['nTime']=positionExpressedAsPercentage-last['nF'];
		}
		if ((quality=='')||(quality=='QUALITY')) {
			quality=oVideo.sVideoQuality;
		}
		oVideo.computeCompletion(this,id,quality,positionExpressedAsPercentage,2);
	}
	
	
	this.tracking_evt = function (id, quality, position, sType, sValue)
	{
		if (sValue===undefined) sValue='';
		var oVideo=this.get_video_object(id,quality);
		if (oVideo._name=='') return;
		this.log("tracking_evt. " + id+"  "+quality+"  "+position+"  "+sType+" "+sValue+", oVideo="+oVideo._name);
		this.oVisit.nVisitDuration=mmmRightNow()-this.oVisit.tVideo;
// 		this.log("tracking_evt. " + id+" "+'starting')
		
		if ((quality=='')||(quality=='QUALITY')) {
			quality=oVideo.sVideoQuality;
		}
		if (sType=="START_FLV") sType="START_VIDEO";
		
		if (sType=="NET_LAG") {
		  if (this.bNetLag) {return '';}
		  else {
		    this.bNetLag=true;
		  }
		}
		
		if (sValue!="") {
		      this.do_tracking(sType,id,quality,sValue,"");
		}
		else {
		      if ((sType!='COMPLETION')&&(sType!='START_VIDEO')&&(sType!='DL_COMPLETED')&&(sType!='END_FLV')) {
			    this.do_tracking(sType,id,quality,0,'');
		      }
		      else {
			    this.do_tracking(sType,id,quality,Math.round(position/1000),sValue);
		      }
		}	
		
		if (sType=="QUALITY_CHANGE") {
			this.top_flv_evt(id,quality,position);
		}
		else {
			oVideo.aTrackingEvents.push({nPos:position,sEvent:sType,sV:sValue});
		}
		if (sType=="PLAY") {
// 			this.log("tracking_evt. " + id+" "+'PLAY')
			oVideo.aSeeks.push({nF:0,nT:0,nTime:0});
			
// 			this.log("tracking_evt. " + id+" "+'PLAY')
		}
		if (sType=="START_VIDEO") {
			oVideo.nVideoPlayStarted=mmmRightNow()-oVideo.tVStarted;
			oVideo.computeCompletion(this,id,quality,position);
			if ((quality=='')||(quality=='QUALITY')) {
				quality=oVideo.sVideoQuality;
			}
			
			this.do_tracking('PERF_VIDEO',id,quality,mmmVisitData.nLatency,mmmVisitData.nBitrate)
		}
		if (sType=="DL_COMPLETED") {
			oVideo.nVideoDownloadCompleted=mmmRightNow()-oVideo.tVStarted;
		}
		if ((sType=="END_FLV")||(sType=="CLOSE_FLV")) {
			this.top_flv_evt(id,quality,position);
		}
/*		if (sType=="CLOSE_FLV") { this.dump();}
		if (sType=="END_FLV") {this.dump();}
*/		
		var res='';
		return res;
	};
	
}





window.controllerMMM=function(objectName)
{
	this._name=objectName;
	this._idTarget 		= '';
	this._account 		= mmmVisitData.sClientName;
	this._isHTML5		= false;
	this._isIpadOrIphone = false;
	this._isIpad 		= false;
	this._isIphone 		= false;
	this._idVideo		= '';
	this._videoWidth	= 0;
	this._videoHeight	= 0;
	this._aListener		= new Array();
	this._paramsHTML5	= undefined;
	
	this.browser='Other';
	this.os='Other';
	this.device='';
	this.screen_width='';
	this.screen_height='';
	this.playlist='default';
	this.bInitialized=false;
	
	
	this.onTracking = function()
	{
	};
	
	//debug
	debugMMM.call(this);
	
	//utils
	utilsMMM.call(this);
	
	//playlist
	playlistMMM.call(this);
	
	this.init = function(){
		if (this.bInitialized) return;

		this.bInitialized=true;
		
		
		this.log('--------- init controllerMMM ---------');
		
		
		var ua 				= navigator.userAgent;
		
		this._currentDevice=new Object();
		
		this._currentDevice.android			= !!ua.match(/Android/i);
		this._currentDevice.blackberry_html5= !!ua.match(/blackberry/i) && !!ua.match(/version\/7/i);
		this._currentDevice.blackberry		= !!ua.match(/blackberry/i);
		this._currentDevice.PlayBook		= !!ua.match(/PlayBook/i);
		this._currentDevice.iPad			= !!ua.match(/iPad/i);
		this._currentDevice.tablet			= (this._currentDevice.iPad || this._currentDevice.PlayBook || ( this._currentDevice.android && !ua.match(/mobi/i)) || !!ua.match(/GT-P1000/i) || !!ua.match(/Xoom/i) || !!ua.match(/ViewPad/i) || !!ua.match(/zt180/i)  || !!ua.match(/Dell Streak/i) || !!ua.match(/A101IT/i) || !!ua.match(/hp-tablet/i) );
		this._currentDevice.computer		= (!ua.match(/mobi/i) && !this._currentDevice.android && !this._currentDevice.blackberry && !this._currentDevice.tablet);
		this._currentDevice.mobile			= !this._currentDevice.computer;
		this._currentDevice.iPhone			= !!ua.match(/iPhone/i) || !!navigator.userAgent.match(/iPod/);
		this._currentDevice.iPhone4			= (this._currentDevice.iPhone && window.devicePixelRatio==2);
		this._currentDevice.iPhone3			= (this._currentDevice.iPhone && !this._currentDevice.iPhone4);
		this._currentDevice.iThings			= (this._currentDevice.iPad||this._currentDevice.iPhone);
		this._currentDevice.winPhone		= !!ua.match(/Windows Phone/i);
		
		this._currentDevice.web_iPad = this._currentDevice.computer || this._currentDevice.iPad;
		this._currentDevice.iPhone3_android_wp7 = this._currentDevice.iPhone3 || this._currentDevice.android || this._currentDevice.winPhone;
		
		// du générique au particulier
		this.device='computer';
		if (this._currentDevice.mobile) this.device='mobile';
		if (this._currentDevice.android) this.device='android';
		if (this._currentDevice.tablet) this.device='tablet';
		if (this._currentDevice.iThings) this.device='iThings';
		if (this._currentDevice.iPhone) this.device='iPhone';
		if (this._currentDevice.iPad) this.device='iPad';
		if (this._currentDevice.blackberry) this.device='blackberry';
		if (this._currentDevice.blackberry_html5) this.device='blackberry_html5';
		if (this._currentDevice.PlayBook) this.device='PlayBook';
		if (this._currentDevice.iPhone4) this.device='iPhone4';
		if (this._currentDevice.iPhone3) this.device='iPhone3';
		if (this._currentDevice.winPhone) this.device='winPhone';
				
		this.get_computer_data();

		this.appendScriptTo("head",mmmVisitData.uBase+'/'+this._account+'/player/playlist.js');
		
		if(this.getUrlVars()['debug']==1){
			if (typeof $ == "undefined") {
				this.appendScriptTo("head",mmmVisitData.uBase+'/'+this._account+'/debug/js/jquery-1.4.2.min.js');
			}
			this.appendScriptTo("head",mmmVisitData.uBase+'/'+this._account+'/debug/js/logger.js');
		}
		
		//debit
		mmmCheck.call(this);
		
		//debugParams
		mmmDebugParams.call(this);
		
		//identification cdn
		if (mmmVisitData.sCurrentCDN=='') {
			mmmIdentity.call(this);
			this.checkCDN();
		}
		
		//demarage du radar
		if (mmmVisitData.uRadarPath!='')
			mmmRadar.call(this);
		
		this.startCheck();
		
	}
	
	//appeler suite au calcul du débit
	this.onBitrate = function(){
		this.log('--------- onBitrate ---------');
		//fonction dans la page index : 
		if (this.oVisit!==undefined) {
			//this.do_tracking('PERF',mmmVisitData.nLatency+";"+mmmVisitData.nBitrate)
		}
		try{
		  initWebsite();
		}
		catch(e){}
	}

	
	
	//premiere fonction appel� par le flash
	this.isReady = function(){
		return '1';
	}
	
	//deuxieme fonction appel� par le flash
	this.init_flash =  function(flashdata)
	{
		//var myObj = {version:2,bwLimit:2000,bandwidth:1024,latency:110}	
		var myObj ={version:mmmVisitData.nVideoVer, bwLimit:mmmVisitData.nBwLimit, latency:mmmVisitData.nLatency, bandwidth:mmmVisitData.nBitrate};
		this.log("init_flash. " + flashdata.substring(0,10)+" return :: "+JSON.stringify(myObj));
			
		return JSON.stringify(myObj);
	}
	
	this.get_video = function (idVideo,forcedQuality){
		this._idVideo 	= idVideo;
		this.log("get_video. " + idVideo+"  "+forcedQuality);
		/*var myObj = {
			json:"{\"id\":\"test\",\"id_mmm\":\"test_truc\",\"ressource\":\"testmovie\",\"project\":\"default\",\"poster\":\"\",\"duration\":30,\"qualities\":{\"hq\":{\"filename\":\"espace1500x750_00_HQ.mp4\",\"bitrate\":1024},\"bq\":{\"filename\":\"espace1500x750_00_BQ.mp4\",\"bitrate\":728}}}",
			link:"http://webvideo.massmotionmedia.com/mmm_dev/projects/default/test/videos/espace1500x750_00_HQ.mp4",
			poster:"",
			params:"visiteid=0&idhdprefix=9726051&mode=pgd&bufferTime=2000",
			quality:"hq",
			bufferTime:2000,
			performanceDelay:1000,
			performanceDuration:3000,
			performanceLevel:50,
			failureDelay:30000,
			cdn:"mmmdev"
		};
		
		
		return JSON.stringify(myObj);
		*/
		var oVideo=new mmmVideo('',idVideo,0,forcedQuality)
		var res=JSON.stringify(oVideo.start());
		return res;
		
		
		
	}
	this.get_video_object = function (id,quality)
	{
		var oVideo=this.oVisit.aVideos[this.oVisit.aVideos.length-1];
		return oVideo;
	}
	
	this.set_meta_data = function (id, quality, duration, width, height){
		this.log("set_meta_data. " + id+"  "+quality+"  "+duration+"  "+width+"  "+height);
	}
	
	this.set_real_bw = function (id, quality,bandwidth, qualityNeeded){
	//	this.log("set_real_bw. " + id+"  "+quality+"  "+bandwidth+"  "+qualityNeeded);
		return 1;
	}
	
	this.top_flv_evt = function(id,quality,position){
		this.log("top_flv_evt. " + id+"  "+quality+"  "+position);
		//return TR_MMM.top_flv_evt(id, quality, position);
	}
	
	this.top_swf_evt = function(id,quality,positionExpressedAsPercentage){
		this.log("top_swf_evt. " + id+"  "+quality+"  "+positionExpressedAsPercentage);
	}
	
	this.seek_evt = function(id,quality,from,to){
		this.log("seek_evt. " + id+"  "+quality+"  "+from+"  "+to);
		//return TR_MMM.seek_evt(id, quality, from, to);
	}
	
	this.perf_evt = function( id, quality, fpsMin, fpsMax, fpsAvg, smoothing, stretching){
		this.log("perf_evt. " + id+"  "+quality+"  "+fpsMin+"  "+fpsMax+"  "+ fpsAvg +"  "+smoothing+"  "+stretching);
	}
	
	this.failure_evt = function( id, quality, type){
		
		if(type=="LAG" || type=="WARNING_ERROR") var myObj={do_query:'NONE'};
		//if(type=="FILE_NOT_FOUND") var myObj ={do_query:'NONE'};
		if ((type=="TIMEOUT")||(type=="FILE_NOT_FOUND")) {
			var oVideo=this.get_video_object(id,quality);
			var reg=/^(http:\/)?\/?([^:\/\s]+)((\/\w+)*\/)/;
			var sHost='';
			var m=oVideo.uVideo.match(reg);
			if (m) {
				sHost=m[2];
			}
			if (sHost=='') {
				res={doQuery:'NONE'};
				this.doDebug('failure_evt => '+res);
				return JSON.stringify(res);
			}
			
			if (this.nCurrentPos<this.aCDNs.length-1) {
				this.nCurrentPos++;
				var url=this.aCDNs[this.nCurrentPos].host;
				var reg=new RegExp("("+sHost+")", "g");
				oVideo.uVideo=oVideo.uVideo.replace(reg,""+url+"");
				mmmVisitData.sCurrentCDN=this.aCDNs[this.nCurrentPos].name;
			}
			else {
				res={doQuery:'NONE'};
				this.doDebug('failure_evt => '+res);
				return JSON.stringify(res)
			}
		
		
		
			res={doQuery:'NEW_LINK',json:JSON.stringify(PLAYLIST_MMM_DATA[oVideo.sVideoId]),link:oVideo.uVideo,poster:oVideo.uPoster,params :oVideo.params,quality:oVideo.sVideoQuality,bufferTime:mmmVisitData.nBufferTime,performanceDelay:mmmVisitData.nPerfDelay,performanceDuration:mmmVisitData.nPerfDuration,performanceLevel:mmmVisitData.nPerfLevel,failureDelay:mmmVisitData.nFailDt,cdn:mmmVisitData.sCurrentCDN};
			
			return JSON.stringify(res);
		}
		this.log("failure_evt. " + id+"  "+quality+"  "+type +" return :: "+JSON.stringify(myObj));
		return JSON.stringify(myObj);
		
	}
	
	this.tracking_evt = function( id, quality, position, type){
		this.log("tracking_evt. " + id+"  "+quality+"  "+position+"  "+type);
		//return TR_MMM.tracking_evt(id, quality, position, type);
		var res='';
		return res;
	}
	
	
	//tracking
	trackingMMM.call(this);
	

}

window.set_flash_id_for_embed=function(url)
{
  //url='webvideo';
  try {
    var els=document.getElementsByTagName('object');
    for (var i in els) {
        if (els[i].src==url) {
          CTRL_MMM._idTarget = els[i].id;
          CTRL_MMM.init();
          return els[i].id;
        }
    }
    var els=document.getElementsByTagName('embed');
    for (var i in els) {
        if (els[i].src==url) {
          CTRL_MMM._idTarget = els[i].id;
          CTRL_MMM.init();
          return els[i].id;
        }
    }
  }
  catch(e){alert(e);}
  return '';
}


if (!window.CTRL_MMM) window.CTRL_MMM	= new controllerMMM('CTRL_MMM');
//CTRL_MMM.startCheck(); cf CTRL_MMM.init()

