/*********** A NATIVE GetElementsByClassName FUNCTION *****************
*	Developed by Robert Nyman, http://www.robertnyman.com
*	Code/licensing: http://code.google.com/p/getelementsbyclassname/
**********************************************************************/
var getElementsByClassName=function(className,tag,elm){if(document.getElementsByClassName){getElementsByClassName=function(className,tag,elm){elm=elm||document;var elements=elm.getElementsByClassName(className),nodeName=(tag)?new RegExp("\\b"+tag+"\\b","i"):null,returnElements=[],current;for(var i=0,il=elements.length;i<il;i+=1){current=elements[i];if(!nodeName||nodeName.test(current.nodeName)){returnElements.push(current);}}
return returnElements;};}
else if(document.evaluate){getElementsByClassName=function(className,tag,elm){tag=tag||"*";elm=elm||document;var classes=className.split(" "),classesToCheck="",xhtmlNamespace="http://www.w3.org/1999/xhtml",namespaceResolver=(document.documentElement.namespaceURI===xhtmlNamespace)?xhtmlNamespace:null,returnElements=[],elements,node;for(var j=0,jl=classes.length;j<jl;j+=1){classesToCheck+="[contains(concat(' ', @class, ' '), ' "+classes[j]+" ')]";}
try{elements=document.evaluate(".//"+tag+classesToCheck,elm,namespaceResolver,0,null);}
catch(e){elements=document.evaluate(".//"+tag+classesToCheck,elm,null,0,null);}
while((node=elements.iterateNext())){returnElements.push(node);}
return returnElements;};}
else{getElementsByClassName=function(className,tag,elm){tag=tag||"*";elm=elm||document;var classes=className.split(" "),classesToCheck=[],elements=(tag==="*"&&elm.all)?elm.all:elm.getElementsByTagName(tag),current,returnElements=[],match;for(var k=0,kl=classes.length;k<kl;k+=1){classesToCheck.push(new RegExp("(^|\\s)"+classes[k]+"(\\s|$)"));}
for(var l=0,ll=elements.length;l<ll;l+=1){current=elements[l];match=false;for(var m=0,ml=classesToCheck.length;m<ml;m+=1){match=classesToCheck[m].test(current.className);if(!match){break;}}
if(match){returnElements.push(current);}}
return returnElements;};}
return getElementsByClassName(className,tag,elm);};

/*********** FX.JS *******************/
eval(function(p,a,c,k,e,r){e=function(c){return(c<a?'':e(parseInt(c/a)))+((c=c%a)>35?String.fromCharCode(c+29):c.toString(36))};if(!''.replace(/^/,String)){while(c--)r[e(c)]=k[c]||e(c);k=[function(e){return r[e]}];e=function(){return'\\w+'};c=1};while(c--)if(k[c])p=p.replace(new RegExp('\\b'+e(c)+'\\b','g'),k[c]);return p}('q $1z(g){7(g.19&&g.19==1)8 h=g;t 7(1A(g).1a(/^#(\\w+)/i)){8 h=1B.1C(L.$1+\'\');7(!h)9 R}t 9 R;7(X(h.6)!=\'Y\'&&h.6){h.6.S();9 h};h.1D=0.1;h.6={};h.6.4=[];h.6.D=0;7(X(h.M)!=\'Y\')1b{1c h.M}1d(1e){h.M=R}8 k={\'1f|1g|1E|1F|1h|1i|1G|1H|1I|1j|1k\':\'1J\',\'1K\':\'1L\',\'F\':\'\'};8 l=!!1M.1N.1a(/1O/1P);8 m={1l:T,I:5,E:\'\'};8 n={F:q(a,b){a=u(a);7(A(a)){7(l){8 c=(U L(\'1m\\\\s*\\\\(F\\\\s*=\\\\s*(\\\\d+)\\\\)\')).Z(h.v.1n+\'\');7(c)9 u(c[1]);t 9 1}t{9 10.1Q((h.v.F?1R(h.v.F):1)*T)}}t{a=10.1S(T,10.1T(0,a));7(l){h.v.1U=1;h.v.1n=\'1m(F=\'+a+\');\'}t{h.v.F=a/T}}},\'1j\':q(a,b){a=u(a);8 x=0,y=0;8 c=(U L(\'^(-?\\\\d+)[^\\\\d\\\\-]+(-?\\\\d+)\')).Z(h.v.V+\'\');7(c){x=u(c[1]);y=u(c[2])}7(A(a))9 x;t{h.v.V=a+b+\' \'+y+b}},\'1k\':q(a,b){a=u(a);8 x=0,y=0;8 c=(U L(\'^(-?\\\\d+)[^\\\\d\\\\-]+(-?\\\\d+)\')).Z(h.v.V+\'\');7(c){x=u(c[1]);y=u(c[2])}7(A(a))9 y;t{h.v.V=x+b+\' \'+a+b}}};8 o={1h:q(){9 u(h.1V)},1i:q(){9 u(h.1W)},1f:q(){8 a=0;B(8 b=h;b;b=b.1o)a+=u(b.1X);9 a},1g:q(){8 a=0;B(8 b=h;b;b=b.1o)a+=u(b.1Y);9 a}};h.1p=q(){3.6.S();9 3};h.1q=q(a,b){7(h.6.4[3.6.D].J)9 3;8 b=u(b);3.6.4[A(b)?3.6.D:b].11=a;9 3};h.1r=q(c){8 d=3.6.D;7(3.6.4[d].J)9 3;B(8 p 1s m){7(!c[p])c[p]=m[p]};7(!c.E){B(8 e 1s k)7((U L(e,\'i\').1Z(c.r))){c.E=k[e];20}};c.K=(c.K&&c.K.C)?c.K:q(){};c.N=(c.N&&c.N.C)?c.N:q(){};7(!3.6[c.r]){7(n[c.r])3.6[c.r]=n[c.r];t{8 f=3;3.6[c.r]=q(a,b){7(X(a)==\'Y\')9 u(f.v[c.r]);t f.v[c.r]=u(a)+b}}};7(A(c.G)){7(A(3.6[c.r]()))7(o[c.r])c.G=o[c.r]();t c.G=0;t c.G=3.6[c.r]()}c.12=c.G;3.6[c.r](c.G,c.E);3.6.4[d].z.21(c);9 3};h.1t=q(a,b,c){8 d=h.6.D;7(3.6.4[d].J){9 3}1u(q(){7(h.6.4[d].J)9 h;h.6.4[d].J=13;7(h.6.4[d].O>0)9 h;h.6.4[d].14=(a&&a.C)?a:q(){};h.6.4[d].1v=(c&&c.C)?c:q(){};7(!A(b))h.6.4[d].W=b;B(8 i=0;i<h.6.4[d].z.H;i++){h.6.4[d].z[i].K.C(h);h.6.P(d,i)}},h.6.4[d].11);9 3};h.1w=q(a,b){3.6.4[!A(b)?b:3.6.D].15=a;9 3};h.1x=q(a){3.6.4[!A(a)?a:3.6.D].16=13;9 3};h.1y=q(){B(8 i=0;i<3.6.4.H;i++){B(8 j=0;j<3.6.4[i].z.H;j++){8 a=3.6.4[i].z[j];7(A(a.12))3.6[a.r](\'\',\'\');t 3.6[a.r](a.12,a.E)}}8 b=[\'6\',\'1q\',\'1r\',\'1p\',\'1t\',\'1w\',\'1x\',\'1y\'];B(8 i=0;i<b.H;i++)1b{1c 3[b[i]]}1d(1e){3[b[i]]=R}3.M=13};h.6.S=q(){8 a=3.4.H;3.D=a;3.4[a]={};3.4[a].W=1;3.4[a].16=17;3.4[a].z=[];3.4[a].O=0;3.4[a].Q=0;3.4[a].11=0;3.4[a].15=17;3.4[a].J=17;3.4[a].14=q(){};9 3};h.6.P=q(a,b){7(!3.4[a]||3.4[a].16||h.M)9;8 c=3.4[a].z[b];8 d=3[c.r]();7((c.I>0&&d+c.I<=c.18)||(c.I<0&&d+c.I>=c.18)){7(!3.4[a].15)3[c.r](d+c.I,c.E);8 e=3;1u(q(){7(e.P)e.P(a,b)},c.1l)}t{3[c.r](c.18,c.E);3.4[a].O++;c.N.C(h);7(3.4[a].z.H==3.4[a].O){3.4[a].O=0;3.4[a].Q++;3.4[a].1v.C(h,3.4[a].Q);7(3.4[a].Q<3.4[a].W||3.4[a].W==-1){B(8 i=0;i<3.4[a].z.H;i++){3[c.r](c.G,3.4[a].z[i].E);3.4[a].z[i].K.C(h,3.4[a].Q);3.P(a,i)}}t{3.4[a].14.C(h)}}}};h.6.S();9 h}',62,126,'|||this|sets||_fx|if|var|return|||||||||||||||||function|type||else|parseInt|style||||_queue|isNaN|for|call|_currSet|unit|opacity|from|length|step|_isrunning|onstart|RegExp|_fxTerminated|onfinish|_effectsDone|_process|_loopsDone|null|_addSet|100|new|backgroundPosition|_loops|typeof|undefined|exec|Math|_holdTime|_initial|true|_onfinal|_paused|_stoped|false|to|nodeType|match|try|delete|catch|err|left|top|width|height|backgroundx|backgroundy|delay|alpha|filter|offsetParent|fxAddSet|fxHold|fxAdd|in|fxRun|setTimeout|_onloop|fxPause|fxStop|fxReset|fx|String|document|getElementById|fxVersion|right|bottom|margin|padding|spacing|px|font|pt|navigator|userAgent|MSIE|ig|round|parseFloat|min|max|zoom|offsetWidth|offsetHeight|offsetLeft|offsetTop|test|break|push'.split('|'),0,{})) ;


/******************************************************************** JSONP PLUGIN ****/
var Jsonp = { 
	check_XSS:	false,
	api_url:	'http://api.vibeswall.com/',
	timer_ttl:	10000,
	max_try: 	3,
results:{},script:{},callback:{},timer:{},queries:{},destroying:false,req_id:0,		
get:function(opts){if(Jsonp.destroying)return false;opts.wait_lastOne=(typeof opts.wait_lastOne=='undefined'?false:opts.wait_lastOne);opts.timer_ttl=(typeof opts.timer_ttl=='undefined'?Jsonp.timer_ttl:opts.timer_ttl);opts.max_try=(typeof opts.max_try=='undefined'?Jsonp.max_try:opts.max_try);if((opts.url.match('^http://')||opts.url.match('^https://'))&&opts.url.indexOf(Jsonp.api_url)==-1&&Jsonp.check_XSS){Jsonp.growl('JSONP : XSS Attack suspected by calling<br>url : '+opts.url);return false;}
if(!opts.url.match('/')){Jsonp.growl('JSONP : url is not defined<br>url : '+opts.url);return false;}
var req_id=Jsonp.req_id;var parent=(opts.parent?opts.parent:req_id);Jsonp.queries[parent]=(opts.q?opts.q.replace(/^\s+|\s+$/g,''):req_id);if(typeof opts.onBefore=="function")opts.onBefore(Jsonp.queries[parent]);if(Jsonp.results.hasOwnProperty(Jsonp.queries[parent]+"_"+parent)&&!opts.nocache){if(typeof opts.onComplete=="function")opts.onComplete(Jsonp.queries[parent],Jsonp.results[Jsonp.queries[parent]+"_"+parent]);return;}
if(typeof Jsonp.script[parent]!="undefined"){if(!opts.wait_lastOne){try { Jsonp.script[parent].parentNode.removeChild(Jsonp.script[parent]);} catch(e) {} }else{if(!Jsonp.script[parent].errors)Jsonp.script[parent].errors=0;Jsonp.script[parent].errors++;if(Jsonp.script[parent].errors<opts.max_try)return false;Jsonp.script[parent].errors=0;Jsonp.growl('JSONP : seems to be freeze on parent='+parent+"<br>So unfreeze it !");delete(Jsonp.script[parent]);delete(Jsonp.callback[parent]);}}
var callback="c_"+req_id+"_"+new Date().getTime();if(Jsonp.timer[parent])clearTimeout(Jsonp.timer[parent]);Jsonp.timer[parent]=setTimeout(function(){if(Jsonp.results.hasOwnProperty(Jsonp.queries[parent]+"_"+parent)&&!opts.nocache)return true;if(typeof opts.onError=="function")opts.onError(parent,'timeout');try{log('error on : '+Jsonp.queries[parent]+"_"+parent);}catch(e){};},opts.timer_ttl);Jsonp.script[parent]=document.createElement('script');Jsonp.script[parent].src=opts.url+(opts.url.match("=")?"&":'?')+"callback=Jsonp|callback['"+parent+"']";Jsonp.callback[parent]=null;Jsonp.callback[parent]=function(data){if(data){Jsonp.results[Jsonp.queries[parent]+"_"+parent]=data;}
if(typeof opts.onComplete=="function")opts.onComplete(Jsonp.queries[parent],Jsonp.results[Jsonp.queries[parent]+"_"+parent]);if(Jsonp.timer[parent])clearTimeout(Jsonp.timer[parent]);if(Jsonp.script[parent]){Jsonp.script[parent].parentNode.removeChild(Jsonp.script[parent]);for(var prop in Jsonp.script[parent]){delete Jsonp.script[parent][prop];}
delete Jsonp.script[parent];}
delete Jsonp.callback[parent];};document.body.appendChild(Jsonp.script[parent]);Jsonp.req_id++;},growl:function(m){try{if(typeof jQuery.jGrowl=='function')jQuery.jGrowl(m);}
catch(e){};try{console.log(m);}catch(e){};},destroyAll:function(){Jsonp.destroying=true;Jsonp.get=function(o){return false;};try{log('Destroy All JSONP');}catch(e){};},endFlag:true};


/*********** A little DOM Framework named '_w2ajax' By Guillaume DE LA RUE *************/
var isMsie = (navigator.userAgent.match(/MSIE.(\d.\d)/i) != null ? true : false),
	rclass = /[\n\t]/g,
	rspace = /\s+/,
	rtrim = /^(\s|\u00A0)+|(\s|\u00A0)+$/g,
	count = function(myobj) { var count = 0; for (k in myobj) if (myobj.hasOwnProperty(k)) count++; return count ;} ;

_$ = function(tag) {
	return new _w2ajax(tag) ;
}

_w2ajax = function(tag) {
	if ( typeof tag == 'undefined' ) { this.length = 0 ; return false; }
	if ( typeof tag == 'object' ) {
		this[0] = tag ;
	} else if ( typeof tag == 'string' ) {
		if ( tag.indexOf('#') == 0 ) {
			this[0] =  document.getElementById(tag.replace('#', '')) ;
		//} else if ( tag.indexOf('.') == 0 ) {
			//var els = 
		} else {
			this[0] = this.create(tag) ;
		}	
	}
	
	this.length = 0 ;
	for ( var x in this ) 
		if ( 'object' == typeof this[x] && null != this[x] ) 
			this.length++;
} ;

_w2ajax.prototype.create = function(tag) {
	return document.createElement(tag) ;
} ;

_w2ajax.prototype.get = function(index) {
	if ( 'number' != typeof index ) index = 0 ;
	try { return this[index] ; } 
	catch(e) { return {length:0}; }
} ;

_w2ajax.prototype.find = function(classTxt) {
	if ( classTxt.indexOf('.') == 0 ) 
		try { return getElementsByClassName(classTxt.substr(1), false, this.get()); } catch(e) {  }
	else
		try { return this.get().getElementsByTagName(classTxt); } catch(e) { } 
} ;

_w2ajax.prototype.attr = function(attr, value) {
	if ( attr == 'class' && isMsie ) attr = 'className' ; 
	if ( typeof value != 'undefined' ) {
		this.get().setAttribute(attr, value) ;
		return this ;
	} else {
		try { return this.get().attributes.getNamedItem(attr).value ; }
		catch(e) { return ''; } ;
	}
} ;

_w2ajax.prototype.addClass = function(value) {
	var classNames = (value || "").split( rspace );
	var elem = this.get() ;
	if ( elem.nodeType === 1 ) {
		if ( !elem.className ) {
			elem.className = value;
		} else {
			var className = " " + elem.className + " ", setClass = elem.className;
			for ( var c = 0, cl = classNames.length; c < cl; c++ ) {
				if ( className.indexOf( " " + classNames[c] + " " ) < 0 ) {
					setClass += " " + classNames[c];
				}
			}
			elem.className = this.trim( setClass );
		}
	}
	return this;
} ;

_w2ajax.prototype.removeClass = function(value) {
	var classNames = (value || "").split( rspace );
	var elem = this.get() ;
	if ( elem.nodeType === 1 && elem.className ) {
		if ( value ) {
			var className = (" " + elem.className + " ").replace(rclass, " ");
			for ( var c = 0, cl = classNames.length; c < cl; c++ ) {
				className = className.replace(" " + classNames[c] + " ", " ");
			}
			elem.className = this.trim( className );
		} else {
			elem.className = "";
		}
	}
	return this;
} ;

_w2ajax.prototype.trim = function( text ) {
	return (text || "").replace( rtrim, "" );
} ;

_w2ajax.prototype.html = function(html) {
	this.get().innerHTML = html ;
	return this;
};

_w2ajax.prototype.before = function(wrapper) {
	try { wrapper.parentNode.insertBefore( this.get(), wrapper ); } 
	catch(e) { wrapper.get().parentNode.insertBefore( this.get(), wrapper.get() ); }
	return this;
} ;

_w2ajax.prototype.after = function(wrapper) {
	try { wrapper.parentNode.insertBefore( this.get(), wrapper.nextSibling ); } 
	catch(e) { wrapper.get().parentNode.insertBefore( this.get(), wrapper.get().nextSibling ); }
	return this;
} ;

_w2ajax.prototype.appendTo = function(wrapper) {
	try { wrapper.appendChild(this.get()); } catch(e) { wrapper.get().appendChild(this.get()); }
	return this;
} ;

_w2ajax.prototype.prependTo = function(wrapper) {	
	try { wrapper.insertBefore(this.get(),wrapper.childNodes[0]); } catch(e) { wrapper.get().insertBefore(this.get(),wrapper.get().childNodes[0]); }
	return this;
} ;

_w2ajax.prototype.remove = function() {
	if ( 'object' == typeof this.get() && this.get() != null ) this.get().parentNode.removeChild(this.get()) ;
} ;

_w2ajax.prototype.getStyle = function(strCssRule) {
	var strValue = "";
	var oElm = this.get() ;
	if(document.defaultView && document.defaultView.getComputedStyle){
		strValue = document.defaultView.getComputedStyle(oElm, "").getPropertyValue(strCssRule);
	} else if(oElm.currentStyle){
		strCssRule = strCssRule.replace(/\-(\w)/g, function (strMatch, p1){
			return p1.toUpperCase();
		});
		strValue = oElm.currentStyle[strCssRule];
	}
	return strValue;
}; 

_w2ajax.prototype.bind = function(event, call) {
	var oElm = this.get() ;
	oElm[event] = new Function(call);
	return this ;
}

_w2ajax.prototype.hover = function() {
	var oElm = this ;
	oElm.get().onmouseover = function() { oElm.addClass('hover'); } ;
	oElm.get().onmouseout = function() { oElm.removeClass('hover'); } ;
	return this ;
}



/******************************************************************************************************/
/******************************************************************************************************/
/******************************************************************************************************/
/******************************************************************************************************/




/********** LOAD JUKEBO WIDGET API ************/
JukeboRegistry = {
        _registry : {},
        
        set : function (uid,widget){
            this._registry[uid] = widget;
        },
        
        get : function (uid){
            return this._registry[uid];
        }
} 

JukeboCookie = {
    set : function (c_name,value,expiredays){
        var exdate=new Date();
        exdate.setDate(exdate.getDate()+expiredays);
        document.cookie=c_name+ "=" +escape(value)+
        ((expiredays==null) ? "" : ";expires="+exdate.toGMTString())+
        "; path=/";
    },
    get : function getCookie(c_name){
        if (document.cookie.length>0){
            c_start=document.cookie.indexOf(c_name + "=");
            if (c_start!=-1){
                c_start=c_start + c_name.length+1;
                c_end=document.cookie.indexOf(";",c_start);
                if (c_end==-1) c_end=document.cookie.length;
                return unescape(document.cookie.substring(c_start,c_end));
            }
        }
        return "0";
    },
    get_capping : function(){
        cook_val = parseInt(this.get("jukebo_widget_capping"));
        this.displayed_times = parseInt(cook_val==NaN || cook_val=="NaN" ? "0" : cook_val);
        //console.log('JukeboCookie::get_capping >> '+this.displayed_times);
        return this.displayed_times;
    },

    increment_capping : function(){
    	if ( 'undefined' == typeof this.displayed_times ) this.displayed_times = 0 ;
        this.displayed_times++;
        JukeboCookie.set("jukebo_widget_capping",this.displayed_times,1);
        //console.log('JukeboCookie::increment_capping >> '+this.displayed_times);
    }
}


JukeboSize = function(zone_type){
	
	// -- Throw exception if 
	if ( 'undefined' == typeof zone_type ) {
        throw("'zone_type' must be defined");
    } else if ( zone_type == 1 ) {
    	var width = 300; 
    } else if ( zone_type == 2 ) {
    	var width = 480; 
    } else {
    	throw("'zone_type' "+zone_type+" is unknwown");
    }
    
	// -- Define height
    var height = Math.max(290,3*width/4);
    
    // -- Set class vars
    this._width = width;
    this._height = height;
}
JukeboSize.prototype.getWidth = function(){ return Math.max(300,this._width); }
JukeboSize.prototype.getHeight = function(){ return Math.max(290,this._height); }

JukeboCallback = function(calling_id,data){
    var _calling_widget = JukeboRegistry.get(calling_id);
    _calling_widget.hideLoading() ;
    switch(data._jkbc){
        case "display_vid":
            _calling_widget.showVideo(data._jkbp);
            //_calling_widget.display_ad(data._jkbp);
            break;
        default:
            throw("Error in method name : " + data._jkbc);
    }
}


JukeboSearchQuery = function(term,type){
    if(term == undefined || term == null || term == "") throw("Can't query on a null term");
    if(type == undefined || type == null || type == "") type = "regular";
    switch(type){
        case "regular":
            break;
        case "favorites":
            break;
        case "playlist_by_username":
            break
        case "playlist_by_id":
            break
        case "playlist_by_artist":
            break
        default:
            throw("Invalid query type");
    }
    this._type = type;
    this._search_term = term;
}

JukeboSearchQuery.prototype.getType = function(){
    return this._type;
}

JukeboSearchQuery.prototype.getCallURL =function(){
    switch(this.getType()){
        case "regular":
            call_url = '/search/name/'+encodeURIComponent(this._search_term);
            break;
        case "favorites":
            call_url = '/favorites/user/'+encodeURIComponent(this._search_term);
            break;
        case "playlist_by_username":
            call_url = '/playlist/name/'+encodeURIComponent(this._search_term);
            break;
        case "playlist_by_id":
            call_url = '/playlist/id/'+encodeURIComponent(this._search_term);
            break;
        case "playlist_by_artist":
            call_url = '/playlist/artist/'+encodeURIComponent(this._search_term);
            break;
        default:
            throw("Invalid query type");
    }
    return call_url;
}



/******************************************************************** JUKEBO WIDGET CLASS ****/
var JukeboWidget = function(target_div,options){

	// -- If only options are sended (no container) => consider writing div with document.write
	if ( 'object' == typeof target_div && 'undefined' == typeof options ) {
		
		// => transfer options
		options = target_div ;
		
		// => create container in place of js call
		target_div = 'JukeboWidget' ;
		
		// -- Create a div inplace
		document.write('<div id="'+target_div+'"></div>') ;
	
	}
	
	// -- Control size
    if(options.size == undefined) {
        throw("JukeboSize expected");
    }
    var size = options.size
    if(!(size instanceof JukeboSize)) {
        throw("JukeboSize expected");
    }
    
    // -- Get the standard mdtk
    this._mdtk = ( 'undefined' != typeof options.mdtk ) ? options.mdtk : false;
    if ( ! this._mdtk ) throw("You have to specify your MDTK code into options. Look at www.jukebo.fr for more informations on this widget usage.");
    
    // -- Get the zone type 
    this._zone = ( 'undefined' != typeof options.zone ) ? options.zone : false;
    if ( ! this._zone ) throw("You have to specify the zone code. Look at www.jukebo.fr for more informations on this widget usage.");
    
    // -- Max num of returned results
    if(options.maxResults != undefined && options.maxResults != null){
        this._maxResults = options.maxResults;
    }else{   		
        this._maxResults = 6;
    }
    
    // -- Should autostart Ad on Load ?
    this._autostart =  ( 'boolean' == typeof options.autostart && options.autostart == true ) ? true : false ;
    this._autostart_done = false ;
    
    // -- Should launch the video in autoplay ?
    this._autoplay = ( 'boolean' == typeof options.autoplay && options.autoplay == true ) ? true : false ;
    
    // -- If specified, force the locale language config
    if(options.locale != undefined && typeof options.locale == "string"){
        this._locale = options.locale;
    }
    
    // -- Display Facebook Like feature
    this._fb_like = ( 'boolean' == typeof options.fb_like && options.fb_like == false ) ? false : true ;
    
    // -- How to display results
    if(options.searchType != undefined){
        switch(options.searchType){
            case "list": 
                this._search_type = "list";
                break;
            case "thumbs":
            default:
                this._search_type = "thumbs";
        }
    } else {
    	this._search_type = "thumbs";    
    }  
 
    // -- Detect Language
    this.getLocale() ;
    
    // -- Set private vars
    this._size = size;
    this._target_div = target_div;
    this._prod_site = 'http://www.jukebo.fr' ;
    
   	this._root_site = document.location.host == 'www.jukebo.fr.dbx7' ? 'http://'+document.location.host :  this._prod_site ;
   	this._root_site = document.location.host == 'www.jukebo.fr.local' ? 'http://'+document.location.host : this._root_site ;
   	
    //this._root_site = 'http://www.jukebo.fr.local' ;
    this._root_api = this._prod_site+"/api/widget";
    this._theme_css = this._root_site+"/css/widget_v2.css";
    this._prefix = "jkbwdgt";
    this._uid = Math.round(Math.random()*100000);
    this._videoViews = 0 ;
   
    // -- Bypass Backlink in footer
    this._backlink = ( typeof options.backlink == 'undefined' ? this._prod_site : options.backlink ) ;
    this._backlink_title = ( typeof options.backlink_title == 'undefined' ? 'More clips on : '+this._backlink : options.backlink_title ) ;
  
    // -- Scroll and active panel config
    this.scrollLeft = 0 ; 
    this.activePanel = null; 
     
    // -- Ad Config
    this._ad_startMessage = 'Video Start in XX seconds' ;
    this._ad_duration = 15000;
    this._ad_capping  = 4;
    this._ad_rotation = 2 ;
    
    // -- Registry the current transmit 
    this._transmit_div = this._prefix+"_transmit_"+this._uid;
    JukeboRegistry.set(this._transmit_div,this);
    
    // -- Load CSS on theme
    this.loadTheme() ;
    
    // -- Load Addon CSS if specified
    this._theme_addon = ( typeof options.theme != 'undefined' ? options.theme : false ) ;
    if ( this._theme_addon ) {
    	if ( this._theme_addon.indexOf('http') ==  -1 ) this._theme_addon = this._root_site+"/css/widget_v2_"+this._theme_addon+'.css'
    	this.loadTheme(this._theme_addon) ;
    }

	// -- Calculate max results and dimensions
	this._resultLineHeight_default = 45 ;
	var maxViewportH = size._height - 70 ;
	var maxResults = Math.round(maxViewportH/this._resultLineHeight_default) ;
	this._resultLineHeight = Math.round((maxViewportH-1)/maxResults) - 1 ;    
	
    // -- Draw the widget
    this.drawWidget() ;
    
    // -- If query specified in options
    if ( 'undefined' != typeof options.query ) {
    	this.execute(new JukeboSearchQuery(options.query));	
    	this.searchInput.get().value = options.query ;
    }
    
    // -- If onLoad specified in options
    if ( 'function' == typeof options.onLoad ) {
    	var onLoadFunction = options.onLoad.toString() ;
    	onLoadFunction = onLoadFunction.replace(/(this|jw|widget|jkbwidget)\./g, 'JukeboRegistry.get(\''+this._transmit_div+'\').') ;
    	onLoadFunction = '('+onLoadFunction+')()' ;    	
    	try { eval(onLoadFunction) ; } catch(e) {  }
    }
    
    // -- If options are default, display top
    if ( 'undefined' == typeof options.query && 'undefined' == typeof options.onLoad ) {
    	this.showPanel(this._prefix+'_TopClips', true) ;
    }
}


JukeboWidget.prototype.getLocale = function() {

	// -- Current language
	if ( this._locale ) {
		this.locale = this._locale ;
	} else if ( navigator ) {
	    if ( navigator.language ) {
	        this.locale = navigator.language;
	    }
	    else if ( navigator.browserLanguage ) {
	        this.locale = navigator.browserLanguage;
	    }
	    else if ( navigator.systemLanguage ) {
	        this.locale = navigator.systemLanguage;
	    }
	    else if ( navigator.userLanguage ) {
	        this.locale = navigator.userLanguage;
	    }
	}
	
	// -- Set locale managed
	this._locales = {
		'en': 		['en_en', 'usa'],
		'en_en': 	['en_en', 'usa'],
		'en_us': 	['en_en', 'usa'],
		'en_uk': 	['en_uk', 'uk'],
		'fr': 		['fr_fr', 'france'],
		'fr_fr':	['fr_fr', 'france'],
		'de':		['de_de', 'germany'],
		'de_de':	['de_de', 'germany'],
		'es':		['es_es', 'spain'],
		'es_es':	['es_es', 'spain']	
	} ;
	
	// -- Set translations
	this._translate = {
		'en_en': {
			'Go Back': 'Go back',
			'Play': 'Play',
			'Visit': 'Visit',
			'Search': 'Search'		
		},
		'fr_fr': {
			'Go Back': 'Retour',
			'Play': 'Lire',
			'Go to': 'Visiter',
			'Search': 'Rechercher'
		},
		'es_es': {
			'Go Back': 'Volver',
			'Play': 'Play',
			'Go to': 'Ir a',
			'Search': 'Buscar'
		},
		'de_de': {
			'Go Back': 'Go back',
			'Play': 'Play',
			'Visit': 'Visit',
			'Search': 'Search'
		}
	
	}
	
	// -- Fix variants and set country
	if ( this._locales[this.locale] && this._locales[this.locale].length ) {
		this.locale = this._locales[this.locale][0];
		this.country = this._locales[this.locale][1];
	} else {
		this.locale = this._locales['en'][0];
		this.country = this._locales['en'][1];
	}

}; 

/******************************************************************** LOAD WIDGET CSS THEME  ****/

JukeboWidget.prototype.loadTheme = function(themeFile) {
	
	if ( 'undefined' == typeof themeFile ) themeFile = this._theme_css ;
	setTimeout(function() {
		_$('link').attr("rel", "stylesheet").attr("href", themeFile)
		.appendTo(document.getElementsByTagName('head')[0]) ;
	}, 500) ;
	 
}



/******************************************************************** CREATE AND DRAW THE WIDGET ****/

JukeboWidget.prototype.drawWidget = function(opts) {
	
	// -- Get Widget wrapper and reset it
	this.widget = _$('#'+this._target_div) ;
	this.widget.get().style.width = this._size._width+'px' ;
	this.widget.get().style.height = this._size._height+'px' ;
	this.widget.html('');

	// -- Create menu
	this.menu = _$('div').attr('id', 'menu').addClass(this._prefix+'_menu') ;
	this.menuHided = false ;
	this.menuHideTimeOut = null ;
	this.drawMenu() ;
	
	// -- Append menu to widget
	this.menu.appendTo(this.widget) ;
	
	// -- Create viewport
	this.viewport = _$('div').addClass(this._prefix+'_viewport');
	this.viewport.get().style.width = '10000px' ;
	this.viewport.get().style.height = (this._size._height-40)+'px' ;
	this.viewport.bind('onmouseout', 'JukeboRegistry.get(\''+this._transmit_div+'\').hideMenu(2000); ') ;
	this.viewport.appendTo(this.widget);	 
	
	// -- Create search result
	this.results = _$('div').addClass(this._prefix+'_panels').attr('id', this._prefix+'_results') ;
	this.results.get().style.width = this._size._width+'px' ;
	this.results.get().style.height = (this._size._height-70)+'px' ;
	this.results.get().style.marginTop = '30px' ;
	this.results.appendTo(this.viewport) ;
	
	// -- VideoPlayer Panel
	this.VideoPlayer = _$('div').addClass(this._prefix+'_panels').attr('id', this._prefix+'_VideoPlayer') ;
	this.VideoPlayer.get().style.width = this._size._width+'px' ;
	this.VideoPlayer.get().style.height = (this._size._height-40)+'px' ;
	this.VideoPlayer.bind('onmouseover', 'JukeboRegistry.get(\''+this._transmit_div+'\').showMenu(); ') ;
	this.VideoPlayer.bind('onmousemove', 'JukeboRegistry.get(\''+this._transmit_div+'\').hideMenu(2000); ') ;
	this.VideoPlayer.appendTo(this.viewport) ;
	
	// -- Create footer
	var footer = _$('div').addClass(this._prefix+'_footer').html('<a href="'+this._backlink+'" title="'+this._backlink_title+'" target="_jukebo"><img src="'+this._root_site+'/img/trans.gif" width="167" height="38"></a>');
	footer.get().style.width = this._size._width+'px' ;
	footer.get().style.height = 40+'px' ;
	footer.appendTo(this.widget);
	
	// -- Set widget loaded class
	this.widget.addClass('loaded'); 
	
	// -- Create SearchInput
	this.createSearchPanel() ;
	
	// -- Create Ad Layer
	this.createAdLayer() ;
} ;



/******************************************************************** SHOW A PANEL ****/
	
// -- Go to a panel into viewport
JukeboWidget.prototype.showPanel = function(panelID, storeLastPanel) {
	
	// -- If asked to store last panel
	if ( 'undefined' != typeof storeLastPanel) this.lastPanelUsed = panelID ;
	
	// -- If panelID asked is 'last' 
	if ( panelID == 'last' ) 
		if ( typeof this.lastPanelUsed != 'undefined'  ) panelID = this.lastPanelUsed ;
		else panelID = this._prefix+'_results' ;
	
	// -- Show a loading spinner
	var self = this ;
	if ( this.menuHideTimeOut ) clearTimeout(this.menuHideTimeOut) ;
	this.showLoading() ;
	this.showMenu() ;
	
	// -- Search if div exists, else do nothing
	//console.log(panelID) ;
	
	var panel = _$('#'+panelID) ;
	if ( ! panel.length ) {
		try {
			var createFunction = 'JukeboRegistry.get(\''+this._transmit_div+'\').create'+panelID.replace(this._prefix+'_', '') ;
			createFunction = '('+createFunction+')()' ;    	
			eval(createFunction) ; 
			panel = _$('#'+panelID) ;
			//console.log('showPanel :: ', panelID, 'this.create'+panelID.replace(this._prefix+'_', '')) ;
		} catch(e) { 
			//console.log(e) ;
		}
	}
	
	if ( ! panel.length ) {
		return this.hideLoading() ;
	}
	
	// -- Get num of panels and set the good left cssRule
	var panels = this.viewport.find('.'+this._prefix+'_panels') ;
	var activeIndex = 0 ;
	for ( var x in panels ) {
		var id = _$(panels[x]).attr('id') ;
		if ( id == panelID ) {
			activeIndex = parseInt(x) ;
			this.activePanel = panelID.toString() ;
			break;
		}
	}
	
	// -- Restore default menu
	if ( this.activePanel != this._prefix+'_VideoPlayer' )  this.drawMenu() ;
	
	// -- Hide Search menu
	if ( this.activePanel != this._prefix+'_results' )  this.hideSearchPanel() ;
	
	// -- Calculate and animate 'left' style
	var nowLeft = parseInt((this.viewport.get().style.left||'0').replace('px', '')) ;
	var left = parseInt(-1*this._size._width*activeIndex) ;
	var deltaLeft = (nowLeft-left) ;
	var step = ((deltaLeft) < 0 ? 10 : -10)*Math.abs(deltaLeft/this._size._width) ;
	var delay = 10 ;
	
	var uMove = {type: 'left', from:nowLeft, to:left, step:  step, delay:delay} ;
	$fx(this.viewport.get()).fxAdd(uMove).fxRun(function() { self.hideLoading() ; });
	
} ;



/******************************************************************** MENU ****/

// -- Redraw Menu bar
JukeboWidget.prototype.drawMenu = function(menu) {	
	menu = menu || 'default' ;
	switch(menu) {
		case 'video':
			if ( 'undefined' != typeof this._jukebo_video_link ) {
			var fb_like = '<iframe src="http://www.facebook.com/plugins/like.php?href='+encodeURIComponent(this._root_site+this._jukebo_video_link)+'&amp;layout=button_count&amp;show_faces=false&amp;width=100&amp;action=like&amp;font=verdana&amp;colorscheme=light&amp;height=21" scrolling="no" frameborder="0" id="fb_like" style="border:none; overflow:hidden; width:66px; height:21px; top:0px; right:10px; margin-top:1px;  position: absolute; padding:0;" allowTransparency="true"></iframe>' ;
			}
			var menuList = {} ;
			menuList[' &laquo; '+this._translate[this.locale]['Go Back']+' &nbsp;&nbsp;&nbsp;'] = 'JukeboRegistry.get(\''+this._transmit_div+'\').showPanel("last");' ;
			if ( this._fb_like ) menuList['fb_like'] = '' ;
			break;
			
		default: 
			var menuList = {} ;
			menuList[this._translate[this.locale]['Search']] = 'JukeboRegistry.get(\''+this._transmit_div+'\').toggleSearchPanel(); JukeboRegistry.get(\''+this._transmit_div+'\').showPanel(\''+this._prefix+'_results\', true);' ;
			menuList['Tops'] = 'JukeboRegistry.get(\''+this._transmit_div+'\').showPanel(\''+this._prefix+'_TopClips\', true);' ;
	}
	this.menu.html(''); 
	var i = 0 ;
	for ( var label in menuList ) {
		if ( 'undefined' != typeof fb_like && label == 'fb_like' ) label = fb_like ;
		try { var onClick_cmd = menuList[label] ; } catch(e) {} ;
		var menuItem = _$('span').addClass('menuItem').html(label) ;
		if ( 'undefined' != typeof onClick_cmd ) 
			menuItem.bind('onclick', onClick_cmd) ;
		
		var separator = _$('span').addClass('menuSeparator').html('|') ;
		menuItem.hover(); 
		menuItem.appendTo(this.menu) ;
		if ( i < (count(menuList)-1) && 'undefined' == typeof fb_like ) separator.appendTo(this.menu) ;
		i++; 
	}
}; 

// -- Show Menu
JukeboWidget.prototype.showMenu = function() {
	if ( ! this.menuHided ) return false;
	if ( this.activePanel == this._prefix+'_Ad' ) return false;
	
	var self = this ;
	if ( this.menuHideTimeOut ) clearTimeout(this.menuHideTimeOut) ;
	this.menuHideTimeOut = setTimeout(function() {
		var uMove = {type: 'top', from:-30, to:0, step: 2, delay:20} ;
		$fx(self.menu.get()).fxStop() ;
		$fx(self.menu.get()).fxAdd(uMove).fxRun(function() {
			JukeboRegistry.get(self._transmit_div).menuHided = false;
		});
	}, 300) ;
} ;

// -- Hide Menu
JukeboWidget.prototype.hideMenu = function(timeout) {
	
	if ( this.activePanel != this._prefix+'_VideoPlayer' ) return false;
	if ( this.menuHided ) return false;
	if ( this.menuHideTimeOut ) clearTimeout(this.menuHideTimeOut) ;
	var timeout = timeout || 300 ;
	var self = this ;
	
	this.menuHideTimeOut = setTimeout(function() {
		var uMove = {type: 'top', from:0, to:-30, step: -2, delay:20} ;
		$fx(self.menu.get()).fxStop() ;
		$fx(self.menu.get()).fxAdd(uMove).fxRun(function() {
			JukeboRegistry.get(self._transmit_div).menuHided = true;
		});
	}, timeout) ;
} ;


/******************************************************************** LOADING ****/

// -- Show a loading div
JukeboWidget.prototype.showLoading = function() {
	var isDivExists = _$('#' + this._prefix+'_loading') ;
	if ( window.loadingTimeout ) clearTimeout(window.loadingTimeout) ;
	if ( ! isDivExists.length ) {
		var loading = _$('div').attr('id', this._prefix+'_loading') ;
		loading.get().style.width = this._size._width+'px' ;
		loading.get().style.height = (this._size._height-70)+'px' ;
		loading.get().style.marginTop = '30px' ;
		loading.appendTo(this.widget) ;
	}
}

// -- Hide loading div
JukeboWidget.prototype.hideLoading = function() {
	var self = this;
	if ( window.loadingTimeout ) clearTimeout(window.loadingTimeout) ;
	window.loadingTimeout = setTimeout(function() {
		_$('#'+self._prefix+'_loading').remove() ; 
	}, 500) ;
}


/********************************************************* SEARCH FEATURES ****/

// -- Create Search Input
JukeboWidget.prototype.createSearchPanel = function() {
	
	// -- Create the div
	this.searchEngine = _$('div').attr('id', this._prefix+'_search_engine') ;
	this.searchInput = _$('input').attr('id', this._prefix+'_search_input') ;
	
	// -- Adjust sizes
	this.searchEngine.get().style.width = this._size._width+'px' ;
	
	// -- Attach autocomplete
	this.searchInput.bind('onkeyup', 'JukeboRegistry.get(\''+this._transmit_div+'\').autoComplete()') ;
	
	// -- Append to document
	this.searchInput.appendTo(this.searchEngine) ;
	this.searchEngine.appendTo(this.widget) ;
	
	// -- Set expanded size
	this.SearchPanelDisplayed = false ;
	this.searchEngineHeight = 28 ;
} ;


// -- Show the search Panel
JukeboWidget.prototype.showSearchPanel = function() {
	this.SearchPanelDisplayed = true ;
	this.searchEngine.get().style.display = 'block' ;
	
	this.searchInput.get().focus() ;
	this.searchInput.get().select() ;
	
	// -- Animate Search Panel
	var uMove = {type: 'height', from:0, to:this.searchEngineHeight, step: 2, delay:20} ;
	$fx(this.searchEngine.get()).fxStop() ;
	$fx(this.searchEngine.get()).fxAdd(uMove).fxRun();
	
	// -- Animate Viewport
	var vHeight = {type: 'height', from:this._size._height-40, to:(this._size._height-40-this.searchEngineHeight), step: 2, delay:20} ;
	var vTop = {type: 'top', from:0, to:this.searchEngineHeight, step: 2, delay:20} ;	
	$fx(this.viewport.get()).fxStop() ;
	$fx(this.viewport.get()).fxAdd(vHeight).fxAdd(vTop).fxRun();
	
} ;

// -- Hide the SearchPanel
JukeboWidget.prototype.hideSearchPanel = function() {
	this.SearchPanelDisplayed = false ;

	var currentHeight = (this.searchEngine.get().style.height) ;
	currentHeight = ( currentHeight == '' ? 0 : parseInt(currentHeight.replace('px', '')) );	
	if ( currentHeight == 0 ) return ;

	var self = JukeboRegistry.get(this._transmit_div).searchEngine ;
	
	// -- Animate Search Panel
	var uMove = {type: 'height', from:this.searchEngineHeight, to:0, step: -2, delay:20} ;
	$fx(this.searchEngine.get()).fxStop() ;
	$fx(this.searchEngine.get()).fxAdd(uMove).fxRun(function() {
		self.get().style.display = 'none' ;
	});
	
	// -- Animate Viewport
	var vHeight = {type: 'height', from:(this._size._height-40-this.searchEngineHeight), to:(this._size._height-40), step: -2, delay:20} ;
	var vTop = {type: 'top', from:this.searchEngineHeight, to:0, step: -2, delay:20} ;	
	$fx(this.viewport.get()).fxStop() ;
	$fx(this.viewport.get()).fxAdd(vHeight).fxAdd(vTop).fxRun();
} ;

// -- Toggle the SearchPanel
JukeboWidget.prototype.toggleSearchPanel = function() {
	if ( this.SearchPanelDisplayed == true ) this.hideSearchPanel() ;
	else this.showSearchPanel();
} ;


// -- Display results returned by JSCall
JukeboWidget.prototype.display_result = function(data){

	// -- Clear results
    this.results.html('') ;
   
   	try {
   		//console.log('Search Results', data) ;
   	} catch(e) { }
   	
    // -- Parse datas and build html lines
    var dataLength = count(data) ;
    for (x in data){       
        row = data[x];
        
        // -- Thumb size
        row.thumbW = 42 ;
        row.thumbH = (this._resultLineHeight_default-10-(this._resultLineHeight_default-this._resultLineHeight)) ;
        
        // -- Create DOM and attach HTML
        var line = _$('div').addClass('searchResultItem').attr('video_id',row.ide)  ;
        line.get().style.height = this._resultLineHeight+'px';
        line.html('<div class="arrow"></div><div class="thumb"><img src="'+row.thumb+'" width="'+row.thumbW+'" height="'+row.thumbH+'"></div><div class="infos"><h2>'+row.artist+'</h2><h3>'+row.title+" ("+row.format+")"+'</h3></div></div>') ;
        
        // -- If at end, add an 'end' class
		if ( parseInt(x) == (dataLength-1) ) line.addClass('searchResultItem end') ;
		
		// -- Add onClick
		line.bind('onclick', 'JukeboRegistry.get(\''+this._transmit_div+'\').showVideo("'+row.ide+'", this)') ;
		line.hover() ;
		
		// -- Add title for mouseover
		line.attr('title', 'Play '+row.artist+' - '+row.title+" ("+row.format+")") ;
		
		// -- If autostart is true and not yet done
		if ( this._autostart == true && ! this._autostart_done ) {
			this.showVideo(row.ide, line.get()) ;
			this._autostart_done = true ;
		}
		
		// -- Append to results
        line.appendTo(this.results.get()) ;        
    }
    
    // -- Hide loading
    this.hideLoading() ;
}

// -- Manage autocompletion
JukeboWidget.prototype.autoComplete = function() {
	var self = this ;
	if ( this.autoCompleteDelay ) clearTimeout(this.autoCompleteDelay) ;
	this.autoCompleteDelay = setTimeout(function() {
		self.execute(new JukeboSearchQuery( self.searchInput.get().value));	
		self.showPanel(self._prefix+'_results') ;
		try {
			console.log('Autcomplete >> ',self.searchInput.get().value) ;
		} catch(e) {} ;
	}, 1000) ;
} ;

// -- execute a search Query
JukeboWidget.prototype.execute = function(query){
	 
	// -- Init Query instance
    if(typeof query == "string") query = new JukeboSearchQuery(query);
    if(!(query instanceof JukeboSearchQuery)) throw("JukeboSearchQuery or string expected in execute");

    // -- Show loading
   	this.showLoading() ;
    
    // -- Make Query
    var self = this; 
    var opts = {  	
    	q: 'jukebo_searchEngine',
    	url : this._root_api+query.getCallURL()+'/n/'+this._maxResults+"/",
    	onComplete: function(q, data) {
    		try { eval('data='+data); } catch(e) { throw('Search Results Error'); } ;
    		try { console.log(data) ; } catch(e) {} ;
    		JukeboRegistry.get(self._transmit_div).display_result(data._jkbp) ;
    	},
    	onError: function() {
    		JukeboRegistry.get(self._transmit_div).hideLoading() ;
    	}
    } ;
    Jsonp.get(opts) ;
}


/********************************************************* DISPLAY A VIDEO ****/
JukeboWidget.prototype.jscall = function(call_url){
    call_url = this._root_api+call_url+'/n/'+this._maxResults+"/"+'?calling_id='+this._transmit_div;
    _$('#'+this._prefix+'_jsonp').remove() ;
    _$('script').attr("type", "text/javascript").attr("src", call_url).attr('id', this._prefix+'_jsonp')
    .appendTo(document.getElementsByTagName('body')[0]) ;
}

JukeboWidget.prototype.request_vid = function(ide){
    call_url = '/preview/ide/'+ide+'/width/'+this._size.getWidth()+'/height/'+(this._size.getHeight()-40)+'/autoplay/'+(this._autoplay?'yes':'no')+'/mdtk/'+this._mdtk+'/zone/'+this._zone+'/';
    this.jscall(call_url);
}

// -- Insert a Video Panel and switch to it
JukeboWidget.prototype.showVideo = function(videoID, elDom, adSeen) {
	
	try {
		//console.log('Show Video > VideoID :: ', videoID, ' DOM :: ', elDom ) ;
	} catch(e) { }
	
	// -- Set panel ID
	var panelID = this._prefix+'_VideoPlayer' ;
	var panel = _$('#'+panelID) ;
	
	// -- Hide search box
	if ( this.SearchPanelDisplayed == true ) this.hideSearchPanel() ;
	
	// -- If videoID is a string, request for embed code
	if ( typeof videoID == 'string' ) {
		
		// -- Remove playing class setted in past and add to new one
		var el = ( 'undefined' != typeof elDom ) ? _$(elDom) : false ;
		var oldElm = this.viewport.find('.playing') ;
		if ( oldElm.length && el != _$(oldElm[0]) ) for ( var x in oldElm) _$(oldElm[x]).removeClass('playing') ;	
		if ( el ) el.addClass('playing') ;
		
		// -- Get Video to play
		if ( videoID == panel.attr('video_id') ) {
			this.hideLoading() ;
			this.drawMenu('video') ;	// -- Set menu bar to 'video'
			this.showPanel(panelID) ;	// -- Switch to video panel without rewriting embed code
		} else {
			this.request_vid(videoID);	
		}
		
		// -- Wait for jsonp response
		return false ;
	} 
	
	// -- If Video is playing, simply display VideoPlayer div
	if ( typeof videoID == 'object' && videoID.ide == panel.attr('video_id') ) {
		this.showPanel(panelID) ;	// -- Switch to video panel without rewriting embed code
		return false;
	}
	
	// -- Search if div exists, else do nothing
	if ( panel.length ) {
		panel.html('') ;
	}
	
	// -- Display the video or request video embed and execute gain with emebed code
	if ( typeof videoID == 'object' && typeof videoID.embed != 'undefined' ){
	
		// -- Have to render Ad ?
		var displayPub = false ;
		var videoViews = JukeboCookie.get_capping() ;
		if ('undefined' == typeof adSeen) {
			if ( (this._videoViews%this._ad_rotation) == 0 ) {
				if ( videoViews < this._ad_capping ) {
					//displayPub = true ;
				}
			}
		}
		
		// -- Special cases
		if ( videoID.embed.indexOf('alloclips') != -1 ) displayPub = false ;		
		
		// -- Display Ad in PreRoll
		if( displayPub ) return this.showAd(videoID, elDom);
		
		// -- Else Show Video
		this._jukebo_video_link = videoID.link ;
		this._videoViews++ ;
		panel.html(videoID.iframe) ;
		panel.attr('video_id', videoID.ide); // -- Set video ID to current video
		this.showPanel(panelID) ;	// -- Switch to panel
		this.drawMenu('video') ;
		this.hideMenu(3000) ;
	}	
} ;


/********************************************************* AD ****/

JukeboWidget.prototype.createAdLayer = function() {
	this.adLayer = _$('div').addClass(this._prefix+'_panels').attr('id', this._prefix+'_adLayer') ;
	this.adLayer.get().style.width = this._size._width+'px' ;
	this.adLayer.get().style.height = (this._size._height-40)+'px' ;
	this.adLayer.get().style.marginTop = '0px' ;
	this.adLayer.appendTo(this.viewport) ;
} ;

JukeboWidget.prototype.showAd = function(videoID, elDom) {
	var self = this ;
	this.showPanel(this._prefix+'_adLayer') ;
	
	// -- Inject Ad HTML Code
	this.adLayer.html(videoID.ad) ;
	
	// -- Set timeout and counter for AdEnd
	if ( this.showAd_timeout ) clearTimeout(this.showAd_timeout) ;
	this.showAd_timeout = setTimeout(function() {
		self.endVideoAd(videoID, elDom) ;
	}, self._ad_duration) ;
	
	this.waitAdEnd = self._ad_duration ;
	if ( this.showAd_interval ) clearInterval(this.showAd_interval) ;
	this.showAd_interval = setInterval(function() {
		self.updateCounterAd() ;
	}, 1000) ;
	self.updateCounterAd() ;
	
	//console.log('showAd::caping >> '+JukeboCookie.get_capping()) ;
} ;

JukeboWidget.prototype.updateCounterAd = function() {
	this.waitAdEnd = this.waitAdEnd - 1000 ;
	var delta = this._ad_duration - this.waitAdEnd ;
	if ( delta > 1000 ) this.menu.addClass('transparent') ;
	this.menu.html('<span class="menuItem">'+this._ad_startMessage.replace(/XX/, this.waitAdEnd/1000)+'</span>') ;
}

JukeboWidget.prototype.endVideoAd = function(videoID, elDom) {
	if ( this.showAd_timeout ) clearTimeout(this.showAd_timeout) ;
	if ( this.showAd_interval ) clearInterval(this.showAd_interval) ;
	JukeboCookie.increment_capping();
	this.adLayer.html('') ;
	this.menu.removeClass('transparent') ;
	this.showVideo(videoID, elDom, true) ;
	//console.log('endVideoAd :: Launch Video ['+videoID.ide+']');
} ;



/********************************************************* DISPLAY TOPS *******/
JukeboWidget.prototype.createTopClips = function() {

	// -- Create container
	this.TopClips = _$('div').addClass(this._prefix+'_panels').attr('id', this._prefix+'_TopClips') ;
	this.TopClips.get().style.width = (this._size._width)+'px' ;
	this.TopClips.get().style.height = (this._size._height-70)+'px' ;
	this.TopClips.get().style.marginTop = '30px' ;
	this.TopClips.get().style.padding = '0px' ;
	this.TopClips_VW = _$('div').attr('id', this._prefix+'_TopClips_VW').appendTo(this.TopClips.get()) ;
	this.TopClips.after(this.results) ;
	
	// -- Request Top
	this.updateTopClips() ;
} ;

// -- Request tops update
JukeboWidget.prototype.updateTopClips = function(){
	this.showLoading() ;
	var self = this; 
	var opts = {
		url : this._root_api+"/top/country/"+this.country+"/",
		onComplete: function(q, data) {
			try { eval('data='+data); } catch(e) { throw('Search Results Error'); } ;
			self.refreshTopClips(data._jkbp) ;
		},
		onError: function() {
			self.hideLoading() ;
		}
	} ;
	Jsonp.get(opts) ;
}

// -- Refresh Top Clips content
JukeboWidget.prototype.refreshTopClips = function(data){

	// -- Hide Search Panel
	this.hideSearchPanel() ;
	
	// -- Clear results and show title
	var dataLength = count(data) ;
	var country = this.country ;
	country = country.charAt(0).toUpperCase() + country.substr(1);
	if ( country == 'Spain' ) country = 'Espa&ntilde;a' ;
	_$('h2').html('Top '+country).appendTo(this.TopClips_VW.get()) ;
   
    // -- Parse datas and build html lines
    data = data.slice(0,20);
    for (x in data){       
        row = data[x];
        
        //console.log(row, dataLength) ;
        
        if ( true ) {
        
	        // -- Thumb size
	        row.thumbW = parseInt((this._size.getWidth()-20)/5) ;
	        row.thumbH = row.thumbW*7/10 ;
	        
	        // -- Create DOM and attach HTML
	        var line = _$('div').addClass('searchResultImage').attr('video_id',row.ide)  ;
	        line.html('<div class="badge">'+(parseInt(x)+1)+'</div><div class="thumb" style="width:'+row.thumbW+'px;"><img src="'+row.thumb+'" width="'+row.thumbW*0.85+'" height="'+row.thumbH*0.85+'"></div></div>') ;
	        
	        // -- If at end, add an 'end' class
			if ( parseInt(x) == (dataLength-1) ) line.addClass('searchResultImage end') ;
			
			// -- Add onClick
			line.bind('onclick', 'JukeboRegistry.get(\''+this._transmit_div+'\').showVideo("'+row.ide+'", this);') ;
			
			// -- Add title for mouseover
			line.attr('title', 'Play '+row.artist+' - '+row.title) ;
			
			// -- If autostart is true and not yet done
			if ( this._autostart == true && ! this._autostart_done ) {
				this.showVideo(row.ide, line.get()) ;
				this._autostart_done = true ;
			}
			
			// -- Append to results
	        line.appendTo(this.TopClips_VW.get()) ;  
        }      
    }
    
    // -- Hide loading
    this.hideLoading() ;
}
