raismth.ns(function() { with (raismth.LIB) {
myDump("[RAISMTH] silverlight module initialization\n");

theApp.silverlight = {
	isInstalled : function(version, doc){		
		// 1.0.30226.2
		// 2.0.30226.2
		// 2.0.30511.0
		// version = '2.0.30511.0';
		let target = myWrapper(doc); 
		if (target.Silverlight) return target.Silverlight.isInstalled(version);
		return false;
	},

	unload : function(event){
		// todo
		// alert('slunload');
	},

	buildHTML : function(slProperties,target,doc){
		let index = false;
		if(doc.getElementById('raismthWindow')) {
			// alert(doc.getElementById('raismthWindow').getAttribute('name'));
			index = raismth.utils.purge_arrays(doc);
		}
		let domVideoURL = false;
		let scripts = doc.getElementsByTagName('script');
		for(var x = 0; x < scripts.length; x++){
		        if(scripts[x].innerHTML.indexOf('videoURL') != -1) {
		                let content = scripts[x].innerHTML;
		                let pattern_1 = content.indexOf('videoURL') + 12;
		                let pattern_2 = content.indexOf('"', pattern_1);
		                domVideoURL = content.substring(pattern_1, pattern_2);
		                break;
		        }
		}
		
		let d = raismth.silverlight.odump(slProperties);
		let initParams = slProperties.initParams.split(',');
		let myInitParams = {};
		for(let c = 0; c < initParams.length; c++){
			let n = initParams[c].substring(0, initParams[c].indexOf('='));
			let v = initParams[c].substring(initParams[c].indexOf('=') + 1);
			if(n == 'mediaUri') myInitParams.mediaURI = v;
			if(n == 'configUri') myInitParams.configUri = v;
			if(n == 'advertisingUri') myInitParams.advertisingUri = v;
			if(n == 'overrideConfig') myInitParams.overrideConfig = v;
		}
		myInitParams.domVideoURL = domVideoURL ? domVideoURL : myInitParams.mediaURI;
		// if(myInitParams.domVideoURL && myInitParams.domVideoURL != myInitParams.mediaURI) myInitParams.mediaURI = myInitParams.domVideoURL;
		initParams = initParams.join('\n                 ');
		let maxFramerate = slProperties.maxFramerate;
		let id = slProperties.id;
		let ts = (new Date()).getTime();
		let videoURL = target.videoURL;	
		let videoURL_M3U8 = target.videoURL_M3U8;
		let videoTitolo = target.videoTitolo ? raismth.utils.addslashes(target.videoTitolo) : '';
		let isUgc = target.isUgc;
		let subtitle = target.subtitle;
		let videoFormat = target.videoFormat;
		let estensioneVideo = target.estensioneVideo;
		let codificaVideo = target.codificaVideo;
		let skin = raismth.skin; 
		let bgcolor = '#3B5998';
		raismth.rai.identify(doc,ts,index);
		myDump('[RAISMTH] silverlight buildHTML : [ rai_windows_ts array : ' + raismth.rai_windows_ts.toString() + ' ]\n');
		let Prefs = Cc["@mozilla.org/preferences-service;1"].getService(Ci.nsIPrefBranch);
		let rai_windows_counter = Prefs.getIntPref("extensions.raismth.rai_windows_counter");
		myDump('[RAISMTH] silverlight buildHTML : rai_windows_counter: ' + rai_windows_counter + '\n');

		// #3B5998
		// #519ef8
		//  var cl = setTimeout(function(){ var tgt = document.getElementById(\'cctrl\'); tgt.click(); }, 2000);"
		//  var tt = document.getElementById(\'clipctrl\'); if(tt.style.display == \'block\') { var tgt = document.getElementById(\'cctrl\'); tgt.click();}
		// <pre>Clip controls ▼</pre>
		let html = '<table class=tblContainer><tr><td colspan=6 id=tdtop><div id=mask><pre><marquee id=marq direction=right scrollamount="10"><img src="chrome://raismth/skin/mask.png" /></marquee></pre></div><div id=raismthWindow name='+ts+'></div> <div id=status><img id=imgstatus src=""/></div> </td></tr><tr><td id=clipctrl><pre><div id=ctrl></div></pre></td> <td id=maincont colspan=6> <div id=embed></div> <div id=info> <pre>Logs ▼<br><textarea id=statusmsg name=statusmsg cols=80 rows=9></textarea></pre> <pre><span id=det onclick="show_det();">Stream Details ▼</span></pre><div id=details><pre> '+d+'  </pre> </div> </div></td></tr><tr></tr><tr><td class=tdBtn><img class=play id='+myInitParams.mediaURI+' onclick="play_content(\''+myInitParams.domVideoURL+'\', \''+videoTitolo+'\', \''+ts+'\', false, true);" onmouseover="this.src=\'chrome://raismth/skin/'+skin+'/play_64.png\'" onmouseout="this.src=\'chrome://raismth/skin/'+skin+'/play_48.png\'" src="chrome://raismth/skin/'+skin+'/play_48.png" alt="Play" title="Play" /></td><td class=tdBtn><img onclick="stop_player(\''+ts+'\');" onmouseover="this.src=\'chrome://raismth/skin/'+skin+'/stop_64.png\'" onmouseout="this.src=\'chrome://raismth/skin/'+skin+'/stop_48.png\'" src="chrome://raismth/skin/'+skin+'/stop_48.png" alt="Stop" title="Stop" /></td><td class=tdBtn><img onclick="var ret = play_content(\''+myInitParams.mediaURI+'\', \''+videoTitolo+'\', \''+ts+'\', true, true); if(ret) { var url = ret[0]; var playerObj = ret[1]; document.getElementById(\'embed\').innerHTML = playerObj; document.getElementById(\'maincont\').style.display = \'block\';} " onmouseover="this.src=\'chrome://raismth/skin/'+skin+'/embed_64.png\'" onmouseout="this.src=\'chrome://raismth/skin/'+skin+'/embed_48.png\'" src="chrome://raismth/skin/'+skin+'/embed_48.png" alt="Embedded Player" title="Embedded Player" /></td><td class=tdBtn><img onclick="document.getElementById(\'embed\').innerHTML = \'\'; stop_player(\''+ts+'\');" onmouseover="this.src=\'chrome://raismth/skin/'+skin+'/close_64.png\'" onmouseout="this.src=\'chrome://raismth/skin/'+skin+'/close_48.png\'" src="chrome://raismth/skin/'+skin+'/close_48.png" alt="Close Embedded Player" title="Close Embedded Player" /></td><td class=tdBtn><img id=cinfo onclick="show_info();" onmouseover="this.src=\'chrome://raismth/skin/'+skin+'/info_64.png\'" onmouseout="this.src=\'chrome://raismth/skin/'+skin+'/info_48.png\'" src="chrome://raismth/skin/'+skin+'/info_48.png" alt="Stream details" title="Stream details / Addon logs" /></td><td class=tdBtn><img id=cctrl onclick="var ret = show_ctrl(\''+ts+'\'); if(ret) document.getElementById(\'ctrl\').innerHTML=ret;" onmouseover="this.src=\'chrome://raismth/skin/'+skin+'/clip_64.png\'" onmouseout="this.src=\'chrome://raismth/skin/'+skin+'/clip_48.png\'" src="chrome://raismth/skin/'+skin+'/clip_48.png" alt="Advanced controls" title="Advanced clips controls" /></td></tr></table><div><pre><h3 style="text-align: center; color:white;">LINUX SMOOTH STREAMING PLAYER</h3> </pre></div>';
		return html;
	},

	spoof : function(doc) {		
		let target = myWrapper(doc); 
		let jso = target; 
		let b = '2.0.30226.2';
		if (!jso.Silverlight) jso.Silverlight = { };
		jso.Silverlight.isInstalled = function() { return true; };
		jso.onbeforeunload = function (event) { raismth.silverlight.unload(event); };
		jso.show_det = function() {
			let sel = doc.getElementById('det'); 
			let tar = doc.getElementById('details'); 
			let show = (tar.style.display == 'block' ? false : true); 
			if(show) { 
				tar.style.display = 'block'; 
				let text = sel.innerHTML.replace('▼','▲');
				let txt = document.createTextNode(text);
				sel.removeChild(sel.childNodes[0]);
				sel.appendChild(txt);
				// sel.innerHTML = sel.innerHTML.replace('▼','▲'); 
			} else { 
				tar.style.display = 'none'; 
				let text = sel.innerHTML.replace('▲','▼');
				let txt = document.createTextNode(text);
				sel.removeChild(sel.childNodes[0]);
				sel.appendChild(txt);
				// sel.innerHTML = sel.innerHTML.replace('▲','▼'); 
			}
		};

		jso.show_ctrl = function(ts) {
			var i = doc.getElementById('imgstatus'); 
			var t = doc.getElementById('ctrl'); 
			var tgt = doc.getElementById('clipctrl'); 
			var tgtt = doc.getElementById('maincont');
			if(tgt.style.display == 'block') { 
				tgt.style.display = 'none'; 
				return false;
			} else {
				var h = jso.clip_controls(ts); 
				i.style.display = 'none';
				// let my_timer = Cc["@mozilla.org/timer;1"].createInstance(Ci.nsITimer);
				tgt.style.display = 'block'; 
				tgtt.style.display = 'none'; 
				if(h[1]<1) {
					// let my_timer = Cc["@mozilla.org/timer;1"].createInstance(Ci.nsITimer);					
					// my_timer.initWithCallback(function() { i.style.display = 'none'; tgtt.style.display = 'none'; tgt.style.display = 'none'; }, 2000, Ci.nsITimer.TYPE_ONE_SHOT);
                                        // my_timer.initWithCallback(function() { jso.show_ctrl(ts); }, 2000, Ci.nsITimer.TYPE_ONE_SHOT);
				} else {
					// my_timer.initWithCallback(function() { i.style.display = 'none'; tgtt.style.display = 'none'; tgt.style.display = 'block'; }, 2000, Ci.nsITimer.TYPE_ONE_SHOT);
				}
				return h[0];
			};
		};
		jso.show_info = function() {
			var i = doc.getElementById('imgstatus');
			i.style.display = 'none';
			var cnt = doc.getElementById('maincont'); 
			var tgt = doc.getElementById('clipctrl'); 
			if(cnt.style.display == 'block') { 
				cnt.style.display = 'none'; 
			} else { 
				cnt.style.display = 'block'; 
				tgt.style.display = 'none'; 
			};
		};

		jso.stop_player = function(ts) {
			let obj = raismth.slobj[raismth.utils.arrayIndexOf(raismth.rai_windows_ts, parseInt(ts))];
			if(obj && obj.ctrl) {
				// obj.stato('SL->STOP', 'User Stop', 1, 9);
				obj.kill = true;
				if(obj.grabber_timer) obj.grabber_timer.cancel();
				obj.stop();
				obj.clean();
			} else if (obj && !obj.ctrl) {
				obj.stato('UI->STOP', 'Mplayer not detected [UI control disabled]', 1);
			} else if (!obj) {
				myDump("[RAISMTH] silverlight object is not defined\n");
			}
		};

		jso.play_wrapper = function(indice,name) {
			let obj = raismth.slobj[indice];
			// if(!this.media.IsLive) 
			if(name == "Play") {				
				if(!obj.paused && !obj.ppaused) {
					obj.switch_action(obj.clip,true);
					obj.stato('JSO->WRAPPER', '[Clip controls] Play button pressed', 1, 5);
				} else {
					obj.grabber_unpause(indice,obj.media.IsLive);
				}
			} else {
				obj.stato('JSO->WRAPPER', '[Clip controls] Pause button pressed', 1, 5);
				if(!obj.media.IsLive) {
					obj.paused = true;
				} else {
					obj.grabber_pause(indice);
				}
				// todo: pause
			}
		};

		jso.seek_wrapper = function(indice,name,delta) {
			let obj = raismth.slobj[indice];
			obj.grabber_seek(indice,name,delta);
		};

		jso.clip_wrapper = function(clip,indice) {			
			let obj = raismth.slobj[indice];
			let ret = false;
			if(!obj.playing) {
				obj.stato('JSO->WRAPPER', 'Clip changed [OLD: ' + obj.clip + ' NEW: ' + clip + ']', 1);
				// obj.switch_action(clip,true);
				obj.clip = clip;
				obj.offset = 0;
				obj.skipped = 0;
				ret = true;
			} else {
				obj.stato('JSO->WRAPPER', 'Player already running', 1);
				obj.stato('JSO->WRAPPER', 'Please stop player istance first', 1);
			}
			return ret;
		};

		jso.ql_wrapper = function(idx,indice) {
			let obj = raismth.slobj[indice];
			let ret = false;
                        if(obj.playing) {
				if(obj.waiting) {
					obj.stato('JSO->WRAPPER', 'Trying to modify video bitrate.', 1);
					ret = obj.adjust_video_quality(false,idx,indice);
				} else if(obj.ppaused||obj.paused) {
					obj.stato('JSO->WRAPPER', 'Operation not allowed in current state [player paused]', 1);
				} else {
					obj.stato('JSO->WRAPPER', 'Grabber overloaded. Please try again later', 1);
				}
			} else {
				obj.stato('JSO->WRAPPER', 'Video bitrate chnged [OLD: ' + obj.vqli + ' NEW: ' + idx + ']', 1);
				obj.vqli = idx; 
				obj.mvqli = idx;
				ret = true;
				// alert("Current: " + obj.vqli + " New: " + idx);				
				// obj.stato('JSO->WRAPPER', 'Player not running', 1);
			}
			return ret;
		};

		jso.clip_controls = function(ts) {
			let tss = ts;
			let indice = raismth.utils.arrayIndexOf(raismth.rai_windows_ts, parseInt(ts));
			let obj = raismth.slobj[indice];			
			let lenclip = 0;
			let ret = new Array();
			let html = '';
			let rc = -1;
			if(obj && obj.media) {
				// if(!obj.playing) return 'Please select a stream first';
				let numclips = obj.media.Clip.length;
				
				html = '<table cellpadding=10 cellspacing=10 border=1 rules=all frame=below><tr>';
				let sel = '';
				let en = true;
				for(let d = 0; d < numclips; d++){
					en = true;
					let tgt = obj.media.Clip[d];
					let vsi = tgt.StreamIndex[tgt.def_video_idx];
					sel = '';					
					if(vsi.c.length < 5) {
						// alert(raismth.silverlight.odump(vsi.c));
						sel = ' style="background: gray;" ';
						en = false;
					} else {
						sel = ' style="cursor:pointer;" ';
					}
					if(d == obj.clip) {
						sel = ' style="background: green; cursor:pointer;" ';
						lenclip = parseInt(vsi.c.length);
					}
					let s = vsi.c.length * 2;
					let h = parseInt(s/3600);
					let m = parseInt((s%3600)/60);
					s -= h*3600+m*60;
					let tm = h>0?h+'h ':'';
					tm += m>0?m+'m ':'';
					tm += s>0?s+'s':'';
					/*
					let m = 0;
					if(s >= 60) {
						m = parseInt(s/60);
						s = s%60;
					}
					*/
					let dd = d+1;
					let evt = ' title="Clip selection" onclick="show_info(); var ret = clip_wrapper(this.id,'+indice+'); setTimeout(function() {show_ctrl(\''+tss+'\')}, 2000); if(ret) unselect(this.className, this.id);"';
					html += "<td class=\"sclip\" " + (en?evt:'') + " " + sel + " id=" + d + ">";
					html += obj.media.IsLive ? "<small>LIVE</small>" : "Clip " + dd + "\n<small>" + tm + "</small>";
					html += "</td>";
				}
				html += '</tr></table>';
				html += '<table cellpadding=10 cellspacing=10 border=1 rules=all frame=below id=ttttt><tr style="cursor:pointer;">';
				let availql = obj.vql_avail.length;
				for(let d = 0; d < availql; d++) {
					sel = '';
					if(d == obj.vqli) sel = ' style="background-color: green;" ';
					let evt = ' class="svql" title="Video quality (bitrate)" onclick="show_info(); var ret = ql_wrapper(this.id,'+indice+'); setTimeout(function() {show_ctrl(\''+tss+'\')}, 2000); if(ret) unselect(this.className, this.id); "';
					html += "<td " + evt + " " + sel + " id=" + d + ">QL " + obj.vql_avail[d][1]/1000 + "k</td>";
				}
				html += '</tr></table>';

				let t = obj.playing ? (obj.ppaused ? 'Play' : 'Pause') : 'Play';				
				html += '<table style="width:595px;" cellpadding=10 cellspacing=10 border=1 rules=all frame=below><tr style="background:green; cursor:pointer; text-align:center">';

				html += '<td width=20% id=rew name="'+t+'" onclick="seek_wrapper('+indice+',this.getAttribute(\'name\'),-10);">FRew</td><td width=20% id=rew name="'+t+'" onclick="seek_wrapper('+indice+',this.getAttribute(\'name\'),-1);">Rewind</td><td width=20% id=play name="'+t+'" onclick="var n = this.getAttribute(\'name\'); show_info(); setTimeout(function() { show_ctrl(\''+tss+'\') }, 2000); play_wrapper('+indice+',this.getAttribute(\'name\')); var a = (n==\'Play\' ? \'Pause\' : \'Play\'); this.setAttribute(\'name\', a); this.innerHTML = a;">'+t+'</td><td width=20% id=fwd name="'+t+'" onclick="seek_wrapper('+indice+',this.getAttribute(\'name\'), 1);">Forward</td><td width=20% id=fwd name="'+t+'" onclick="seek_wrapper('+indice+',this.getAttribute(\'name\'), 10);">FFwd</td>';
				html += '</tr></table><br/><table bordercolor=white border=1 rules=all frame=below cellspacing=0 cellpadding=0>';
				let ret = raismth.utils.slider(0,lenclip);
				let str = ret.str;
				let ts = ret.ts;
				html += '<tr><td title="Slider" class=slider><div style="cursor:pointer; width:595px; height:17px; overflow:hidden;" id=slider>'+str+'<div></td></tr>';
				html += '<tr><td title="Buffering time"><div id=vtime>'+ts+'</div></td></tr>';
				html += '</table>';
				rc = 1;
			} else {
				
				html = 'Please use Play button first.';
				if(obj && !obj.media && !obj.isSmooth){
					html = 'Clip controls unavailable [MMS stream detected].';
					rc = 0;
				} 
			}
			ret[0] = html;
			ret[1] = rc;
			return ret;
			// doc.embeds[0].Pause;
			// doc.embeds[0].pause;
			// let embed = doc.embeds[0];
			// dump(raismth.silverlight.odump(embed) + '\n');
			// return true;
			// alert(doc.embeds[0].Stop());
		};

		jso.unselect = function(cname, sel) {
			let ctrls = doc.getElementsByClassName(cname);
			for(let c = 0; c < ctrls.length; c++) {
				if(c!=sel) {
					if(ctrls[c].style.backgroundColor == 'green') ctrls[c].style.backgroundColor = 'transparent';
				} else {
					ctrls[c].style.backgroundColor = 'green';
				}
			}
		};

		jso.loadCSS = function(doc) {
			let h = doc.getElementsByTagName("head")[0];
			raismth.utils.loadCSS(doc, h, 'chrome://raismth/content/raismth.css');
		};
		jso.play_content = function(url,title,ts,embed,play) {
			let indice = raismth.utils.arrayIndexOf(raismth.rai_windows_ts, parseInt(ts));
			// raismth.force_kill[indice] = false;
			if(raismth.slobj[indice] && raismth.slobj[indice].busy) {
				raismth.slobj[indice].stato('SL->PLAY', 'Window busy...', 1);
				return false;
			} else {
				raismth.slobj[indice] = new raismth.myPlayer(); 
				raismth.slobj[indice].initialize(url, title, ts, doc, embed, indice, play);
			}
			if(embed) {				
				// alert('Initializing Embedded Player [FIXME: waiting object init]');
				if(!raismth.slobj[indice].isSmooth){
					let url = raismth.slobj[indice].videoURI;
					// let playerObj = '<object type="application/x-mplayer2" height="218" width="585"><param name="fileName" value="'+url+'"><param name="autoStart" value="true"></object>';
					let playerObj = '<embed name=mpmitm id=mpmitm width="585" height="218" type="application/x-mplayer2" autostart="true" src="'+url+'" loop="true" onClick="this.Pause()" />';
					let ret = new Array();
					ret[0] = url;
					ret[1] = playerObj;
					return ret;
				}
				return false;
			}
		};		
                jso.Silverlight.buildHTML = function(slProperties){
			jso.loadCSS(doc);
                        return raismth.silverlight.buildHTML(slProperties,target,doc);
                };
	},

	uninstall : function(doc) {
		let jso = myWrapper(doc);
		if (!jso.Silverlight) jso.Silverlight = { };
		jso.Silverlight.isInstalled = function() { return false; };		
	},

        odump : function (object, depth, max){
                depth = depth || 0;
                max = max || 2;

                if (depth > max)
                        return false;

                var indent = "";
                for (var i = 0; i < depth; i++)
                        indent += "  ";

                var output = "";
                for (var key in object){
                        output += "\n" + indent + key + ": ";
                        switch (typeof object[key]){
                                case "object": output += raismth.silverlight.odump(object[key], depth + 1, max); break;
                                case "function": output += "function"; break;
                                default: output += object[key]; break;
                        }
                }
                return output;
        },

}

}});
	
