var debug = false;
var inBucketBrowse = false; // will be set true by BucketBrowse.html
var disableRepositioning = true; // to disable the bucket repositioning action here.

if( typeof VUZE == "undefined" ) {
    var VUZE = window.VUZE || {};
}
VUZE.log = function( msg , level){
	//if($('qwert')) $('qwert').innerHTML += msg
	//if(level != null){
	//	if($('debugg')) $('debugg').innerHTML += msg
	//}
}
VUZE.ThoughtBubbleManager = function(){
	this.active = 0
	this.remaining = 0

	this.register = function(_tb){
		VUZE.log( "<br/>registering... ")
		this.setActive( this.active + 1 )
		if(_tb.duration > 0) this.setRemaining( Math.max( this.remaining , _tb.duration ) )
	}
	this.unregister = function(_tb){
		VUZE.log( "<br/>unregistering... ")
		this.setActive( this.active - 1 )
	}
	this.setRemaining = function(remaining){
		this.remaining = remaining
		var t = this
		var rem = remaining - 1
		if(remaining) setTimeout( function(){t.setRemaining(rem)} , 1000)
	}
	this.setActive = function( active ){
		VUZE.log( "<br/>active set to: " + active)
		this.active = active
	}
}
var TBM = new VUZE.ThoughtBubbleManager()

VUZE.ThoughtBubble = {
	create: function( params ){
	VUZE.log( "<br/>creating Bubble... " + params.id)
		var SUFFIX = "_tb"
		var tbId = params.id + SUFFIX
		var tbIdClose = tbId + "_close"
		var parentId = params.id
		var msg
		var div
		var container

		if(typeof params.source == 'String') {
			VUZE.log( "<br/>creating Bubble... with : " + params.source)
			div = document.createElement("div")
			msg = params.source
		} else {

			div = params.source
			VUZE.log( "<br/>creating Bubble... with : " + params.source.innerHTML)
			msg = div.innerHTML
			div.innerHTML = ''
				VUZE.log( "<br/>creating Bubble... with : " + div.innerHTML)
		}
		div.id = tbId
		div.className = 'tb cont'
		div.style.width = params.s.w + 'px'
		div.style.height = params.s.h + 'px'
		div.style.display = 'none'

		container = document.body;
		if(params && params.container){
			container = $(params.container)
		}
		container.appendChild(div)

		var contSize = {width:$(tbId).getWidth(),height:$(tbId).getHeight()}
		VUZE.log( "<br/>creating Bubble... " + params.id + "["+msg+"]")

		if(!params.arrow) params.arrow = {}
		if(!params.arrow.pos) params.arrow.pos = 'top'
		if(!params.arrow.type) params.arrow.type = ''
		if(!params.arrow.offset) params.arrow.offset = 80

		function setContainerSize(){
			div.style.width = params.s.w + 'px'
			div.style.height = contSize.height + 'px'
		}
		function drawCorner(/*json width and height*/sizes,/*boolean*/top,/*boolean*/left){
			var el = document.createElement("div");
			el.style.width = sizes.width + 'px'
			el.style.height = sizes.height + 'px'
			el.style.position = "absolute"
			el.style.top = ( top ? 0 : (contSize.height - sizes.height) ) + 'px'
			el.style.left = ( left ? 0 : (contSize.width - sizes.width) ) + 'px'
			var c = (top ? "t" : "") + (left ? "l" : "");
			el.className = (_IE6 ? "ie":"") + "tbc " + c
			div.appendChild(el)
			//alert(el.className)
			delete el
		}
		function drawBorder(top, right, bottom, left){
			var el = document.createElement("div");
			var w = top || bottom
			var l = left || right
			/*if(!right)*/ el.style.width = ( w ? (contSize.width - 2*sizes.width) : sizes.width ) + 'px'
			/*if(!bottom)*/ el.style.height = ( l ? (contSize.height - 2*sizes.height) : sizes.height) + 'px'
			el.style.position = "absolute"
			el.style.overflow = "hidden"
			el.style.top = ( l ? sizes.height : ( top ? 0 : (contSize.height - sizes.height)  ) ) + 'px'
			el.style.left = ( w ? sizes.width : ( right ? (contSize.width - sizes.width) : 0 ) ) + 'px'
			var bo = (w ? "w " : "") + (l ? "l " : "") + (bottom ? "b" : "") + (right ? "r" : "");
			el.className = (_IE6 ? "ie":"") + "tbbo" + bo
			div.appendChild(el)
			delete el
		}
		function drawArrow(){
			var el = document.createElement("div");
			var horizontal = params.arrow.pos == 'top' || params.arrow.pos == 'bottom'
			var big = params.arrow.type == 'big'
			var width =  big ? (horizontal ? sizes.abigwidth : sizes.abigheight) : (horizontal ? sizes.awidth : sizes.aheight)
			var height = big ? (horizontal ? sizes.abigheight : sizes.abigwidth) : (horizontal ? sizes.aheight : sizes.awidth)
			el.style.width = width + 'px'
			el.style.height = height + 'px'
			el.style.position = "absolute"
			el.style.top = ( - (_IE6 ? 2 : 3) - (big ? 10 : 0) ) + 'px'
			el.style.left = (contSize.width - width + 13) + 'px'
			if(horizontal){
				el.style.left = (params.arrow.offset / 100 * contSize.width) + 'px'
				if(params.arrow.pos == 'bottom') el.style.top = (contSize.height - height) + 'px'
			}else{
				el.style.top = (params.arrow.offset / 100 * contSize.height) + 'px'
				if(params.arrow.pos == 'left') el.style.left = '-13px'
			}
			el.className = (_IE6 ? "ie":"") + "tb a" + params.arrow.type + params.arrow.pos;
			div.appendChild(el)
			delete el
		}
		function drawClose(){
			var el = document.createElement("a");
			el.href = "#"
			el.style.width = sizes.cwidth + 'px'
			el.style.height = sizes.cheight + 'px'
			el.style.position = "absolute"
			el.style.top = (sizes.height) + 'px'
			el.style.left = ((contSize.width - sizes.width - sizes.cwidth )) + 'px'
			el.className = "tb cl"
			el.id = tbIdClose
			div.appendChild(el)
			delete el
		}
		function prepareMsg(/*string*/msg){
				VUZE.log( "<br/>preparing msg... " + params.id)
			var el = document.createElement("div")
			var random = Math.floor(Math.random()*1000)
			el.className = "tb pmsg"
			el.id = "tbmsg" + random
			el.style.width = (contSize.width - 2 * sizes.width - 6 ) + 'px'
			el.innerHTML = msg
			document.body.appendChild(el)
			contSize.height = $('tbmsg'+random).getHeight() + 2 * sizes.height
			el.style.display='none'
			document.body.removeChild(el)
			delete el, random
		}
		function insertMessage(/*string*/msg){
			var el = document.createElement("div")
			var random = Math.floor(Math.random()*1000)
			el.className = "tb pmsg"
			el.id = "tbmsg" + random
			el.innerHTML = msg
			div.appendChild(el)
			el.style.height = (contSize.height - 2*sizes.height - 6) + 'px'
			el.style.width = (contSize.width - 2*sizes.width - 6) + 'px'
			delete el, random
		}
		var w = h = 22;
		var sizes = {width:w,height:h,awidth:26,aheight:16,abigwidth:25,abigheight:26,cwidth:13,cheight:13}

		prepareMsg(msg)
		VUZE.log( "<br/>creating Bubble... " + params.id)
		setContainerSize()
		drawCorner({width:w,height:h},true,true)
		drawCorner({width:w,height:h},true,false)
		drawCorner({width:w,height:h},false,true)
		drawCorner({width:w,height:h},false,false)
		VUZE.log( "<br/>creating Bubble... " + params.id)
		drawBorder(true, false, false, false)
		drawBorder(false, true, false, false)
		drawBorder(false, false, true, false)
		drawBorder(false, false, false, true)
		drawArrow()
		insertMessage(msg)
		drawClose()
		VUZE.log( "<br/>finished creating Bubble... " + params.id)

		return {
			render: function( opts ){
			VUZE.log( "<br/>rendering Bubble... ")
			var flashHidden = false
			if( TBM.active > 0 ) {
				var t4 = this;
				var opts4 = opts;
				setTimeout( function(){ t4.render(opts4) }, 1050); VUZE.log("<br/>already someone there: " + TBM.remaining + "s left; active: " + TBM.active); return; }
			else { TBM.register({duration:opts.duration || 10}); VUZE.log("<br/>registering for: " + (opts.duration || 10) + "s;"); }

				var id = opts.id

				function toggelFlash(bool){
					if(flash.needsToggling()){
						if( (!flashHidden && !bool && isOverlappingFlash()) || (flashHidden && bool) ){
							toggleFlashness( bool );
							flashHidden = !bool;
						}
					}
				}
				function isOverlappingFlash(){
					if($('vdetails')) return false;
					return true;
				}
				function position(){
					var _top = 0;
					var _left= 0;
					if($(id)){
						var tabPos = Element.cumulativeOffset( $(id) )
						if( opts.container && $(opts.container) ) {
							tabPos[0] = tabPos[0] -  Element.cumulativeOffset( opts.container )[0]
							tabPos[1] = tabPos[1] -  Element.cumulativeOffset( opts.container )[1]
							//tabPos =  Element.positionedOffset( $(id) )
						}
						if(opts.relpos){
							if(opts.relpos == 'right'){
								_top = tabPos[1] - $(id).getHeight();
								_left = tabPos[0] + $(id).getWidth() + 20
							} else {
								_top = tabPos[1] - $(id).getHeight() ;
								_left = tabPos[0] - $(id+SUFFIX).getWidth() - 20;
								if( _left < 0 ) _left = tabPos[0]
							}
						} else {
							//thought bubble under to the left
							_top = tabPos[1] + $(id).getHeight() + 10 ;
							_left = tabPos[0] - 0.6 * $(id+SUFFIX).getWidth() - 20;
							if( _left < 0 ) _left = tabPos[0]
						}
					}

					if(opts.pos) {
						_top = opts.pos[1]
						_left = opts.pos[0]
					}

					$(id+SUFFIX).style.top = _top + 'px'
					$(id+SUFFIX).style.left = _left + 'px'
					toggelFlash( false )
					//$(id+SUFFIX).style.top = $(id+SUFFIX).style.left = 0
				}
				function close(event) {
					if(_IE6){
						Element.hide( id+SUFFIX ); TBM.unregister();toggelFlash(true)
					} else {
						Effect.Fade( id+SUFFIX, {duration:0.4,afterFinish: function(){TBM.unregister();toggelFlash(true)}} )
					}
					Event.stopObserving(window,'resize', position)
					if(event) Event.stop(event);
				}

				if(opts.condition && typeof opts.condition == 'function' && (opts.condition).call()) {
					if(opts.onclose && typeof opts.onclose == 'function'){
						var fn = opts.onclose
						Event.observe(tbIdClose, 'click', function(ev){ fn.call();close(ev); })
					} else {
						Event.observe(tbIdClose, 'click', close )
					}

					position();

					if(_IE6){
						Element.show( id+SUFFIX )
					} else {
						Effect.Appear( id+SUFFIX )
					}

					Event.observe(window,'resize', position)

					if( opts.duration && parseInt( opts.duration ) ) { window.setTimeout( close , parseInt(opts.duration)*1000 ) }
				} else {
					//alert('not displaying thoughtbubble')
					//(opts.onclose).call()
					TBM.unregister();
				}
			}
		};
	}
}
var alertBarContainer = 'summ'
Event.observe(document, 'dom:loaded', function(){
	if($('list_view') != null) { alertBarContainer = 'list_view'; }
	if($('fcont') != null) { alertBarContainer = 'fcont'; }
	if($('vabout') != null) { alertBarContainer = 'vabout'; }
	if($('d_columns') != null) { alertBarContainer = 'd_columns'; }
	if($('cont') != null) { alertBarContainer = 'cont'; }
        if($('modules') != null) { alertBarContainer = 'modules'; }
        if($('gwModulesBox') != null) { alertBarContainer = 'gwModulesBox'; }
})

// Functions related to the bucket view of the content preview for browse
var azContent = {};	// Namespace for these functions

azContent.loaded = false;

//
azContent.curview = "";
azContent.showDetails = function(evt,that,bool){

	if( ! evt ) {
		evt = window.event;
	}

	var bucket = null;

	if( evt.target ) {
		bucket = azContent.getBucket(evt.target);
	} else if( evt.srcElement ) {
		bucket = azContent.getBucket(evt.srcElement);
	}

	if( bool ) {/* && that.onmousemove*/
		azContent.getBucketChild(bucket, 'prevdets').style.display = 'block';
		azContent.getBucketChild(bucket, 'bucket_opaque').style.display = 'block';
	} else {
		azContent.getBucketChild(bucket, 'prevdets').style.display = 'none';
		azContent.getBucketChild(bucket, 'bucket_opaque').style.display = 'none';
	}

	return;
}


function previewBucketInit(buckcont){
	$$([name="pvdlink"]).invoke('observe', 'click', bubbleOff)
	return;
}

function bubbleOff(e){
	e = (e) ? e : ((event) ? event : null);
	if(e){
		e.cancelBubble=true;
	}
};


// Get a reference to the bucket
azContent.getBucket = function(element) {
	if( element.bucket ) {
		return element.bucket;
	}

	if( ! element ) {
		return null;
	} else if( azContent.getClassAttributeValue(element) == 'gmi' ) {
		element.bucket = element;
		return element;
	} else {
		element.bucket = azContent.getBucket(element.parentNode);
		return element.bucket;
	}
}

azContent.getBucketChild = function(bucket, classStyle) {
	if( ! bucket ) {
		return null;
	}

	if( bucket[classStyle] != null ) {
		return bucket[classStyle];
	}

	if( azContent.getClassAttributeValue(bucket) == classStyle ) {
		bucket[classStyle] = bucket;
		return bucket;
	} else {
		var children = bucket.childNodes;

		for( var a=0; a<children.length; a++ ) {
			if( children[a].nodeType == 1 ) {
				var ret = azContent.getBucketChild(children[a], classStyle);

				if( ret != null ) {
					bucket[classStyle] = ret;
					return ret;
				}
			}
		}
	}

	return null; // If it hasn't found the child, return null
}

azContent.getClassAttributeValue = function(element) {
	if( ! (element && element.getAttribute) ) {
		return null;
	}
	var attr = element.getAttribute('class');

	if( attr == null ) {
		attr = element.getAttribute('className');
	}

	return attr;
}

azContent.loaded = true;

function getBrowserViewable() {
	var width,height;
	if (self.innerHeight) { // all except Explorer
		width = self.innerWidth;
		height = self.innerHeight;
	} else if (document.documentElement && document.documentElement.clientHeight) {
		// Explorer 6 Strict Mode
		width = document.documentElement.clientWidth;
		height = document.documentElement.clientHeight;
	} else if (document.body) { // other Explorers
		width = document.body.clientWidth;
		height = document.body.clientHeight;
	}

	// If width or height are undefined, set them to 0 (zero)
	if( ! width ) width = 0;
	if( ! height ) height = 0;

	return { width: width, height: height };
}

//TODO GET THOS DAMN URLS OUT OF THERE !!!!!
var IMG_ALERT = 'http://cache1.vuze.com/cdnassets/4/27296cdcdf022115a09d451ea1639513/img/ico_alert.gif';
var IMG_PROGRESS = 'http://cache1.vuze.com/cdnassets/4/89f5b22785166e3c0f5d619b53d8e592/img/indicator_alert.gif';
var IMG_OK = 'http://cache1.vuze.com/cdnassets/4/e336875fe8aaac30e8b0f1767db5b86a/img/green_check.gif';
var IMG_MATURE = 'http://cache1.vuze.com/cdnassets/4/fe86843b64f6ee4aa542efa69c09d672/img/MA_icon.png';
var IMG_IDEA = 'http://cache1.vuze.com/cdnassets/4/a43ad4ce1c63a0d3d5b870c285329761/img/ico_idea.gif';
var IMG_INFO = 'http://cache1.vuze.com/cdnassets/4/5bad3c03d49f361239bffc2249de8fbd/img/info_icon.gif';

var img_array = [ IMG_ALERT , IMG_PROGRESS , IMG_OK , IMG_MATURE , IMG_IDEA , IMG_INFO ]

function AlertBars() {
	var list = new Array();
	if(typeof $A != 'undefined') this.list = $A( list )
}
AlertBars.prototype.setList = function( l ) {
	this.list = l
}
AlertBars.prototype.add = function( alertBarId ) {
	var l = this.list
	l.push( alertBarId )
	this.setList( l )
}
AlertBars.prototype.remove = function( alertBarId ) {
	var l = this.list
	this.setList( l.without( alertBarId ) )
}

var alertBars = new AlertBars()

var detailAlertBar = function(name){
	this.name = 'unknown';
	this.showWhereSet = false;
	if(name!=null) {this.name = name}
	this.alertId = (new Date()).getTime();

	alertBars.add( this.alertId );

	this.id="alertbar" + this.alertId;

	var hthree 	= document.createElement("H3");
	hthree.id=this.id;
	hthree.className="alert";
	var alrtimg	= document.createElement("img");
	alrtimg.id = "bigalertimg" + this.alertId;
	alrtimg.on = false;
	//alrtimg.style.marginRight = '0.5em'
	//alrtimg.style.marginLeft = '0.5em'
	alrtimg.src = IMG_PROGRESS;
	hthree.appendChild(alrtimg);
	var alrtmsg	= document.createElement("SPAN");
	alrtmsg.id = "bigalert" + this.alertId;
	//alrtmsg.on = false;
	hthree.appendChild(alrtmsg);
	var cont;

	this.showing = false;

	this.showWhere = function (divid) {
		this.cont = $(divid);
		cont = this.cont;
		var insertIn = cont
		if(cont){
			var divs = cont.childElements(); //cont.immediateDescendants();
			hthree.style.display = 'none';
			var div = divs[0]
			if( cont.id != "vabout" ) {
				var elts = divs.findAll(function(div){return div.hasClassName('bd')})
				if(elts.size()>0) {
					var d = elts[0]
					var ds = d.childElements()
					div = ds[0]
					insertIn = d
				}
			}
			insertIn.insertBefore(hthree,div);
			this.showWhereSet = true;
		}
	}
	this.setImg = function( imgSrc ) {
		//alert( imgSrc )
		img_array = $A( img_array )
		var hit = false
		img_array.each( function(img){
			if(imgSrc == img) hit = true;
		});
		if(hit) alrtimg.src = imgSrc;
	}
	this.setBgColor = function( bgColor ){
		//hthree.style.bgColor = bgColor
		$(this.id).setStyle({ backgroundColor : bgColor })
	}
	this.showMsg = function (damsg , params){
		if( ! this.showWhereSet ) {
			this.showWhere( alertBarContainer )
		}
		if(params == null) {
			this.showExtendedMsg(damsg, {image:IMG_ALERT})
		} else {
			this.showExtendedMsg(damsg, params)
		}
	}
	this.showExtendedMsg = function (damsg , params){
		this.clear();
		if( params.image && params.image != '' ) {
			if(params.image == 'none') {
				alrtimg.style.display = 'none'
			} else {
				if(alrtimg.style.display == 'none') alrtimg.style.display = 'inline'
				this.setImg ( params.image )
			}
		} else {
			this.setImg ( IMG_ALERT )
		}
		if( params.bgcolor && params.bgcolor != '' ) {
			this.setBgColor ( params.bgcolor )
		} else {
			//this.setBgColor ( IMG_ALERT )
		}
		if( params.duration && !isNaN(parseInt(params.duration)) ) {
			var t = parseInt(params.duration) * 1000;
			var currentBar = this;
			setTimeout(function(){currentBar.clear()}, t)
		}

		if( params.textAlign && params.textAlign != '' ) {
			hthree.style.textAlign = params.textAlign
			alrtmsg.style.styleFloat = params.textAlign
		}
		if( params.imgClose && params.imgClose != '' ) {
			var thisBar = this
			var alrtaClose = document.createElement('a')
			Event.observe( alrtaClose, 'click', function(){
					thisBar.clear();
					createCookie('showRec','0',1)
				});
			Event.observe( alrtaClose, 'mouseover', function(){
				alrtaClose.style.backgroundPosition = 'top left'
			});
			Event.observe( alrtaClose, 'mouseout', function(){
				alrtaClose.style.backgroundPosition = 'bottom left'
			});
			alrtaClose.addClassName('close')
			alrtaClose.style.backgroundImage = 'url(' + params.imgClose + ')';
			alrtaClose.style.backgroundPosition = 'bottom left'
			alrtaClose.style.textIndent = '-5000px'
			alrtaClose.innerHTML = 'close'
			alrtaClose.href="javascript:void(0);"

			alrtmsg.style.styleFloat = 'left'
			alrtimg.style.styleFloat = 'left'

			hthree.appendChild( alrtaClose )
		}
		if( params.scroll && params.scroll != '' ) {
			if( params.scroll == 'body' ) {
				realBody.scrollTop = 0;
			} else {
				$( params.scroll ).scrollTop = 0;
			}
		}

		if(this.isShowing) {
			alrtmsg.innerHTML = "";
		}

		alrtmsg.innerHTML = damsg;

		this.setShowing( true );

		//hthree.style.display = 'block'
		Element.show('alertbar' + this.alertId)

	}
	this.isShowing = function() {
		return this.showing
	}
	this.setShowing = function( bool ) {
		this.showing = bool;
	}
	this.clear = function() {
		Element.hide( this.id )
		this.setShowing( false );
	}
	this.remove = function() {
		alertBars.remove( this.alertId );
		Element.remove( this.id );
	}

	return;
};

var installUpgradeBar = new detailAlertBar('installUpgrade');
var PLAY_UPGRADE_MESSAGE = 'Please get the latest version of Vuze to use the Play button. <a href="http://www.vuze.com">http://www.vuze.com</a>';

function checkAzureusVersion( fromAzureus, playNow, successCallback, failureCallback) {
	debugDL('checkAzureusVersion() :: fromazureus: ' + fromAzureus + ' playNow: ' + playNow)
	debugDL('checkAzureusVersion() :: ' + playNow)
	if(playNow) {
		debugDL('checkAzureusVersion() :: ' + successCallback)
		debugDL('checkAzureusVersion() :: ' + failureCallback)
		var minAzVersion = '3.0.2.3'
		if(_OS == 'Mac'){
			minAzVersion = '3.0.3.3'
		}
		sendMessageFromExternalBrowser('display', 'is-version-ge', {'id':'client','version': minAzVersion}, successCallback, failureCallback)
	} else {
		debugDL('checkAzureusVersion() :: ' + successCallback)
		successCallback();
	}
}
function setPlayNow( bool ) {
	playNow = bool;
}
function setDownloadSource(_downloadSource) {
	downloadSource = _downloadSource
}

function toggleView(nb) {
	if( $('v' + nb) != null ) {
		var bl = $('v' + nb)
		var img = $('i' + nb)
		if(bl.style.display != 'none') {
			img.src = 'http://cache1.vuze.com/cdnassets/4/37b52034f1a35de13ab19a19aadf6144/img/arrowup.gif'
		} else {
			img.src = 'http://cache1.vuze.com/cdnassets/4/3fb77dd13c8cd519ef010480cc4bbc41/img/arrowdown.gif'
		}
		Effect.toggle( bl , 'blind', {duration:0.4} );
	}
}

var azChannel = {};	// Namespace for these functions

azChannel.performWipeIn = function(evt) {
    if( ! evt ) {
		evt = window.event;
	}

	var target = null;

	if( evt.target ) {
		target = evt.target;
	} else if( evt.srcElement ) {
		target = evt.srcElement;
	}

	var bucket = azChannel.getBucket(target);
	azChannel.getBucketChild(bucket, 'channel_bucket_opaque').style.display = 'block';
	azChannel.getBucketChild(bucket, 'channel_bucket_meta').style.display = 'block';
}

azChannel.performWipeOut = 	function(evt) {
	if( ! evt ) {
		evt = window.event;
	}

	var target = null;

	if( evt.target ) {
		target = evt.target;
	} else if( evt.srcElement ) {
		target = evt.srcElement;
	}

	var bucket = azChannel.getBucket(target);
	azChannel.getBucketChild(bucket, 'channel_bucket_opaque').style.display = 'none';
	azChannel.getBucketChild(bucket, 'channel_bucket_meta').style.display = 'none';
}

// Get a reference to the bucket
azChannel.getBucket = function(element) {
	if( ! element ) {
		return null;
	} else if( azChannel.getClassAttributeValue(element) == 'channel_bucket_roundcont' ) {
		return element;
	} else {
		return azChannel.getBucket(element.parentNode);
	}
}

azChannel.getBucketChild = function(bucket, classStyle) {
	if( ! bucket ) {
		return null;
	} else if( azChannel.getClassAttributeValue(bucket) == classStyle ) {
		return bucket;
	} else {
		var children = bucket.childNodes;

		for( var a=0; a<children.length; a++ ) {
			if( children[a].nodeType == 1 ) {
				var ret = azChannel.getBucketChild(children[a], classStyle);

				if( ret != null ) {
					return ret;
				}
			}
		}
	}

	return null; // If it hasn't found the child, return null
}

azChannel.getClassAttributeValue = function(element) {
	if( ! (element && element.getAttribute) ) {
		return null;
	}
	var attr = element.getAttribute('class');

	if( attr == null ) {
		attr = element.getAttribute('className');
	}

	return attr;
}
if(typeof Element != 'undefined') {
	if(typeof Element.addMethods != 'undefined') {
	Element.addMethods({
		smoothScrollTo : function( element , url, params) {
			element = $(element);
			var pos = Element.cumulativeOffset(element);
			var relativePos = Element.viewportOffset( element )
			var x0 = pos[0] - relativePos[0]
			var y0 = pos[1] - relativePos[1]
                        //console.log("GOAL POS :: x0: "  + pos[0] + " / y0: " + pos[1])
                        //console.log("x0: "  + x0 + " / y0: " + y0)
                        //console.log("relativePosX: "  + relativePos[0] + " / relativePosY: " + relativePos[1])

			var nbSteps = 60;
			var duration = 300;
			var callback = null;
			var scrollElt = null;

			if(params){
				if(params.steps) nbSteps = params.steps;
				if(params.duration) duration = params.duration;
				if(params.afterFinish) callback = params.afterFinish;
				if(params.scrollElt) {
					scrollElt = params.scrollElt
				}
			}
			if( params && params.scrollElt && $(params.scrollElt)) {scrollElt = $(params.scrollElt)}

			var stepX = relativePos[0]/nbSteps;
			var stepY = relativePos[1]/nbSteps;
			var nb = 0;
			var interval;
			var phases = {first: nbSteps*80/100, second: nbSteps*15/100, third: nbSteps*5/100}
			var goodX = false, goodY = false;
                        //console.log("duration: " + duration)
                        //var cumulTime = 0
			goScrollTo( stepX , stepY )

                    function goScrollTo( x, y ) {
                        //console.log("goScrollTo: " + nb + ":: " + x + "," + y)
	    		doScrollTo(x, y)
	    		
	    		if(nb < nbSteps){
	    			interval = (nb < phases.first + phases.second)?((nb < phases.first)?duration/3/phases.first:duration/3/phases.second):duration/3/phases.third;
                                var currX = (x0 + nb*x)
                                var currY = (y0 + nb*y)
	    			if( x > 0 && (currX + x) > pos[0] || x < 0 && (currX + x) < pos[0] ) goodX = true;
	    			//if( y > 0 && (currY + y) > pos[1] || y < 0 && (currY + y) < pos[1] ) y = goodY;
                                if( (y > 0 && (currY + y) > pos[1] && currY <= pos[1]) || (y < 0 && (currY) <= pos[1]) ) goodY = true;
                                if(goodX && goodY) {
                                    nb = (nbSteps - 1)
                                }
                                //console.log("CURR POS: x:"+currX+" / y: " + currY)
                                nb++
	    			setTimeout(function(){ goScrollTo( x , y ) } , interval)
                                //cumulTime = cumulTime + interval
	    		} else {
                            //console.log("FINAL POS: x:"+currX+" / y: " + currY)
                            //console.log("exec: " + cumulTime )
	    			if(typeof callback == 'function') {
	    				setTimeout( callback, ( interval + 10 ) )
	    			}
	    		}
                        
                    }
                    function doScrollTo(x,y){

	    		if(scrollElt != null){
	    			//$(scrollElt).scrollLeft=nb*x
	    			//$(scrollElt).scrollTop=nb*y-60
                                $(scrollElt).scrollTop=y0 + nb*y -32
	    		} else {
	    			window.scrollTo(x0 + nb*x, y0 + nb*y)
	    		}
                    }
		},
                isVisible: function(element){
                    element = $(element)
                    if( !element.visible() ) return false
                    //return element.ancestors().inject(true, function(visible, elt){ return visible && elt.visible()} )
                    var ancestors = element.ancestors()
                    for(var i=0;i<ancestors.size();i++){
                        if( !ancestors[i].visible() ) return false
                    }
                    return true
                }
	})
	}
}
var contentObj = function(_hash) {
	this.hash = _hash;
	this.FFS = false;
	this.DRMed = false;
	this.licenseChecked = false;
	this.BR = false;

	this.setHash = function( _hash ){
		this.hash = _hash;
	}
	this.getHash = function( ){
		return this.hash;
	}
	this.setFFS = function( _bool ){
		this.FFS = _bool;
	}
	this.isFFS = function( ){
		return this.FFS;
	}
	this.setDRMed = function( _bool ){
		this.DRMed = _bool;
	}
	this.isDRMed = function( ){
		return this.DRMed;
	}
	this.setLicenseChecked = function( _bool ){
		this.licenseChecked = _bool;
	}
	this.isLicenseChecked = function(){
		return this.licenseChecked;
	}
	this.isBR = function(){
		return this.BR;
	}
	this.setBR = function( bool ) {
		this.BR = bool;
	}
}
var content = null;

function gotoHomeTab() {
	sendMessage("display", "open-url", { "url": "", "target": "minibrowse" } );
}

// function openUrl( url ){
// 	sendMessage("display", "open-url", { "url": url } );
// }

function debugDL( msg ){
//	alert( msg )
    if( typeof log4js != "undefined" ) log4js.info( "DL :: " + msg )
}

/* bucket layout */
var _fromDashboard = false;
var bucketElts = $A()
var channelElts = $A()
var N, P;
var bCont = 'list_view'
var w_delta = 0;
var RP;

/* category accordion + skyscraper ad */
var SIDE_ITEMS_WIDTH = 320;

Event.observe(document, 'dom:loaded', function() {
	RP = new repositionDaBuckets();
	if($('dashboard')) {_fromDashboard = true}
	if($('fcont') != null) { bCont = 'fcont'; };
	bucketElts = $$('.prevbuck'); //document.getElementsByClassName('prevbuck')
	N = bucketElts.size();
	if(_fromDashboard){
		channelElts = $$('.prevchan'); //document.getElementsByClassName('prevchan')
		var as = document.getElementsByTagName('a')
		var ass = $A(as).findAll(function(elt){
			return elt.getAttribute('rel') == 'dashboard'
		})
		ass.each(function(elt){
			elt.href = "javascript:gotoDetails('" + elt.href + "')"
		})
		P = channelElts.size();
	}

	if (inBucketBrowse)
		disableRepositioning = true;

	if (disableRepositioning)
		return;

	if(bucketElts.size()>0 && $(bCont) && !$('ppb')){
		// ad unit insertion for skyscraper ads
		var bcSize = $(bCont).getDimensions();
		w_delta = document.viewport.getWidth() - bcSize.width;

		RP.resize(bCont , {afterFinish: function() {if($('ch')) setTimeout( adjustHeader , 1 );}})
		Event.observe(window, 'resize', function() {
			RP.resize(bCont , {afterFinish: function(){if($('ch')) setTimeout( adjustHeader , 1 );}})
		})
	}
})

function adjustHeader() {
	/*var browserViewable = getBrowserViewable()
	var bWidth = browserViewable.width
	var bHeight = browserViewable.height
	if( bWidth > BROWSER_MAX_WIDTH) {*/
	//$('debugg').innerHTML += "<br/>" + ( ($('right_column').getHeight() > (getBrowserViewable().height-64) ) + " :: " + $(bCont).getWidth())
		if( $('right_column').getHeight() > (getBrowserViewable().height-64) ) {
			if ($("adSkyScraper"))
				$('ch').style.width = (document.viewport.getWidth() - w_delta) + 'px';
			else{
				//$('ch').style.width = '98%' //$(bCont).getWidth() + 'px';
            }
		} else {
			//$('ch').style.width = '98%'
		}
	//}
}
var _IE6 = false
var WN,Wa
var WP = 1;
var TOTAL_WIDTH
// var ITEM_WIDTH = 239;	// fullsize buckets
var ITEM_WIDTH = 151;	// mini-buckets
var MARGIN_MIN = 10;
var _margin_h, _half_margin_h;
var ITEMS_PER_LINE;
var contentWidth
var channelWidth
var running = false;
var waiting = false;

var smoothieRepos = true;

var repositionDaBuckets = function(){
	this.width = null
	this.timer = null
	this.resize = function(container,params,waiter){
		this.container = container
		this.params = params
		this.waiter = waiter
		if(smoothieRepos){
			if( $(this.container).getWidth() == this.width ) return
			if(this.timer) clearTimeout(this.timer);
			this.timer = setTimeout(this.onTimerResize.bind(this), 150);
			this.width = $(container).getWidth()
		} else {
			repositionBuckets(this.container,this.params,this.waiter)
		}
	}

	this.onTimerResize = function(){
		this.timer = null;
		repositionBuckets(this.container,this.params,this.waiter)
	}
}

function repositionBuckets(container,params,waiter){
	//return;
	if( running && (!waiting || waiter) ){
		waiting = true
		setTimeout( "repositionBuckets(bCont,null,true);" , 200 )
	}
	waiting = false
	running = true;

	//if(true || !_IE6 || _fromDashboard){
	TOTAL_WIDTH = $(container).getWidth() - ( _IE6 ? 12 : 2);

	//if($$('#'+container+' .prevbuck') && $$('#'+container+' .prevbuck')[0]) ITEM_WIDTH = $$('#'+container+' .prevbuck')[0].getWidth();
	if(_fromDashboard) { TOTAL_WIDTH = $('d_content').getWidth() - ( _IE6 ? 21 : 4); ITEM_WIDTH = 151; MARGIN_MIN = 6 }

	var items_per_line;

	function doDashboard(){
		//$('deb').style.color = 'white'

		getW( ITEMS_PER_LINE )
		setContainerSize()

		channelElts.each(function(elt,index){
				//elt.style.marginRight = ( ((index+1+WP) % WP == 0) ? MARGIN_MIN : _marginH  ) + 'px';
				applyMarginToBucket(elt,0,( ((index+1+WP) % WP == 0) ? MARGIN_MIN : _marginH  ) + 'px')
			//elt.style.marginLeft = elt.style.marginRight = (Math.floor(marginH / 2)) + 'px';
		})

		//$('deb').style.color = 'white'
		//$('deb').innerHTML += ("Container Width: " + TOTAL_WIDTH + " :: Content Width: " + contentWidth + " :: Channel Width: " + channelWidth + " :: marginH: " + marginH + " :: N: " + N + " :: P:" + P +  " :: Wa:" + Wa + " :: Columns of content: " + WN + " :: Columns of channels: " + WP + "<br/>")

	}
	function getW(W /*available columns of buckets*/){
		/* returns repartition columns of content / columns of channels */
		N = bucketElts.size();
		P = channelElts.size();
		Wa = W
		var WNr = Wa * N / ( N + P )
		var WPr = Wa - WNr

		var GNr = ( WNr ) / Math.floor(WNr)
		var GPr = ( WPr ) / Math.floor(WPr)

		if( Math.ceil( GNr * 1000 ) < Math.floor( GPr * 1000 ) ) {
			WN = Math.floor(WNr);
			WP = Math.ceil(WPr)
		} else {
			WN = Math.ceil(WNr);
			WP = Math.floor(WPr)
		}
	}

	function setContainerSize(){
		var offset = _IE6 ? 4 : 1;
		contentWidth = ( WN * (ITEM_WIDTH+marginH) + offset )
		channelWidth = ( WP * (ITEM_WIDTH+marginH) + offset )
		if( $('part2') ) $('part2').style.width = channelWidth + 'px'
		$('relatedcontent').style.width = contentWidth + 'px'
	}

	function getMargin(items){
		_margin_h = Math.floor( ( TOTAL_WIDTH - ITEM_WIDTH * items ) / items )
		return _margin_h
	}
	function setItemsPerLine(_itemsPerLine) {
		items_per_line = _itemsPerLine;
		ITEMS_PER_LINE = items_per_line //+ WP
	}
	setItemsPerLine( Math.floor( ( TOTAL_WIDTH  ) / (ITEM_WIDTH+MARGIN_MIN)) );

	var marginH = MARGIN_MIN
	var marginV = marginH

	if( items_per_line <= bucketElts.size() ) {
		marginH = getMargin(items_per_line);
		if(marginH < MARGIN_MIN && items_per_line > 1) { setItemsPerLine( items_per_line - 1 ); marginH = getMargin(items_per_line) }
		if(marginH<=0) {redoposition();running = false;return;}
		marginV = marginH;
		if(marginV > MARGIN_MIN*2) marginV = MARGIN_MIN*2
	}

	function redoposition(){
		setTimeout(function(){repositionBuckets(bCont,null,false)},200)
	}

	var _marginH = _margin_h = Math.floor(marginH)
	_half_margin_h = Math.floor( _margin_h / 2 );

	if(_fromDashboard) doDashboard()

	setMarginToBuckets(bucketElts)

	if(params && params.afterFinish) { (params.afterFinish).call() }

	//}
	running = false;
}
function applyMarginToBucket(elt,mLeft,mRight){
	if(smoothieRepos){
		new Effect.Morph(elt,{style:"margin-left: " + mLeft + "; margin-right:" + mRight,duration:0.4})
	} else {
		elt.style.marginLeft = mLeft
		elt.style.marginRight = mRight
	}
}
function setMarginToBuckets(buckets){
	var mRight, mLeft;
	if(_fromDashboard){
		buckets.each(function(elt,index){
			mLeft = 0;
			mRight = ( ((index+1+WN) % WN == 0) ? MARGIN_MIN : _margin_h  ) + 'px';
			applyMarginToBucket(elt,mLeft,mRight)
		})
	} else {
		if(_IE6) {
			buckets.each(function(elt,index){
				elt.style.display = 'inline' // double margin fix
				mLeft = _half_margin_h + 'px';
				mRight = ( ((index+1+ITEMS_PER_LINE) % ITEMS_PER_LINE == 0) ? MARGIN_MIN : _half_margin_h  ) + 'px';
				applyMarginToBucket(elt,mLeft,mRight)
			})
		} else {
			buckets.each(function(elt){
				mLeft = mRight = _half_margin_h + 'px';
				applyMarginToBucket(elt,mLeft,mRight)
				// new Effect.Morph( elt, { style: 'margin-left:' + _half_margin_h + 'px; margin-right:' + _half_margin_h + 'px;', duration: 0.4 } );
			})
			//elt.style.marginBottom = Math.floor(marginV / 2) - 4 + 'px'
		}
	}
	//if($('deb')) {$('deb').style.color = 'white'; $('deb').update('containerWidth: ' + TOTAL_WIDTH + ' :: itemWidth: ' + (ITEM_WIDTH+MARGIN_MIN) + ' :: items/line: ' + ITEMS_PER_LINE + ' :: marginRight: ' + Math.floor(_margin_h / 2) ) }
}
/* bucket layout */

/* filters */
var filterElements = [ [ 'header_filter_showadv' ], [ 'header_advanced_filter', 'header_filter_hideadv' ] ];

function setupFilterCookie( type ){
    if( type == 0 ){
        eraseCookie('azfilter')
    } else {
        createCookie('azfilter', type, 1000)
    }
}
function getFilterBarCookieValue(){
    if(readCookie('azfilter')!=null && readCookie('azfilter') == 1) {
 		return 1
 	}
    return 0
}
 function setupFilterBar( fromAzureus ) {
 	switchFilterType( getFilterBarCookieValue(), fromAzureus )
 }
function switchFilterType( toType, fromAzureus ) {
	setupFilterCookie( toType )
	if( filterMenu ) filterMenu.hideSortOptions();

    $A(filterElements).each(function(elt,index){
        elt.each((index==toType)?Element.show:Element.hide)
    })

	if (!inBucketBrowse)
	    $('wrapper').style.top = toType?(fromAzureus?'59px':'163px'):(fromAzureus?(inBucketBrowse?'10px':'32px'):'134px');

    if(!inBucketBrowse && typeof onHeaderResize == 'function' && _IE6 ) onHeaderResize( toType )
}

/* filters */

/* logger */

var Logger = function(){
	this.log = function( msg ){
		if(debug && $('debugg')) $('debugg').innerHTML += msg + '<br>'
	}
}
var logger = new Logger();

/* subnav */
var menusArray = {	'arrow_video':{menu:'menucats_video',tab:'tab_video'},
				'arrow_audio':{menu:'menucats_audio',tab:'tab_audio'},
				'arrow_games':{menu:'menucats_games',tab:'tab_games'},
				'arrow_chans':{menu:'menuchans',tab:'browsechans'}
			};
var _menusArray = $H(menusArray)
var dropDownMenu = new Array();
var activeMenu = null
var attributes 	= { opacity: { to: 0 } }
var MENU_DISAPPEAR_DELAY = 500
var MENU_DISAPPEAR_TIMER
var menuOverlay = null;

_menusArray.each(function(g){
	window[g.value['menu']] = false;
})
var MenuOverlay = function(id) {
	this.id = id
	this.top = 0
	this.height = 0
	this.opacity = 0.8;

	this.setup = function(){

		var bb = document.getElementsByTagName("body").item(0);
		var ov = document.createElement("div");
		ov.setAttribute('id',this.id);
		ov.style.display = 'none';
		ov.onclick = function() {
			menuManager.deactivateAll();
		}
		bb.appendChild(ov);
	}
	this.setHeight = function( height ) {
		$(this.id).style.height = parseInt( height ) + 'px'
		this.height = parseInt( height )
	}

	this.resize = (function() {
		logger.log( ':: resizing! ' )
		this.position(this.id);
	}).bind(this);

	this.position = function(topId) {
		Element.setOpacity(this.id, '0.01');
		Element.show(this.id)
		var newTop = Element.getStyle(this.id,'top') || null
		/*var viewportHeight = document.viewport.getHeight();*/
		var pageHeight = document.page.getHeight();
		var viewportOffset = parseInt($(this.id).viewportOffset().top)
		Element.hide(this.id)
		function clearPartOfViewport(top){/*needed in FF if elt not visible*/
			return (viewportOffset > 0) ? viewportOffset : Math.abs(parseInt(top+viewportOffset))
		}
		var newHeight = pageHeight - ( (newTop != null) ? ((Prototype.Browser.IE) ? viewportOffset : parseInt(newTop)) : 0 )
		this.setHeight( newHeight )
		//alert("newTop: " + newTop + " :: pageHeight: " + pageHeight + " :: viewportOffset: " + viewportOffset + " :: newHeight: " + newHeight)
	}
	this.hide = (function() {
		this.hidding = true
		Effect.Fade(this.id, {duration:0.2, afterFinish: (function(){this.hidding=false;Event.stopObserving(window,'resize',this.resize);}).bind(this)})
	}).bind(this);

	this.show = (function() {
		Effect.Appear(this.id, {duration:0.5, to:this.opacity})
		Event.observe(window,'resize', this.resize)
	}).bind(this);

	this.setup()
}

Event.observe(window,'load',function(){

	menuOverlay = new MenuOverlay( 'menuOverlay' )

	if($('arrow_video')){
		_menusArray.each(function(g){
			/* observe arrow */
			Event.observe(g.key ,"click", function(evt){
				$(g.key).blur();
				//if(activeMenu && activeMenu != dropDownMenu[g.value['menu']]) {activeMenu.reset();}
				if(window[g.value['menu']]){
					window[g.value['menu']] = false;
					Element.removeClassName($(g.key), 'act')
					dropDownMenu[g.value['menu']].hide();
					//menuOverlay.hide();
				} else {
					window[g.value['menu']] = true;
					Element.addClassName($(g.key), 'act')
					dropDownMenu[g.value['menu']].show();
					//menuOverlay.show();
				}
			});
			Event.observe(g.key ,"mouseout", function(){
				//window[g.value['menu']] = false;
				//MENU_DISAPPEAR_TIMER = setTimeout(function(){hideFlyMenu(g.value['menu'],g.key,g.value['tab'])},MENU_DISAPPEAR_DELAY);
				Element.removeClassName($(g.key), 'mena');
				Element.removeClassName($(g.key), 'highl');
				if(!window[g.value['menu']]) {Element.removeClassName($(g.key), 'act');Element.removeClassName($(g.value['tab']), 'act')}
			} );
			Event.observe(g.key ,"mouseover", function(){ Element.removeClassName($(g.key), 'mena'); Element.addClassName($(g.key), 'highl'); Element.addClassName($(g.value['tab']), 'act')  } );

			/* observe dropdown menu */
			Event.observe(g.value['menu'] ,"mouseover", function(){
				clearTimeout(MENU_DISAPPEAR_TIMER)
				window[g.value['menu']] = true;
				Element.addClassName($(g.key), 'act');
				Element.addClassName($(g.value['tab']), 'act') } );
			//Event.observe(g.value['menu'] ,"mouseout", function(){ window[g.value['menu']] = false;MENU_DISAPPEAR_TIMER = setTimeout(function(){	hideFlyMenu(g.value['menu'],g.key,g.value['tab'])	},MENU_DISAPPEAR_DELAY);	});

			/* observe content type tab */
			Event.observe(g.value['tab'] ,"mouseover", function(){ Element.addClassName($(g.key), 'mena') } );
			Event.observe(g.value['tab'] ,"mouseout", function(){ Element.removeClassName($(g.key), 'mena') } );

			if( $(g.value['menu']) ){
				dropDownMenu[g.value['menu']] = new DropDownMenu(g.value['menu'],g.value['tab'],g.key)
				//$('ttest').innerHTML += ' :: ' + g.value['menu'] + ' : ' + $(g.value['menu']).getHeight()
			}

		})
	}
})

/* subnav */

/* cat menus */

var menuScrollTimer = null
var MAX_TOP = 0
var MAX_BOTTOM = 0;
var DEFAULT_MENU_HEIGHT = 400;
var MENU_SCROLL_HEIGHT = 20; /*px increment*/
var MENU_SCROLL_SPEED = 20; /*ms increment*/

function menuScroll(id /* elt id */, height /* increment in px */, speed /* time in ms */) {
	var top = parseInt($(id).style.top || 0)
	MAX_BOTTOM = $(id).getHeight();

	if(top+height > MAX_TOP) {$(id).style.top='0px';return;}
	if(top+height-DEFAULT_MENU_HEIGHT < -MAX_BOTTOM) {$(id).style.top=(-MAX_BOTTOM+DEFAULT_MENU_HEIGHT)+'px';return;}

	$(id).style.top=(top+height)+'px'
	menuScrollTimer = setTimeout( function(){menuScroll(id, height, speed)}, speed)
	//$('ttest').innerHTML += ' :: MenuScroll : ' + (top+height) + ' :: '
}
var DropDownMenu = function(id /*menu id*/, tabId /*menu header id*/, arrowId /*menu header arrow id*/){
	this.menuId = id
	this.tabId = tabId
	this.arrowId = arrowId
	this.id = id = id + '_scroll'
	this.navUp = id+'_up'
	this.navDown = id+'_down'
	this.menuHeight = null
	this.visible = false;
	this.built = false
	this.disappearing = false;
	this.appearing = false;
	this.heightSet = false;
	this.positioned = false;

	menuManager.add(this)

	this.appear = function(){
		if(!this.appearing && !this.disappearing){
			this.appearing = true
			var t = this
			new Effect.BlindDown( this.menuId ,{duration:0.5,afterFinish:function(){t.build();t.appearing=false;activeMenu = t;}})
			this.visible = true
			menuManager.activate(this)
		}
	}
	this.disappear = function(){
		//Element.hide( this.menuId )
		if(!this.disappearing && this.visible && !this.appearing){
			this.disappearing = true;
			var m = $(this.menuId)
			var h = m.getHeight()
			var t = this
			//$('ttest').innerHTML += (h) + '::'
			new Effect.BlindUp( this.menuId ,{duration:0.1,afterFinish:function(){/*t.setHeight((h-2));*/t.visible = false;t.disappearing = false;}})
			//if(activeMenu == this) activeMenu = null
			menuManager.deactivate(this)
		}
	}

	this.position = function(){
		/*position menu*/
		/*
		var t = this; setTimeout( function(){ t.position2() } , 2000 )
		*/
		var tabPos = Element.cumulativeOffset( $(this.tabId) )
		//alert("tab["+this.tabId+"]::(left:"+tabPos[0]+"px, top:"+tabPos[1]+"px)")
		$(this.menuId).style.left = tabPos[0] + 'px'
		$(this.menuId).style.top = tabPos[1] + $(this.tabId).getHeight() + 'px';

	}
	this.position2 = function(){
		/*position menu*/
		var tabPos = Element.cumulativeOffset( $(this.tabId) )
		alert("tab["+this.tabId+"]::(left:"+tabPos[0]+"px, top:"+tabPos[1]+"px)")
		$(this.menuId).style.left = tabPos[0] + 'px'
		$(this.menuId).style.top = tabPos[1] + $(this.tabId).getHeight() + 'px';
	}
	/*
	this.setHeight = function(h){
		if(!this.heightSet) {
			//$('ttest').innerHTML += ' :: Setting height to ' + h + ' '
			$(this.menuId).style.height = h + 'px'
			this.heightSet = true
		}
	}
	*/
	this.build = function(){
		if(!this.built){
			/*reduce height if scroll not necessary*/
			var id = this.id
			if(this.menuHeight == null) this.menuHeight = parseInt( $(this.id).getHeight() )

			if(this.menuHeight < DEFAULT_MENU_HEIGHT) {
				var conts = ($(this.id)).ancestors()
				conts[0].style.height = this.menuHeight + 'px'
				Element.addClassName(this.navUp, 'off')
				Element.addClassName(this.navDown, 'off')
			} else {
				Event.observe(this.navUp, 'mouseover', function(){menuScroll(id,MENU_SCROLL_HEIGHT, MENU_SCROLL_SPEED)})
				Event.observe(this.navUp, 'mouseout', function(){clearTimeout( menuScrollTimer )})
				Event.observe(this.navDown, 'mouseover', function(){menuScroll(id,(-MENU_SCROLL_HEIGHT), MENU_SCROLL_SPEED)})
				Event.observe(this.navDown, 'mouseout', function(){clearTimeout( menuScrollTimer )})
			}
			this.built = true
		}
	}

	this.resetTab = function(){
		Element.removeClassName($(this.arrowId), 'highl');
		Element.removeClassName($(this.arrowId), 'act');
		Element.removeClassName($(this.tabId), 'act')
		Element.removeClassName($(this.arrowId), 'mena');
	}

	this.reset = function(){
		window[this.menuId] = false;
		this.resetTab();
		this.hide()
	}

	this.show = function() {
		if(window[this.menuId]){
			//flashthingie && IE6
			if( !this.positioned ) {
				this.position();
				this.positioned = true;
			}
			this.appear();
		}
		return false;
	}

	this.hide = function() {
		if(!window[this.menuId]){
			//flashthingie && IE6
			dropDownMenu[this.menuId].disappear();
			Element.removeClassName($(this.arrowId), 'act');
			if(!Element.hasClassName($(this.arrowId), 'highl')) Element.removeClassName($(this.tabId), 'act')
		}
		return false;
	}

	//this.position()
}
/* cat menus */

function toggleSelectBoxes( bool ){
	var selects = document.getElementsByTagName("select");
	for (i = 0; i != selects.length; i++) {
		selects[i].style.visibility = bool ? "visible" : "hidden";
	}
}

/* hack to fix broken ads - for times when the Java component wants to serve
   an ad, but TribalFusion give us lame JavaScript that fails in Safari */
if ( Prototype.Browser.WebKit ) {
	Event.observe( window, 'load', function() {
		if ( $('adSkyScraper') ) {
			// bucket browse
			var dim = $( $('adSkyScraper').getElementsByTagName('center')[0] ).getDimensions();

			if ( dim.height < 50 ) {
				// aaargh! no ad!
				$('adSkyScraper').remove();

				if($('fcont') != null) { bCont = 'fcont'; };
				$(bCont).style.width = ( document.viewport.getWidth() - 22 ) + "px";
				repositionBuckets(bCont , {afterFinish: function(){if($('ch')) setTimeout( adjustHeader , 1 );}})
			}
		}
		if ( $('skyscraper') ) {
			// CDP, all channels, all categories
			var dim = $( $('skyscraper').getElementsByTagName('center')[0] ).getDimensions();

			if ( dim.height < 10 ) {
				$('skyscraper').remove();
				$$( '#pri', '#ter', '#comments', '#comment_box', '#all_categories #video', '#all_categories #audio', '#all_categories #games', '#all_channels .contseg', '.channelgroup' ).each( function(el){ el.style.marginRight = '0'; } )
			}
		}
	} );
}

/* delay buckets appearance */
//setTimeout( displayBuckets, 5000)
//Event.observe(window, 'load',
document.observe( "dom:loaded",	displayBuckets )
function displayBuckets(){
	if($('cloading') && $('cloading').visible()) {
		Element.hide('cloading');
	}
	var bCont = 'list_view'
	if($('fcont')) bCont = 'fcont'
	if( $(bCont) && $(bCont).style.visibility=='hidden') $(bCont).style.visibility='visible';
}

/* mature filter toggle */

var MenuManager = function(){
	this.l = new Array()
	this.activel = new Array()
	this.list = $A( this.l )
	this.activelist = $A( this.activel )
	this.menus = new Array()
	this.activeMenus = new Array()

	this.activating = false;
	this.deactivating = false;

	this.add = function( menu ){
		var arr = this.list
		arr.push( menu.id )
		this.list = arr
		this.menus[ menu.id ] = menu

	}
	this.remove = function( menu ){
		var previousList = this.list
		this.list = previousList.without( menu.id )
		this.menus[ menu.id ] = null
	}
	this.addToActive = function( menu ){
		var arr = this.activelist
		arr.push( menu.id )
		this.activelist = arr
		this.activeMenus[ menu.id ] = menu

	}
	this.removeFromActive = function( menu ){
		var previousList = this.activelist
		this.activelist = previousList.without( menu.id )
		this.activeMenus[ menu.id ] = null
	}
	this.getMenus = function(){
		return this.menus
	}
	this.getMenu = function( menuId ){
		return this.menus[ menuId ]
	}
	this.activate = function( menu ){
		var t = this;
		var n = menu;
		if( this.deactivating ) {
			setTimeout( function(){t.activate( n ) }, 10)
		} else {
			this.activating = true;
			logger.log('activating ' + menu.id + ' :: activeListSize= ' + (this.activelist).size())
			if((this.activelist).size() > 0){
				(this.activelist).each(function(menuId){
					var m = t.getMenu(menuId)
					m.reset()
				})
			} else {
				var iid = menu.tabId
				menuOverlay.position( iid ? iid : menu.id)
				this.toggleWeirdness( false )
				menuOverlay.show()
			}
			this.addToActive( menu )
			logger.log('activating ' + menu.id + ' :: activeListSize= ' + (this.activelist).size())
			this.activating = false;
		}
	}
	this.deactivate = function( menu ){
		var t = this;
		var n = menu;
		if( this.activating ) {
			setTimeout( function(){ t.deactivate( n ) }, 10)
		} else {
			this.deactivating = true;
			logger.log('deactivating ' + menu.id + ' :: activeListSize= ' + (this.activelist).size())
			this.removeFromActive( menu )
			if((this.activelist).size() == 0){
				menuOverlay.hide()
				this.toggleWeirdness( true )
			}
			logger.log('deactivating ' + menu.id + ' :: activeListSize= ' + (this.activelist).size())
			this.deactivating = false;
		}
	}
	this.deactivateAll = function(){
		var t = this;
		if((this.activelist).size() > 0){
			(this.activelist).each(function(menuId){
				var men = t.getMenu(menuId)
				//t.deactivate( men )
				men.reset()
			})
		}
	}
	this.toggleWeirdness = function( bool ){
		toggleFlashness( bool )
	}
}
var menuManager = new MenuManager();

function toggleFlashness( bool ){
	for(var i=0;i<flash.replaceEltsArray.size()-1;i+=2){
		VUZE.log( " // checking : " + flash.replaceEltsArray[i]  + "("+$(flash.replaceEltsArray[i])+")"+ " and " + flash.replaceEltsArray[i+1] + "("+$(flash.replaceEltsArray[i+1])+")"+ " ");
		flash.toggle(flash.replaceEltsArray[i], flash.replaceEltsArray[i+1], bool);
	}
	if(_IE6) toggleSelectBoxes( bool )
	VUZE.log( " // toggling flashness to " + bool)
}

var ChoicePicker = function( id, contId, params ){
	this.id = id
	this.containerId = contId
	this.tabId = contId
	this.visible = false;
	menuManager.add(this)
    //removing previously used cookie
    eraseCookie('vuze.tb.mature')

	this.toggle = function(){
		//alert( 'toggling: ' + this.id )
		if($(this.id).visible()){
			//alert( 'hide' )
			this.hide();
		} else {
			//alert( 'show' )
			this.show();
		}
	}
	this.show = function(){
		this.position();
		//if(activeMenu) activeMenu.reset();

		Effect.BlindDown(this.id,{duration:0.2})
		this.visible = true;
		menuManager.activate( this )
	}
	this.hide = function(){
		Effect.BlindUp(this.id,{duration:0.1})
		//menuOverlay.hide()
		this.visible = false;
		menuManager.deactivate(this)
	}
	this.position = function(){
		var tabPos = Element.cumulativeOffset( $(this.containerId) )
		$(id).style.top = tabPos[1] + 'px';
		$(id).style.left = (tabPos[0] + $(this.containerId).getWidth() - $(id).getWidth() - 5)+ 'px'
	}
	this.reset = function(){
		this.hide()
		/*
		Effect.BlindUp(this.id,{duration:0.1})
		this.visible = false;
		//menuManager.remove(this)
		*/
	}
	this.createThoughtBubble = function(){
	}

	if(params != null && params.tb != null){
		this.tbId = params.tb.id
		this.msg = params.tb.msg ? params.tb.msg : 'booh'
		var t = this
		//Event.observe(window, 'load', function(){ setTimeout( function(){ t.createThoughtBubble(); delete t}, 1000 ) })
		this.createThoughtBubble()
	}
}
var maturePicker;

function createMaturePicker(){
    // TODO check timing still (if js repositioning)
//	if(bucketElts.size()>0 && $(bCont) && !$('ppb') && (_margin_h == null || _margin_h < 0)){
//		setTimeout( createMaturePicker , 250 )
//	} else {
		maturePicker = new ChoicePicker('maturepicker', 'lmature')
//	}
}
Event.observe( window, 'load', function(){
	setTimeout( createMaturePicker , 1000 )
})

/* pagination input field selection */
Event.observe(document, 'dom:loaded', function(){
	var n = $$('.gtppi'); //document.getElementsByClassName('gtppi')
	if(n.size() > 0) {
		n.each( function(m) {
			Event.observe(m, 'focus', function(){
				setTimeout(function(){m.select()},100);
			})
		})
	}
})

/*recommendations*/
var more_rec = $A()
Event.observe(document, 'dom:loaded', function(){
	if( $('more_rec') ) {
		more_rec = $$('#more_rec .prevbuck'); //document.getElementsByClassName('prevbuck', $('more_rec'));
		//contentBuckets = bucketElts.clone()
		if(more_rec.size() >= 1 ) {
			$R(0,more_rec.size()-1).each(function(){bucketElts.pop()})
		}
	} else {
		//(document.getElementsByClassName('discard')).invoke('hide')
	}
})
function discard(_hash){
	var hash = _hash
	recommend_rpc('discard',hash)
	if( more_rec && more_rec.size() >= 1 ) {
		Effect.Fade( $('buck_' + hash),
			{	duration:0.4,
				afterFinish: function(){ showRecommendation( more_rec[0] ); setMarginToBuckets(bucketElts) }
			} )
	} else {
		/* get more recommendations! */
		window.location.reload( true )
	}
	function showRecommendation( elt ){
		Element.hide(elt)
		$('fcont').insertBefore( elt, $('end') )
		Effect.Appear( elt )
		bucketElts = bucketElts.without( $('buck_' + hash) );
		bucketElts.push( more_rec[0] );
		$('buck_' + hash).remove();
		more_rec.shift()
	}
}

/* no results bubble */
function noContent(){
	//return;
	VUZE.log( "<br/>noContent...")
	if( $('sortf').visible() ) {
		VUZE.log( "<br/>noContent :: GoBubble...")
		var vtb2 = new VUZE.ThoughtBubble.create({
			id:'adv',
			s:{w:350,h:100},
			source: $('vuze.tb.nocontent'),
			arrow: {offset: 90}
		});
		vtb2.render({
			id:'adv',
			condition: function(){return !readCookie('vuze.tb.nocontent') },
			onclose: function(){createCookie('vuze.tb.nocontent', 1, 150);},
			duration: 8
		});
	}

}

/* flash overlapping */
var flash = {
		isNeedToggling: null,
		replaceElts: $A(),
		replaceEltsArray: $A(),
		headerOverlappingElts: $A(),

		needsToggling: function(){
			if(this.isNeedToggling == null) {
				this.isNeedToggling = ( (_browser == "Safari" && _version != "an unknown version" && _version < 500) || // only safari versions < 3 need this
								(_OS == "Mac" && _browser == "Firefox") );
			}
			return this.isNeedToggling
		},

		checkOverlappingOnHeader: function(){
			if(this.needsToggling()){
				setTimeout( this.checkHeaderOverlapping.bind(this) , 500 )
			}
		},
		checkHeaderOverlapping: function(){
			this.headerOverlappingElts.each(function(elt){
				//var flashElt = elt[0];
				//var headerElt = elt[1];
				var flashOverlaps = elt[4];
				//var changed = elt[5]

				var v = elt[0].viewportOffset()[1];
				var h = elt[1].getHeight()

				changed = false

				Element.hide( elt[1] );

				if( (v < h) == !flashOverlaps ) { flashOverlaps = !flashOverlaps; changed = true; }
				if(changed) {flash.toggle( elt[2], elt[3], !flashOverlaps );elt[4] = flashOverlaps;}
				//elt[5] = changed;

				Element.show( elt[1] );
			})
			setTimeout( this.checkHeaderOverlapping.bind(this) , 500 )
		},
		hidden: 0,
		toggle: function( flashElt, flashReplaceElt, show ){
			if( this.needsToggling() && $(flashReplaceElt) && $(flashElt) ) {
				VUZE.log( " // toggling flash to " + show)
				this.hidden = this.hidden + (show? (-1):1)
				if((this.hidden == 0 && show) || (this.hidden == 1 && !show)) {
					logger.log( 'flash.toggle:: ' + (show ? 'show' : 'hide') )
					if( show ) {
						Element.hide(flashReplaceElt)
						Element.show(flashElt)
					} else {
						Element.hide(flashElt)
						Element.show(flashReplaceElt)
					}
				}
			}
		},
		missingDisplayed:false,
		missing: function(id){
			if(!this.missingDisplayed){
				setTimeout(Effect.Appear(id),2000)
				this.missingDisplayed = true
			}
		}
}

/* */
function buttonEffect(id) {
	if($(id) /*&& !_IE6*/){
		Effect.Appear(id, {from:0.2,duration:0.5, transition:Effect.Transitions.EaseFrom})
	}
}

/* GA */
var GATracker = Class.create({
    initialize: function( prefix, params ){
        params = params || {}
        this.prefix = prefix ? prefix : "";
        this.debug = params.debug
        this.args = {}
        this.GADisabled = params.GADisabled
        this.remTracker = params.remTracker || remTracker
        this.referrerTrackingEnabled = false
    },
    getPrefix: function(){
        return this.prefix
    },
    setArgs: function( _args ){
        this.args = _args
    },
    getArgs: function(){
        return this.args
    },
    track: function( url, _args ){
        var args = this.args
        if( _args ) {
            $A(Object.keys(_args)).each(function(key){
                args[key] = _args[key]
            })
        }
//        Object.extend(args, _args)
        if( this.debug ){
            this.fake( url, args )
        } else {
            if( this.validateGASetup() ) {
                pageTracker._trackPageview( this.getPrefix() + url );
                this.trackReferrer.bind(this)(args)
            }
            if(this.remTrackingEnabled && this.remTracker) this.remTracker.track({"event": this.getPrefix() + url}, args)
        }
    },
    fake: function( url, args ){
        ClientLogger.log(this.getPrefix() + url)
        ClientLogger.log("with: " + JSONUtils.toJSONString(args))
    },
    validateGASetup: function(){
        return !this.GADisabled && typeof pageTracker != 'undefined' && typeof pageTracker._trackPageview == 'function'
    },
    enableReferrerTracking: function(referrerTracker){
        this.referrerTrackingEnabled = true
        this.referrerTracker = referrerTracker
    },
    trackReferrer: function(args){
        args = args || {}
        if( this.referrerTrackingEnabled && this.referrerTracker ){
            this.referrerTracker.track.bind(this.referrerTracker,{action:document.referrer,label: args.action})()
        }
        if(typeof log4js != "undefined" ) {
            log4js.info("trackReferrer: " +this.referrerPage + " Referrers" + " :: args: "
                + JSONUtils.toJSONString(args) + " :: this.referrerTrackingEnabled: "
                + this.referrerTrackingEnabled + " :: referrer: " + document.referrer
                + " :: args.action: " + args.action)
        }
    }
})
var GA = new GATracker()
var remTracker
var remEventTracker
if(typeof RemoteTracker != "undefined") remTracker = new RemoteTracker( "universal", "track" )
if(typeof RemoteTracker != "undefined") remEventTracker = new RemoteTracker( "event", "track" )

var UpdatableGATracker = Class.create(GATracker,{
    initialize: function($super, prefix, params){
        $super(prefix, params)
        this.update = params ? params.update : function(){}
    },
    track: function($super, url, _args){
        this.update.bind(this)()
        $super(url, _args)
    }
})

var GARemTracker = Class.create(GATracker,{
    initialize: function($super, prefix, params){
        $super(prefix, params)
        this.remTackingEnabled = true
    }
})

var UpdatableGARemTracker = Class.create(UpdatableGATracker,{
    initialize: function($super, prefix, params){
        $super(prefix, params)
        this.remTackingEnabled = true
    }
})

var GAEventTracker = Class.create(GATracker,{
    initialize: function($super,prefix,params){
        params = params || {}
        $super(prefix,params)
        this.category = prefix
        this.remTrackingEnabled = true
        if(params.remTrackingDisabled) this.remTrackingEnabled = false
        this.remEventTracker = params.remEventTracker || remEventTracker
    },
    track: function( args ){
        if( this.debug ){
            ClientLogger.log( JSONUtils.toJSONString(args) )
        } else {
            if( this.validateGASetup() ) {
                pageTracker._trackEvent( this.category, args.action, args.label, args.value );
                this.trackReferrer.bind(this)(args)
            }
            if(this.remTrackingEnabled && this.remEventTracker) {
                if(!args.action) return
                this.remEventTracker.track({
                    category: this.category,
                    action: args.action,
                    label: args.label,
                    value: args.value
                })
            }
            //log
            if(typeof log4js != "undefined" ) {
                log4js.info("GAEventTracker:: "+this.category+": { action: " + args.action + ", label: " + args.label + ", value: " + args.value + "}")
            }
        }
    },
    validateGASetup: function(){
        return !this.GADisabled && typeof pageTracker != 'undefined' && typeof pageTracker._trackEvent == 'function'
    }
})
var installerTracker = new GAEventTracker("InstallerDownloads");

/* form fields highlight */
function highlightCurrentField() {
	$$('#wrapper form').each( function(f) {
		f.getInputs('text','password')
//                    .invoke("observe", "focus", "setStyle", {backgroundColor: '#fff'})
//                    .invoke("observe", "blur", "setStyle", {backgroundColor: '#ddd'})
                .each( function(field) {
                    field.observe("focus", "setStyle", {backgroundColor: '#fff'}).observe("blur", "setStyle", {backgroundColor: '#ddd'})
		})
	})
}

// click handler for "you need to install Flash!" links
function flashInstallPopup() {
	if ( Prototype.Browser.IE ) {
		// on Windows, make sure users get the ActiveX version
		// even if their default browser is (e.g.) Firefox
		try {
			document.body.innerHTML += "<object codebase=\"http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=9,0,115,0\" classid=\"clsid:d27cdb6e-ae6d-11cf-96b8-444553540000\"></object>";
		} catch (e) {
			openUrl( 'http://www.adobe.com/shockwave/download/index.cgi?P1_Prod_Version=ShockwaveFlash&P2_Platform=Win32&P3_Browser_Version=MSIE' );
		}
		return false;
	} else {
		// Flash installs systemwide on Mac + Linux
		openUrl( 'http://www.adobe.com/go/gntray_dl_getflashplayer' );
		return false;
	}
}

// On browse pages, create a click handler to show the menu
// with sort options (what's hot, what's new, etc.)
var HeaderMenu = Class.create({
    initialize: function(menuId, headerOptionId){
        this.id = menuId //'header_switch_filter',
        this.headerId = headerOptionId //'header_filter_option',
        this.activated = false

        Event.observe( this.headerId, 'click', this.toggleSortOptions.bind(this) );
		Event.observe( this.id, 'mouseover', this.activate.bind(this) );
		Event.observe( this.id, 'mouseout', this.deactivate.bind(this) );
    },
	log: function(msg){
//		$('debugHM').innerHTML += " / " + msg
	},
	toggleSortOptions: function(ev) {
		if ( ev ) { Event.stop(ev); }
//		Effect.toggle( this.id, 'slide', { duration: 0.2 } );
		if( $(this.id).visible() ){
			this.hideSortOptions()
		} else {
			this.position()
			this.showSortOptions()

		}
	},
	position: function(){
		$( this.id ).setStyle({ left: $( this.headerId ).cumulativeOffset()[0] + 'px' })
	},
	showSortOptions: function(ev){
//		this.log('showing!')
		new Effect.BlindDown( this.id, { duration: 0.2 } );
	},
	hideSortOptions: function(ev){
//		this.log('hiding!')
		new Effect.BlindUp( this.id, { duration: 0.2 } );
	},
	activate: function(ev){
		if( this.activated ) return
		this.log('activate')
		this.activated = true
		clearTimeout( this.timeout )
	},
	deactivate: function(ev){
		if( ! this.activated ) return
		this.log('DEactivate')
		this.activated = false
		this.timeout = setTimeout( this.hideSortOptions.bind(this,ev), 400)
	}
})
var filterMenu
var durationMenu
Event.observe( document, 'dom:loaded', function() {
	if ( $('header_filter_option') ) {
        filterMenu = new HeaderMenu('header_switch_filter','header_filter_option')
	}
    if ( $('header_filter_option_duration') ) {
        durationMenu = new HeaderMenu('header_switch_filter_duration','header_filter_option_duration')
	}
} );

var selectedElement = {
    args: null,
    result: null,
//    hash: null,
//    'download-url':null,
//    'display-name':null,
//    'thumbnail.url': null,
//    referer:null,
//    'can-play':null,
//    'is-vuze-content':null,
//    'download-referer':null,
//    'download-cookies':null,
//    'download-header':null,
//    'subscription-id':null,
//    'subscription-result-id':null,
    log: function( msg ){
//        alert( msg )
    },
    set: function( _args ){
         selectedElement.log('SE set')
        selectedElement.args = _args
//        $A(Object.keys(_args)).each(function(key){
//          selectedElement[key] = _args[key]
//        })
      selectedElement.select()
    },
    select: function(){
        selectedElement.log('SE select')
        if( selectedElement.args ) {
          var params = selectedElement.args
//          alert( JSONUtils.toJSONString(params) )
          params.callback = "selectedElement.get"
          sendMessage('display','set-selected-content',params)
        }
    },
    get: function( playOrDownload ){
        selectedElement.log('SE get')
        var play = playOrDownload == "play"
        if( selectedElement.args ) {
            selectedElement.log('booh')
          if( (typeof torrentUrlLoader != "undefined") && selectedElement.result ) {
              selectedElement.log('search')
              torrentUrlLoader.get(selectedElement.result, play)
          } else {
              selectedElement.log('cdp')
              selectedElement.log('hash: ' + selectedElement.args["torrent-hash"])
              deliver(selectedElement.args["torrent-hash"], play, true)
          }
        }
    },
    clear: function(args){
        selectedElement.log('SE clear')
        selectedElement.args = null
        selectedElement.result = null
        var params = args || {}
        sendMessage('display','set-selected-content',params)
    },
    setKey: function(key, value){
        selectedElement.key = value
    }
}
if( typeof az != 'undefined' ) {
    if ( typeof az.msg != 'undefined' ) az.msg.listen('browser', 'shown', selectedElement.select.bind(selectedElement) )
}

var ClientLogger = {
    LEVELS: {INFO: "info", WARN: "warn", ERROR: "error"},
    log: function(msg, name, level){
        var logName = 'WP'
        if(!level) level = ClientLogger.LEVELS.INFO
        if(name) logName = logName + '_' + name

        sendMessage('config', 'log', { 'log-name' : logName, 'text' : '[' + level + '] ' + msg });
    }
}

function onSubmitValidator( formId, inputId, DEFAULT_SEARCH_QUERY ){

    if( $(formId) && $(inputId) ){
        if($F(inputId)!='' && $F(inputId)!=DEFAULT_SEARCH_QUERY){
            return true
        }
    }
    return false
}

function refresh(){
    var location = window.location.href
    var index = window.location.href.indexOf('embed=true')
    if(index>-1){
        window.location.href = location.substring(0, index);
    } else {
        window.location.reload()
    }
}

var ClientApp = Class.create({
    initialize: function(){
        resetSequence();
    },
    popup: function(url, opts) {
        opts = opts || {}
        if (!url.match(/^http:/))
		url = "http://" + window.location.host + url;
        resetSequence();
        sendMessage("lightbox-browser", "open-url",
            {   url:url,
                width: opts.width || 560,
                height: opts.height || 300,
                callback: opts.callback || null
            });
    },
    gotoLibrary: function() {
	this.switchToTab("library")
    },

    gotoUrl: function(url,/*optional*/target,/*optional*/sourceRef) {
	if (!url.match(/^http:/))
		url = "http://" + window.location.host + url;
	resetSequence();
	sendMessage("display", "open-url", {url:url, target:target||null, "source-ref": sourceRef||null});
    },
    openUrl: function(url) {
	if (!url.match(/^http:/))
		url = "http://" + window.location.host + url;
	resetSequence();
	sendMessage("display", "open-url", {url:url});
    },
    switchToTab: function(tab, sourceRef){
        resetSequence();
        sendMessage("display", "switch-to-tab", {target:tab, "source-ref": sourceRef?sourceRef:null});
    }
})
var clientApp = new ClientApp()

var WebBrowser = Class.create({
    initialize: function(){

    },
    signUp: function(networkId, elt, assetHash, playState, fromAzureus, opts){
        var minVersion = "4.0.0.5"
        var successCallBack = (contentData['h_'+assetHash] && contentData['h_'+assetHash].needsMembership) ?
                this.gotoCDP.bind(this, networkId, elt, assetHash, playState, fromAzureus, opts) :
                this.deliverTorrentLink.bind(this, elt, assetHash, playState, fromAzureus, opts)
        var failureCallBack = this.popUpAppropriatePage.bind(this, elt, assetHash, playState, fromAzureus, opts)

        sendMessageFromExternalBrowser("display", "is-version-ge", {"id":"client","version": minVersion}, successCallBack, failureCallBack)
    },
    simpleSignUp: function(signUpUrl, networkId, sourceRef){
        var minVersion = "4.0.0.5"
        var successCallBack = this.gotoClientUrl.bind(this, signUpUrl, networkId ? ('ContentNetwork.' + networkId) : null, sourceRef)
        var failureCallBack = this.popUpAppropriatePage.bind(this)

        sendMessageFromExternalBrowser("display", "is-version-ge", {"id":"client","version": minVersion}, successCallBack, failureCallBack)
    },
    deliverTorrentLink: function(elt, assetHash, playState, fromAzureus, opts){
        deliver(assetHash, playState, fromAzureus, opts);
    },
    gotoCDP: function(networkId, elt, assetHash, playState, fromAzureus, opts){
        var url = contentData['h_'+assetHash].detailsURL
        var target = networkId ? ('ContentNetwork.' + networkId) : null
        this.gotoClientUrl(url, target, "downloadbutton")
    },
    popUpAppropriatePage: function(elt, assetHash, playState, fromAzureus, opts){
        detectAzureus(this.popUpUpgradePage.bind( this, elt, assetHash, playState, fromAzureus, opts), this.popUpDownloadPage.bind( this, elt, assetHash, playState, fromAzureus, opts))
    },
    popUpUpgradePage: function(elt, assetHash, playState, fromAzureus, opts){
        //send upgrade cmd to client as well (works as of 3.0.5.3)
        this.checkForClientUpdates()
        //go to upgrade page
        var location = "/upgradeapp/" + (assetHash ? assetHash : "");
        setTimeout( function(){window.location.href = location}, 50 )
    },
    popUpDownloadPage: function(elt, assetHash, playState, fromAzureus, opts){
        var location = (elt && elt.href) ? elt.href : ("/downloadapp/" + (assetHash ? assetHash : ""));
        window.location.href = location
    },
    gotoClientUrl: function(url, target, sourceRef){
        sendMessageFromExternalBrowser('display','open-url', { url: url, target: target||'browse', "source-ref": (sourceRef ? "web-" + sourceRef : null) }, null, null );
    },
    checkForClientUpdates: function(){
        sendMessageFromExternalBrowser('config','check-for-updates')
    },
    getContent: function(content, fromAzureus, playState, opts){
        var success = (function(content, fromAzureus) {
            if ( !content.hasRules || content.noPrice || ( content.freeScreener && !content.hasDrm ) ) {
                loadOrAlert(content.hash, content.platformURL );
            } else {
                if ( content.freeScreener ) {
                    content.setFFS( true );
                    setMagnet(content.hash);
                    webBrowser.gotoClientUrl(content.detailsURL, null, playState ? content.playNowKey : content.downloadKey);
                }
            }
        }).curry(content,fromAzureus)
        var failure = (opts&&opts.failure) ? opts.failure : this.popUpDownloadPage.bind(this, null, content.hash, null, fromAzureus, null)
        detectAzureus(success, failure)
    }
})
var webBrowser = new WebBrowser()


function setupBrowseBy(){
    $("sortby")
        .observe("mouseover",   function(){this.addClassName("hover")})
        .observe("mouseout",    function(){this.removeClassName("hover")})
}
