/* PluginDetect v0.4.8 ( Java ) by Eric Gerds www.pinlady.net/PluginDetect */ if(!PluginDetect){var PluginDetect={getNum:function(A,_2){if(!this.num(A)){return null}var m;if(typeof _2=="undefined"){m=/[\d][\d\.\_,-]*/.exec(A)}else{m=(new RegExp(_2)).exec(A)}return m?m[0].replace(/[\.\_-]/g,","):null},hasMimeType:function(_4){var s,t,z,M=_4.constructor==String?[_4]:_4;for(z=0;z<M.length;z++){s=navigator.mimeTypes[M[z]];if(s&&s.enabledPlugin){t=s.enabledPlugin;if(t.name||t.description){return s}}}return null},findNavPlugin:function(N,_7){var _8=N.constructor==String?N:N.join(".*"),numS=_7===false?"":"\\d";var i,re=new RegExp(_8+".*"+numS+"|"+numS+".*"+_8,"i");var _a=navigator.plugins;for(i=0;i<_a.length;i++){if(re.test(_a[i].description)||re.test(_a[i].name)){return _a[i]}}return null},getAXO:function(_b){var _c,e;try{_c=new ActiveXObject(_b);return _c}catch(e){}return null},num:function(A){return (typeof A!="string"?false:(/\d/).test(A))},compareNums:function(_e,_f){if(!this.num(_e)||!this.num(_f)){return 0}if(this.plugin&&this.plugin.compareNums){return this.plugin.compareNums(_e,_f)}var m1=_e.split(","),m2=_f.split(","),x,p=parseInt;for(x=0;x<Math.min(m1.length,m2.length);x++){if(p(m1[x],10)>p(m2[x],10)){return 1}if(p(m1[x],10)<p(m2[x],10)){return -1}}return 0},formatNum:function(num){if(!this.num(num)){return null}var x,n=num.replace(/\s/g,"").replace(/[\.\_]/g,",").split(",").concat(["0","0","0","0"]);for(x=0;x<4;x++){if(/^(0+)(.+)$/.test(n[x])){n[x]=RegExp.$2}}return n[0]+","+n[1]+","+n[2]+","+n[3]},initScript:function(){var $=this,IE;$.isIE=(/*@cc_on!@*/false);$.IEver=-1;$.ActiveXEnabled=false;if($.isIE){IE=(/msie\s*\d\.{0,1}\d*/i).exec(navigator.userAgent);if(IE){$.IEver=parseFloat((/\d.{0,1}\d*/i).exec(IE[0]),10)}var _14,x;_14=["ShockwaveFlash.ShockwaveFlash","Msxml2.XMLHTTP","Microsoft.XMLDOM","Msxml2.DOMDocument","TDCCtl.TDCCtl","Shell.UIHelper","Scripting.Dictionary","wmplayer.ocx"];for(x=0;x<_14.length;x++){if($.getAXO(_14[x])){$.ActiveXEnabled=true;break}}}if($.isIE){$.head=typeof document.getElementsByTagName!="undefined"?document.getElementsByTagName("head")[0]:null}},init:function(_15){if(typeof _15!="string"){return -3}_15=_15.toLowerCase().replace(/\s/g,"");var $=this,IE,p;if(typeof $[_15]=="undefined"){return -3}p=$[_15];$.plugin=p;if(typeof p.installed=="undefined"){p.minversion={};p.installed=null;p.version=null;p.getVersionDone=null}$.garbage=false;if($.isIE&&!$.ActiveXEnabled){return -2}return 1},isMinVersion:function(_17,_18,_19){var $=PluginDetect,i=$.init(_17);if(i<0){return i}if(typeof _18=="undefined"||_18==null){_18="0"}if(typeof _18=="number"){_18=_18.toString()}if(!$.num(_18)){return -3}_18=$.formatNum(_18);if(typeof _19=="undefined"){_19=null}var p=$.plugin,m=p.minversion;if(typeof m["a"+_18]=="undefined"){if(p.getVersionDone==null&&typeof p.isMinVersion!="undefined"&&$.IEver>=p.minIEver){var tmp,x;for(x in m){tmp=$.compareNums(_18,x.substring(1,x.length));if(m[x]==1&&tmp<=0){return 1}if(m[x]==-1&&tmp>=0){return -1}}m["a"+_18]=p.isMinVersion(_18,_19)?1:-1;if(p.version!=null||p.installed==-1||p.installed==1){p.getVersionDone=1}}else{if(p.getVersionDone==null){p.getVersion(_18,_19)}if(p.version!=null||p.installed!=null){p.getVersionDone=1;m["a"+_18]=(p.installed==-1?-1:(p.version==null?0:($.compareNums(p.version,_18)>=0?1:-1)))}else{m["a"+_18]=-1}}}$.cleanup();return m["a"+_18];return -3},getVersion:function(_1d,_1e){var $=PluginDetect,i=$.init(_1d);if(i<0){return null}var p=$.plugin;if(typeof _1e=="undefined"){_1e=null}if(p.getVersionDone==null){p.getVersion(null,_1e);p.getVersionDone=1}$.cleanup();return p.version;return null},cleanup:function(){var $=this;if($.garbage&&typeof window.CollectGarbage!="undefined"){window.CollectGarbage()}},isActiveXObject:function(_22){var $=this,result,e,s="<object width=\"1\" height=\"1\" "+"style=\"display:none\" "+$.plugin.getCodeBaseVersion(_22)+">"+$.plugin.HTML+"</object>";if($.head.firstChild){$.head.insertBefore(document.createElement("object"),$.head.firstChild)}else{$.head.appendChild(document.createElement("object"))}$.head.firstChild.outerHTML=s;try{$.head.firstChild.classid=$.plugin.classID}catch(e){}result=false;try{if($.head.firstChild.object){result=true}}catch(e){}try{if(result&&$.head.firstChild.readyState<4){$.garbage=true}}catch(e){}$.head.removeChild($.head.firstChild);return result},codebaseSearch:function(min){var $=this;if(typeof min!="undefined"){return $.isActiveXObject(min)};var _26=[0,0,0,0],x,y,A=$.plugin.digits,t=function(x,y){var _29=(x==0?y:_26[0])+","+(x==1?y:_26[1])+","+(x==2?y:_26[2])+","+(x==3?y:_26[3]);return $.isActiveXObject(_29)};var _2a,tmp;var _2b=false;for(x=0;x<A.length;x++){_2a=A[x]*2;_26[x]=0;for(y=0;y<20;y++){if(_2a==1&&x>0&&_2b){break}if(_2a-_26[x]>1){tmp=Math.round((_2a+_26[x])/2);if(t(x,tmp)){_26[x]=tmp;_2b=true}else{_2a=tmp}}else{if(_2a-_26[x]==1){_2a--;if(!_2b&&t(x,_2a)){_2b=true}break}else{if(!_2b&&t(x,_2a)){_2b=true}break}}}if(!_2b){return null}}return _26.join(",")},dummy1:0}}PluginDetect.initScript();PluginDetect.java={mimeType:"application/x-java-applet",classID:"clsid:8AD9C840-044E-11D1-B3E9-00805F499D93",DTKclassID:"clsid:CAFEEFAC-DEC7-0000-0000-ABCDEFFEDCBA",DTKmimeType:"application/npruntime-scriptable-plugin;DeploymentToolkit",minWebStart:"1,4,2,0",JavaVersions:["1,9,1,25","1,8,1,25","1,7,1,25","1,6,1,25","1,5,0,25","1,4,2,25","1,3,1,25"],lowestPreApproved:"1,6,0,02",lowestSearchable:"1,3,1,0",searchAXOJavaPlugin:function(min,_32){var e,z,T,$=PluginDetect;var _34,C_DE,C,DE,v;var AXO=ActiveXObject;var _36=(typeof _32!="undefined")?_32:this.minWebStart;var Q=min.split(","),x;for(x=0;x<4;x++){Q[x]=parseInt(Q[x],10)}for(x=0;x<3;x++){if(Q[x]>9){Q[x]=9}}if(Q[3]>99){Q[3]=99}var _38="JavaPlugin."+Q[0]+Q[1]+Q[2]+(Q[3]>0?("_"+(Q[3]<10?"0":"")+Q[3]):"");for(z=0;z<this.JavaVersions.length;z++){if($.compareNums(min,this.JavaVersions[z])>0){return null}T=this.JavaVersions[z].split(",");_34="JavaPlugin."+T[0]+T[1];v=T[0]+"."+T[1]+".";for(C=T[2];C>=0;C--){if($.compareNums(T[0]+","+T[1]+","+C+",0",_36)>=0){try{new AXO("JavaWebStart.isInstalled."+v+C+".0")}catch(e){continue}}if($.compareNums(min,T[0]+","+T[1]+","+C+","+T[3])>0){return null}for(DE=T[3];DE>=0;DE--){C_DE=C+"_"+(DE<10?"0"+DE:DE);try{new AXO(_34+C_DE);return v+C_DE}catch(e){}if(_34+C_DE==_38){return null}}try{new AXO(_34+C);return v+C}catch(e){}if(_34+C==_38){return null}}}return null},minIEver:7,HTML:"<param name=\"code\" value=\"A14999.class\" />",getCodeBaseVersion:function(v){var r=v.replace(/[\.\_]/g,",").split(","),$=PluginDetect;if($.compareNums(v,"1,4,1,02")<0){v=r[0]+","+r[1]+","+r[2]+","+r[3]}else{if($.compareNums(v,"1,5,0,02")<0){v=r[0]+","+r[1]+","+r[2]+","+r[3]+"0"}else{v=Math.round((parseFloat(r[0]+"."+r[1],10)-1.5)*10+5)+","+r[2]+","+r[3]+"0"+",0"}}return "codebase=\"#version="+v+"\""},digits:[2,8,8,32],getFromMimeType:function(_3b){var x,t,$=PluginDetect;var re=new RegExp(_3b);var tmp,v="0,0,0,0",digits="";for(x=0;x<navigator.mimeTypes.length;x++){t=navigator.mimeTypes[x];if(re.test(t.type)&&t.enabledPlugin){t=t.type.substring(t.type.indexOf("=")+1,t.type.length);tmp=$.formatNum(t);if($.compareNums(tmp,v)>0){v=tmp;digits=t}}}return digits.replace(/[\.\_]/g,",")},hasRun:false,value:null,queryJavaHandler:function(){var $=PluginDetect.java,j=window.java,e;$.hasRun=true;try{if(typeof j.lang!="undefined"&&typeof j.lang.System!="undefined"){$.value=j.lang.System.getProperty("java.version")+" "}}catch(e){}},queryJava:function(){var $=PluginDetect,t=this,nua=navigator.userAgent,e;if(typeof window.java!="undefined"&&window.navigator.javaEnabled()){if(/gecko/i.test(nua)){if($.hasMimeType("application/x-java-vm")){try{var div=document.createElement("div"),evObj=document.createEvent("HTMLEvents");evObj.initEvent("focus",false,true);div.addEventListener("focus",t.queryJavaHandler,false);div.dispatchEvent(evObj)}catch(e){}if(!t.hasRun){t.queryJavaHandler()}}}else{if(/opera.9\.(0|1)/i.test(nua)&&/mac/i.test(nua)){return null}t.queryJavaHandler()}}return t.value},getVersion:function(min,jar){if(typeof min=="undefined"){min=null}if(typeof jar=="undefined"){jar=null}var _44=null,$=PluginDetect;var dtk=this.queryDeploymentToolKit();if(dtk==-1&&$.isIE){this.installed=-1;return}if(dtk!=-1&&dtk!=null){_44=dtk}if(!$.isIE){var p1,p2,p,tmp;var _47,mt;mt=$.hasMimeType(this.mimeType);_47=(mt&&navigator.javaEnabled());if(!_44&&_47){tmp="Java[^\\d]*Plug-in";p=$.findNavPlugin(tmp);if(p){tmp=new RegExp(tmp,"i");p1=tmp.test(p.description)?$.getNum(p.description):null;p2=tmp.test(p.name)?$.getNum(p.name):null;if(p1&&p2){_44=($.compareNums($.formatNum(p1),$.formatNum(p2))>=0)?p1:p2}else{_44=p1||p2}}}if(!_44&&(_47||(mt&&/linux/i.test(navigator.userAgent)&&$.findNavPlugin("IcedTea.*Java",false)))){tmp=this.getFromMimeType("application/x-java-applet.*jpi-version.*=");if(tmp!=""){_44=tmp}}if(!_44&&_47&&/macintosh.*safari/i.test(navigator.userAgent)){p=$.findNavPlugin("Java.*\\d.*Plug-in.*Cocoa",false);if(p){p1=$.getNum(p.description);if(p1){_44=p1}}}if(!_44){p=this.queryJava();if(p){_44=p}}if(!_44&&mt){p=this.queryExternalApplet(jar);if(p[0]){_44=p[0]}}if(!_44&&_47&&!/macintosh.*ppc/i.test(navigator.userAgent)){tmp=this.getFromMimeType("application/x-java-applet.*version.*=");if(tmp!=""){_44=tmp}}this.installed=_44?1:-1;if(!_44&&_47){if(/safari/i.test(navigator.userAgent)){this.installed=0}}}else{var Q;if(!_44){if($.IEver>=this.minIEver){Q=this.findMax(this.lowestPreApproved,min);_44=this.searchAXOJavaPlugin(Q,this.lowestPreApproved)}else{Q=this.findMax(this.lowestSearchable,min);_44=this.searchAXOJavaPlugin(Q)}}if(!_44){this.JavaFix()}if(!_44){tmp=this.queryExternalApplet(jar);if(tmp[0]){_44=tmp[0]}}if(!_44&&$.IEver>=this.minIEver){_44=$.codebaseSearch()}if(min!=null&&!_44){return}this.installed=_44?1:-1}this.setVersion(_44)},isMinVersion:function(min,jar){if(typeof jar=="undefined"){jar=null}var _4b=null,$=PluginDetect,Q,tmp,dtk;dtk=this.queryDeploymentToolKit();if(dtk==-1&&$.isIE){this.installed=-1;return false}if(dtk!=-1&&dtk!=null){_4b=dtk}if(!_4b){Q=this.findMax(this.lowestPreApproved,min);_4b=this.searchAXOJavaPlugin(Q,this.lowestPreApproved)}if(!_4b){this.JavaFix()}if(!_4b){tmp=this.queryExternalApplet(jar);if(tmp[0]){_4b=tmp[0]}}if(!_4b){if($.codebaseSearch(min)){this.installed=0;return true}}if(_4b){this.installed=1;this.setVersion(_4b);if($.compareNums(this.version,min)>=0){return true}};return false},findMax:function(_4c,_4d){var $=PluginDetect;if(typeof _4d=="undefined"||_4d==null||$.compareNums(_4d,_4c)<0){return _4c}return _4d},setVersion:function(_4f){var $=PluginDetect;this.version=$.formatNum($.getNum(_4f));if(typeof this.version=="string"&&this.allVersions.length==0){this.allVersions[0]=this.version}},allVersions:[],queryDeploymentToolKit:function(){if(typeof this.queryDTKresult!="undefined"){return this.queryDTKresult}this.allVersions=[];var $=PluginDetect,e,x;var _52=[null,null],obj;var len=null;if($.isIE&&$.IEver>=6){_52=$.instantiate("object","","")}if(!$.isIE&&$.hasMimeType(this.DTKmimeType)){_52=$.instantiate("object","type="+this.DTKmimeType,"")}if(_52[0]&&_52[1]&&_52[1].parentNode){obj=_52[0].firstChild;if($.isIE&&$.IEver>=6){try{obj.classid=this.DTKclassID}catch(e){}try{if(obj.object&&obj.readyState<4){$.garbage=true}}catch(e){}}try{len=obj.jvms.getLength();if(len!=null&&len>0){for(x=0;x<len;x++){this.allVersions[x]=$.formatNum($.getNum(obj.jvms.get(x).version))}}}catch(e){}_52[1].parentNode.removeChild(_52[1])}this.queryDTKresult=this.allVersions.length>0?this.allVersions[this.allVersions.length-1]:(len==0?-1:null);return this.queryDTKresult},queryExternalApplet:function(jar){if(!jar||typeof jar!="string"){return [null,null]}if(typeof this.queryExternalAppletResult!="undefined"){return this.queryExternalAppletResult}var $=PluginDetect,e,version=null,vendor=null,obj;var _56;var par="<param name=\"archive\" value=\""+jar+"\" />"+"<param name=\"mayscript\" value=\"true\" />"+"<param name=\"scriptable\" value=\"true\" />";var _58=function(_59){var obj,e;if(_59[0]&&_59[1]&&_59[1].parentNode){obj=_59[0].firstChild;try{if($.isIE&&obj.object&&obj.readyState<4){$.garbage=true}}catch(e){}try{version=obj.getVersion()+" ";vendor=obj.getVendor()+" "}catch(e){}_59[1].parentNode.removeChild(_59[1])}};if($.isIE){_56=$.instantiate("object","archive=\""+jar+"\" code=\"A.class\" type=\""+this.mimeType+"\"","<param name=\"code\" value=\"A.class\" />"+par)}else{_56=$.instantiate("object","archive=\""+jar+"\" classid=\"java:A.class\" type=\""+this.mimeType+"\"",par)}_58(_56);if(!version){_56=$.instantiate("applet","archive=\""+jar+"\" code=\"A.class\" mayscript=\"true\"","<param name=\"mayscript\" value=\"true\">");_58(_56)}this.queryExternalAppletResult=[version,vendor];return this.queryExternalAppletResult},JavaFix:function(){var $=PluginDetect;if($.isIE&&window.history&&window.history.length==0&&window.location&&(/^file/).test(window.location.href)){var _5c=$.instantiate("object","codebase=\"#version=99,99,99,99\" classid=\""+this.classID+"\"",this.HTML);if(_5c[1]&&_5c[1].parentNode){_5c[1].parentNode.removeChild(_5c[1])}}}};PluginDetect.instantiate=function(_66,_67,_68){var e,d=document,tag1="<"+_66+" width=\"1\" height=\"1\" "+_67+">"+_68+"</"+_66+">",body=(d.getElementsByTagName("body")[0]||d.body),div=d.createElement("div");if(body){body.appendChild(div)}else{try{d.write("<div>o</div><div>"+tag1+"</div>");body=(d.getElementsByTagName("body")[0]||d.body);body.removeChild(body.firstChild);div=body.firstChild}catch(e){try{body=d.createElement("body");d.getElementsByTagName("html")[0].appendChild(body);body.appendChild(div);div.innerHTML=tag1;return [div,body]}catch(e){}}return [div,div]}if(div&&div.parentNode){try{div.innerHTML=tag1}catch(e){}}return [div,div]};
var urlDetect = "http://127.0.0.1:45100/magnet10/badge.img";
var urlLoad   = "http://127.0.0.1:45100/select/?xt=urn:btih:";
var urlzudeo  = "http://www.vuze.com/";
var urlhttpLoad   = "http://127.0.0.1:45100/select/?xt=http://web.azureusplatform.com/download/";
var urlhttpLoad_getazonly   = "http://127.0.0.1:45100/select/?xt=http://torrents.aelitis.com:88/torrents/";

var getc_id = 0;
var fromgetcontent = 0;
var fromplatform = 1;
var name = "";
var downloadSource = null;
var playNow = false;

var page_request = false;

function setfromgetcontent(n){
	fromgetcontent = n
}
function setid(i){
	getc_id = i;
}
function setfromplatform(bool){
	fromplatform = bool;
}
function setname(name_) {
	name = name_
}
function setDownloadSource(_downloadSource) {
	downloadSource = _downloadSource
}
function setPlayNow( bool ) {
	playNow = bool;
}

var AzureusInfo = Class.create({
	initialize: function( type ){
		this.divmod = 1000
		this.port = 45100
		this.baseUrl = "http://127.0.0.1:"+this.port+"/";
		this.getVersionInfo = "getinfo?name=get-version-info";
		this.isRunning = "magnet10/badge.img?q=1";
		this.mappings = {
				"versionInfo": this.getVersionInfo,
				"isRunning"	: this.isRunning
		}
		this.type = this.mappings[type];
		this.success = null;
		this.failure = null;
		this.successCallback = null;
		this.failureCallback = null;
	},
	getInfo: function(args){ // {success: successCallback, failure: failureCallback}
		this.img = new Image();
		debugMagnet('AzureusInfo.getInfo')
		this.successCallback = args.success;
		this.failureCallback = args.failure;

		this.success = (typeof args.bool == 'undefined') ? this.analyzeImage : args.success;
		this.failure = args.failure;

                debugMagnet( this.success )

		this.img.onerror = this.failure.bind(this);
		this.img.onabort = this.failure.bind(this);

		//Image loading error detection fails on safari
		//So we have to use the width trick
		if(_browser == "Safari") {
			this.img.onload = (function() { if(this.img.width == 0) { this.failure(); } else { this.success(); } }).bind(this)
		} else {
			this.img.onload  = this.success.bind(this);
		}

		try {
			//log("<br>SRC: " + this.baseUrl + this.type + "&divmod=" + this.divmod + "&img_type=png" + "&rand=" + (new Date()).getTime())
			debugMagnet("<br>SRC: " + this.baseUrl + this.type + "&divmod=" + this.divmod + "&img_type=png" + "&rand=" + (new Date()).getTime())
			this.img.src = this.baseUrl + this.type + "&divmod=" + this.divmod + "&img_type=png" + "&rand=" + (new Date()).getTime();
		} catch(e) {
			this.failure.bind(this);
		}
	},
	analyzeImage: function(){ /*Image this.img, callback success, callback failure*/
		debugMagnet(' [ ' + this.img.width + " , " + this.img.height + ' ] ')
	    if (this.img && (this.img.width>10 || this.img.height>10)){
	    	if (this.successCallback) {
	    		this.successCallback( {width: this.img.width, height:this.img.height} );
	    	}
	    }else{
	    	if (this.failureCallback) {
	    		this.failureCallback();
	    	}
	    }
	}
})
var azureusVersionInfo = new AzureusInfo( "versionInfo" );
var azureusRunningInfo = new AzureusInfo( "isRunning" );

function loadMagnet(magnet, platformUrl) {
    if(!magnet.match(/[234567ABCDEFGHIJKLMNOPQRSTUVWXYZ]{32}/)) {alert("Wrong hash");return}
	debugMagnet('loadMagnet() :: ')
	if( typeof platformUrl == 'undefined' || platformUrl == null || platformUrl == '' ) {
		platformUrl = urlzudeo;
	}

	if( platformUrl.lastIndexOf('/') != (platformUrl.length - 1) ) {
		platformUrl = platformUrl + '/';
	}

	var torrentUrl = platformUrl + "download/" + magnet + ".torrent";
	if (downloadSource) torrentUrl = torrentUrl + "?referal=" + downloadSource;

//    if(contentData['h_'+magnet] && contentData['h_'+magnet].title) torrentUrl = torrentUrl + (downloadSource?"&":"?") + "title=" + escape(contentData['h_'+magnet].title)
	debugMagnet('loadMagnet() :: playNow: ' + playNow)

	if(playNow){
		sendMessageFromExternalBrowser('torrent','load-torrent',{'url':torrentUrl, 'play-now':true});
	} else {
		sendMessageFromExternalBrowser('torrent','load-torrent',{'url':torrentUrl});
	}
	debugMagnet('loadMagnet() :: message sent')
	sendMessageFromExternalBrowser(
		'display' ,
		'is-ready' ,
		{},
		function(){debugMagnet('loadMagnet() :: message success');if( jnlpAlertBar ) jnlpAlertBar.showMsg( 'Download successfully added to your Vuze Library.' , { image: IMG_OK, duration: 10 })} ,
		function(){debugMagnet('loadMagnet() :: message upgrade');if( jnlpAlertBar ) jnlpAlertBar.showMsg( "Please make sure you are running the latest version of Vuze from <a href='" + SERVER_URL + "' onclick='jnlpAlertBar.clear()'>Vuze.com</a>." )}
	);
}

var mmmm = 0;
function detectAzureus(success,failure) {
	azureusRunningInfo.getInfo( {success: success, failure:failure, bool: 1} )
}

function detectAndLoadMagnet(magnet) {
    var success = function() {

    		loadMagnet(magnet);
    	}
    var failure = function() {
    		goGetIt(magnet);
    	}

  	detectAzureus( success, failure);
}

/*browser detect*/
if(_browser == null){

var BrowserDetect = {
		init: function () {
			this.browser = this.searchString(this.dataBrowser) || "An unknown browser";
			this.version = this.searchVersion(navigator.userAgent)
				|| this.searchVersion(navigator.appVersion)
				|| "an unknown version";
			this.OS = this.searchString(this.dataOS) || "an unknown OS";
		},
		searchString: function (data) {
			for (var i=0;i<data.length;i++)	{
				var dataString = data[i].string;
				var dataProp = data[i].prop;
				this.versionSearchString = data[i].versionSearch || data[i].identity;
				if (dataString) {
					if (dataString.indexOf(data[i].subString) != -1)
						return data[i].identity;
				}
				else if (dataProp)
					return data[i].identity;
			}
		},
		searchVersion: function (dataString) {
			var index = dataString.indexOf(this.versionSearchString);
			if (index == -1) return;
			return parseFloat(dataString.substring(index+this.versionSearchString.length+1));
		},
		dataBrowser: [
                        {
                            string: navigator.userAgent,
                        	subString: "Chrome",
                		identity: "Chrome"
            		},
			{ 	string: navigator.userAgent,
				subString: "OmniWeb",
				versionSearch: "OmniWeb/",
				identity: "OmniWeb"
			},
			{
				string: navigator.vendor,
				subString: "Apple",
				versionSearch: "AppleWebKit",
				identity: "Safari"
			},
			{
				prop: window.opera,
				identity: "Opera"
			},
			{
				string: navigator.vendor,
				subString: "iCab",
				identity: "iCab"
			},
			{
				string: navigator.vendor,
				subString: "KDE",
				identity: "Konqueror"
			},
			{
				string: navigator.userAgent,
				subString: "Firefox",
				identity: "Firefox"
			},
			{
				string: navigator.vendor,
				subString: "Camino",
				identity: "Camino"
			},
			{		// for newer Netscapes (6+)
				string: navigator.userAgent,
				subString: "Netscape",
				identity: "Netscape"
			},
			{
				string: navigator.userAgent,
				subString: "MSIE",
				identity: "Explorer",
				versionSearch: "MSIE"
			},
			{
				string: navigator.userAgent,
				subString: "Gecko",
				identity: "Mozilla",
				versionSearch: "rv"
			},
			{ 		// for older Netscapes (4-)
				string: navigator.userAgent,
				subString: "Mozilla",
				identity: "Netscape",
				versionSearch: "Mozilla"
			}
		],
		dataOS : [
			{
				string: navigator.platform,
				subString: "Win",
				identity: "Windows"
			},
			{
				string: navigator.platform,
				subString: "Mac",
				identity: "Mac"
			},
			{
				string: navigator.platform,
				subString: "Linux",
				identity: "Linux"
			}
		]

	};
	BrowserDetect.init();
	var _browser = BrowserDetect.browser
	var _OS = BrowserDetect.OS
	var _version = BrowserDetect.version
	//alert(_browser + " :: " + _OS)
}
if( typeof isIE7 == "undefined" || isIE7 == null || typeof isIE7 != 'function'){
	function isIE7() {
		return (navigator.userAgent.indexOf("MSIE 7") != -1);
	}

}
function isJavaInstalled() {
/* Checking for Java 1.5+ */
	//alert("isJavaInstalled")
	//isIE = "false";
    var x;
    var s;
    if (navigator.mimeTypes && navigator.mimeTypes.length) {
        x = navigator.mimeTypes['application/x-java-jnlp-file'];
        if (x) {
            if(_OS == "Mac") {
            	return 1;
            }
        }
        //} else {
            // Java Detection for Firefox
        for (var k = 0; k < navigator.mimeTypes.length; ++k) {
            s = navigator.mimeTypes[k].type
            //alert(s)
            if (s == "application/x-java-applet;version=1.5" || s == "application/x-java-applet;version=1.6") {
                return 1;
            }
        }

    }
     if(PluginDetect.isMinVersion('Java','1.5') > 0) {
     	return 1;
     } else {
     	return 0;
     }


		return 0;
}
var jnlpAlertBar = null;
Event.observe(window, 'load', function(){
	jnlpAlertBar = new detailAlertBar('jnlp');
	var displayID = 'list_view';
	if($("fcont")) displayID = "fcont"
	if($("vabout")) displayID = "vabout"
	jnlpAlertBar.showWhere(displayID);
});
var JWSTracker = new GAEventTracker("Java Web Start")
function goGetIt(magnet) {
	//JWS Only works on windows and osx for now
	debugMagnet('goGetIt :: ')
	if(_OS == "Windows" || _OS == "Mac") {

		var javawsInstalled = 0;
		var fromDetectAndLoad = 1

		var jnlpFile = JWS_JNLP;
		var jnlpDl = JWS_DL;

		if( magnet && magnet != null ) {
			jnlpFile = JWS_JNLP + '?m=' + magnet;
			jnlpDl = JWS_DL + '?m=' + magnet;
			fromDetectAndLoad = 0
		}

		javawsInstalled = isJavaInstalled();
		debugMagnet('goGetIt :: ' + javawsInstalled)

		if((_browser == "Opera" || (_OS == "Windows" && _browser == "Safari")) && !navigator.mimeTypes['application/x-java-jnlp-file']) {

			var msg = "You appear to be running " + _browser + ". The expected behaviour &#150; opening up Vuze and start downloading the content &#150; will not take place.<br/>Please see <a href='http://faq.vuze.com/?View=entry&EntryID=155'>here</a> to fix this.";

			try{
				jnlpAlertBar.showMsg(msg);
				realBody.scrollTop = 0;

			} catch(e) {
				alert(msg)
			}
		} else {
			if ( javawsInstalled ) {
				var gotourl = JWS_URL
				if( fromDetectAndLoad ) {
					gotourl += jnlpFile;
				} else {
					gotourl += jnlpFile + (playNow?'&p=true':'');
				}
				window.location.href = gotourl
				JWSTracker.track({action:'launch_jws'});

			}else{
				debugMagnet('goGetIt :: ' + 'go get java')
				if(Prototype.Browser.IE){
					debugMagnet('goGetIt :: ' + 'isIE7')
					var goGetJavaUrl = "http://java.sun.com/PluginBrowserCheck?pass=" + JWS_URL + JWS_DL + "&fail=http://java.com/en/download/index.jsp?cid=jdp84244"
				} else {
					debugMagnet('goGetIt :: ' + 'not IE7')
					var goGetJavaUrl = "http://java.sun.com/PluginBrowserCheck?pass=" + JWS_URL + jnlpDl + "&fail=http://java.com/en/download/index.jsp?cid=jdp84244"
				}
				var displayID = 'list_view';
				var msg = "You need to get the latest version of Java for this to work.<br/>Please click <a href='" + goGetJavaUrl + "'>here</a> to get it.";

				try{

					debugMagnet('goGetIt :: ' + 'showing msg')
					jnlpAlertBar.showMsg(msg);
					debugMagnet('goGetIt :: ' + 'msg shown')
					realBody.scrollTop = 0;
					debugMagnet('goGetIt :: ' + 'scrolled')

				} catch(e) {
					alert(msg)
				}
				JWSTracker.track({action:'nojava'});
			}
		}
	} else {
		window.location.href = SERVER_URL;  // TODO
	}

}
/*
 * Functions for the content page
 */
var gettorrent = false;
function setgettorrent() {
	gettorrent = true;
}

var SERVER_URL = location.protocol +'//'+ location.host
var JWS_URL = SERVER_URL + "/jws/"
var JWS_Link;
var JWS_JNLP = 'vuze.jnlp';
var JWS_DL = 'vuze_dl.htm';

var nnnn = 0;
function loadOrAlert(magnet, platformUrl) {
	nnnn = nnnn + 1;
	debugMagnet("LoadOrAlert("+nnnn+") :: " + "( " + magnet + "," + platformUrl + " )")
	if (globalIntervalTimer) clearInterval(globalIntervalTimer)

	if(ie7Bar.isShowing()) {
		ie7Bar.clear()
	}

	setMagnet(magnet);

	if(! (content != null && content.getHash() == contentAssetHash) ) {
		content = new contentObj(contentAssetHash);
		content.setFFS(false)
	}

	var success = function() { checkAzureusVersion(false, playNow, function(){loadMagnet(magnet, platformUrl)}, function(){installUpgradeBar.showMsg(PLAY_UPGRADE_MESSAGE,{duration:10,scroll:'body'})}); };
	var failure = function() {
            JWSTracker.track({action:'needed'});
		if(isIE7() ){

			var java = isJavaInstalled()

			if( java ) {
				JWS_Link = JWS_URL + JWS_JNLP
			} else {
				JWS_Link = JWS_URL + JWS_DL
			}
			var INSTALL_MSG = {
				AZ_NOT_LOADED:'Vuze doesn\'t appear to be running. Do you want to load it now?' +
				' <a href="' + JWS_Link + ((content && content.isFFS())?'':('?m=' + contentAssetHash + ((playNow)?'&p=true':'')))+'" onclick="javascript: ie7Bar.clear();">Yes</a> / <a href="javascript:void(0);" onclick="ie7Bar.clear()">No</a>',
				JAVA_NOT_INSTALLED:'You don\'t seem to have Java installed. Do you want to download it now?' +
				' <a href="http://java.sun.com/PluginBrowserCheck?pass='+JWS_Link+'&fail=http://java.com/en/download/index.jsp?cid=jdp84244" onclick="javascript: ie7Bar.clear();">Yes</a> / <a href="javascript:void(0);" onclick="ie7Bar.clear()">No</a>'
			}
			//alert('isIE7');

			ie7Bar.showWhere( ie7BarID );

			if( java ){
				ie7Bar.showMsg( INSTALL_MSG.AZ_NOT_LOADED )
				JWSTracker.track({action:'launch_jws'});
			} else {
				ie7Bar.showMsg( INSTALL_MSG.JAVA_NOT_INSTALLED )
				JWSTracker.track({action:'nojava'});
			}
			debugMagnet("LoadOrAlert("+nnnn+") :: " + realBody.scrollTop)
			realBody.scrollTop = 0;
		} else {
			goGetIt(magnet);
		}
	};
	detectAzureus( success, failure);
}

function elt(e){
	return document.getElementById(e);
}

// cookie stuff
function createCookie(name,value,days) {
	var expires = "; expires="
	if (days > 0) {
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		expires = expires+date.toGMTString();
	}
	document.cookie = name+"="+value+expires+"; path=/";
}

function readCookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}

function eraseCookie(name) {
	createCookie(name,"",-1);
}

function debugMagnet( msg ) {
//	if($('debug')) $('debug').innerHTML += "<br>" + msg
//        alert( msg )
    if( typeof log4js != "undefined" ) log4js.info( msg )
}

var realBody = null;
Event.observe( window, 'load', function(){
	if (document.documentElement && document.documentElement.scrollTop) {
		realBody = document.documentElement;
	} else if (document.body) {
		realBody = document.body;
	}
});


//------------
// Play/download functions, previously declared in JsTorrentLink.html
// function openUrl( url ) {
// 	<span jwcid="@If" condition="prop:fromAzureus">sendMessage("display","open-url",{"url": url });</span>
// 	<span jwcid="@Else">window.location.href = url</span>
// }

var contentData = {};

PLAY_UPGRADE_MESSAGE = 'Please get the latest version of Vuze to use the Play button. <a href="javascript:void(0);" onclick="openUrl(\'http://www.vuze.com\')">http://www.vuze.com</a>'

var ERROR_CANNOT_CREATE_FREE_LICENSE = "Cannot create a free license for this content";
var waitingForLicenseToFireTorrentDownload = true;

function makeFreeScreenerLicenseRPCRequest(rpcParameters, successCallback, failureCallback) {
	log_remote(/*namespace*/ 'az.license.license',/*message*/ 'Requesting FFFS License for ' + rpcParameters.hash,/*importance*/ 'USUAL')
	var requestParameters = { service : "rpc" ,
							  cmd     : "license;0;freescreener;obtainLicense;" + JSONUtils.toJSONString(rpcParameters) };

	var url = getServiceURL();

	if( url && url != null && url != '' ) {
		new Ajax.Request(url,
		  {
		  	parameters : requestParameters,

		    onSuccess : function(transport){
		    	var response = transport.responseText;
		      	if(response) {
		      		var result = response.split(';');
					if(result.length > 2) {
						var type = result[1];

						//Reconstruct the potentially broken parameters json object
						//And evaluate it as a JS object
						result.splice(0,2);
						var parameters = JSONUtils.parseJSON( result.join(';') );

						if(type == "exception") {
							log_remote(/*namespace*/ 'az.license.license',/*message*/ 'Error getting FFFS License for ' + rpcParameters.hash,/*importance*/ 'IMPORTANT')
							failureCallback(parameters);
							var message = parameters.message;
							//alert('error (exception) in response - ' + message);
						}

						if(type == "response" ) {
							log_remote(/*namespace*/ 'az.license.license',/*message*/ 'Success getting FFFS License for ' + rpcParameters.hash,/*importance*/ 'USUAL')
							successCallback(parameters);
						}
					}
				} else {
					//alert('error = no response');
					failureCallback(response);
		      	}
		    }
		  } );
	}

}

function fireTorrentDownload( torrentUrl ) {
	if( typeof torrentUrl == 'undefined' ) {
		torrentUrl = $('torrentUrl').value;
		// $('torrentUrl').value = '';
	}
    sendPlayMsg(torrentUrl, playNow)
//	var listener = 'torrent'
//	var params = {'url':torrentUrl}
//	if(playNow)	params['play-now'] = playNow;
//	if( content && content.subs_id ) {
//		listener = 'metasearch'
//		params.subs_id = content.subs_id
//		params.subs_rid = content.subs_rid
//	}
//	sendMessage(listener,'load-torrent',params);
}

function fadeAppearIds( fadeIds , appearIds ){

	if( fadeIds & appearIds) {
		var ok = true;

		fadeIds = $A( fadeIds )
		appearIds = $A( appearIds )
		fadeIds.each( function(id) {
			if( ! $( id ) ) {ok = false}
		});
		appearIds.each( function(id) {
			if( ! $( id ) ) {ok = false}
		});

		if( ok ) {
			fadeIds.each( function(id) {
				Element.hide( id )
			});
			appearIds.each( function(id) {
				Element.show( id )
			});
		}
	}
}

function sendPlayMsg( url, playState ) {
    var listener = 'torrent'
    if( downloadSource ) {
        url += ( ( url.indexOf("?") != -1 ) ? "&" : "?" ) + "referal=" + downloadSource;
    }
    var params = {'url': url, 'play-now': playState }
    if( content && content.subs_id ) {
        listener = 'metasearch'
        var k = Object.keys(content)
        $A(k).each(function(key){
            params[key] = content[key]
        })
    }
    sendMessage(listener,'load-torrent',params);
    fadeAppearIds( [ "purchase" , "bigDownloadButton" ] , [ "gohome" ] );
}

function licenseRPCFail(response) {
    if( typeof fireCallBack != 'undefined' ) {
            // If the drm fireCallBack function exists, use it to report the error
            fireCallBack(STATUS_FAILURE, ERROR_CANNOT_CREATE_FREE_LICENSE);
    }
}

function signin( networkId, elt, assetHash, playState, fromAzureus, opts){
    if(fromAzureus) {
        var callbackString = 'deliver(\''+assetHash+'\', '+playState+', '+fromAzureus+', '+opts+')'
        clientApp.popup('/user/LoginPopup.html',{callback:callbackString});
    } else {
        signup( networkId, elt, assetHash, playState, fromAzureus, opts)
    }
}

function signup( networkId, elt, assetHash, playState, fromAzureus, opts){
    if( fromAzureus ){
        if(assetHash && assetHash != "null" ){
            clientApp.gotoUrl("/downloadapp/" + assetHash, networkId?"ContentNetwork."+networkId:null)
        } else {
            clientApp.gotoUrl("/user/SignUp.html", networkId?"ContentNetwork."+networkId:null)
        }
    } else {
        webBrowser.signUp(networkId, elt, assetHash, playState, fromAzureus, opts)
    }
}

function deliver( assetHash, playState, fromAzureus, opts) {
	var thisContent = contentData['h_'+assetHash] || {};
	if(!thisContent.hash) thisContent.hash = assetHash
	deliverWithFullData( thisContent, playState, fromAzureus, opts);
}


function deliverWithFullData( thisContent, playState, fromAzureus, opts) {
    if( thisContent.hash ){
        if ( playState ) {
            buttonEffect('dl_link_' + thisContent.hash + '_stream')
        } else {
            buttonEffect('dl_link_' + thisContent.hash)
        }
    }
    debugMagnet("deliverWithFullData")
    setDownloadSource(playState ? thisContent.playNowKey : thisContent.downloadKey);
    var torrentURL = thisContent.torrentURL;
    var optParams = $H(thisContent.optionalParameters)
    if(optParams) torrentURL += ( ( torrentURL.indexOf("?") != -1 ) ? "&" : "?" ) + optParams.toQueryString();
    debugMagnet("deliverWithFullData: torrentURL set")
	if ( fromAzureus ) {
            debugMagnet("deliverWithFullData: fromAzureus true")

		content = new contentObj(thisContent.hash);
		setPlayNow( playState );
		if( opts ) {
                    Object.extend(content, opts)
                }

		if ( thisContent.hasDrm ) {
			if ( thisContent.requiresLicense ) {
				$('torrentUrl').value = torrentURL;
				setMagnet(thisContent.hash);

				content.setFFS(false);
				content.setDRMed(true);
// alert("has DRM, requires license");
				checkAzureusVersion(
					true,
					playState,
					function(){acquireLicense(thisContent.hash)},
					function(){installUpgradeBar.showMsg(PLAY_UPGRADE_MESSAGE,{duration:10,scroll:'wrapper'})}
				);
			} else {
				if ( thisContent.freeScreener ) {
					// free-screener with DRM
					$('torrentUrl').value = torrentURL;
					setMagnet(thisContent.hash);

					content.setFFS(true);
					content.setDRMed(true);
// alert("has DRM, not license");
					checkAzureusVersion(
						true,
						playState,
						function(){
							makeFreeScreenerLicenseRPCRequest(
								{"hash": thisContent.hash },
								function () {
									acquireLicense(thisContent.hash)
								},
								licenseRPCFail

							)
						},
						function(){installUpgradeBar.showMsg(PLAY_UPGRADE_MESSAGE,{duration:10,scroll:'wrapper'})}
					);
				} else {
					// error case, or the content shouldn't be downloadable now
					alert( "Sorry, this content can't be downloaded at this time." );
				}
			}
		} else {
//			if ( thisContent.freeScreener ) {
//				// non-DRM free-screener
//				setMagnet(thisContent.hash);
//
//// alert("non drm freescreener");
//				checkAzureusVersion(
//					true,
//					playState,
//					function(){
//						makeFreeScreenerLicenseRPCRequest(
//							{"hash": thisContent.hash },
//							sendPlayMsg.bind( this, torrentURL, playState ),
//							licenseRPCFail
//						);
//					},
//					function(){installUpgradeBar.showMsg(PLAY_UPGRADE_MESSAGE,{duration:10,scroll:'wrapper'})}
//				);
//			} else {
//// alert("not freeScreener not DRM")
				if ( playState ) {
					checkAzureusVersion( true, true,
							sendPlayMsg.bind( this, torrentURL, true ),
							function(){installUpgradeBar.showMsg(PLAY_UPGRADE_MESSAGE,{duration:10,scroll:'wrapper'})}
							);
				} else {
					sendPlayMsg( torrentURL, false );
				}
//			}
		}

	} else {

		content = new contentObj(thisContent.hash);
		setPlayNow(playState);
		if( opts ) {
                    Object.extend(content, opts)
                }

                webBrowser.getContent(content, fromAzureus, playState)

//		if ( !thisContent.hasRules || thisContent.noPrice || ( thisContent.freeScreener && !thisContent.hasDrm ) ) {
//// alert("not from Azureus - no rules / no price - "+thisContent.downloadKey);
//                loadOrAlert(thisContent.hash, thisContent.platformURL );
//            } else {
//// alert("not from Azureus - hasrules - "+thisContent.detailsURL);
//			if ( thisContent.freeScreener ) {
//				content.setFFS( true );
//				setMagnet(thisContent.hash);
//				detectAndLoadPage(thisContent.detailsURL);
//			}
//		}
	}
}

