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"));
        displayed_times = parseInt(cook_val==NaN || cook_val=="NaN" ? "0" : cook_val);
        return displayed_times;
    },

    increment_capping : function(){
        displayed_times++;
        JukeboCookie.set("jukebo_widget_capping",displayed_times,1);
    }
}

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

JukeboSize = function(width,height){
    if(width == undefined){
        throw("Width must be defined");
    }
    if(width < 300){
        throw("Width must be greater than 300");
    }
    default_height = Math.max(270,3*width/4);
    
    if(height == undefined || height < default_height){
        height = default_height;
    }
    this._width = width;
    this._height = height;
}

JukeboSize.prototype.getWidth = function(){
    return Math.max(300,this._width);
}

JukeboSize.prototype.getHeight = function(){
    return Math.max(270,this._height);
}


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;
}


JukeboWidget = function(target_div,options){

    if(options.size == undefined){
        throw("JukeboSize expected");
    }
    var size = options.size
    if(!(size instanceof JukeboSize)){
        throw("JukeboSize expected");
    }
    
    if(options.maxResults != undefined && options.maxResults != null){
        this._maxResults = options.maxResults;
    }else{
        this._maxResults = 6;
    }
    
    if(options.preSearch != undefined && typeof options.preSearch == "function"){
        this._pre_search = options.preSearch;
    }
    if(options.postSearch != undefined && typeof options.postSearch == "function"){
        this._post_search = options.postSearch;
    }
    if(options.preDisplay != undefined && typeof options.preDisplay == "function"){
        this._pre_display = options.preDisplay;
    }
    if(options.postDisplay != undefined && typeof options.postDisplay == "function"){
        this._post_display = options.postDisplay;
    }
    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";
    }
   
    if(options.mdtk != undefined && options.mdtk != null){
        this._mdtk = options.mdtk;
    }else{
        this._mdtk = '0100010';
    }
 
    this._size = size;
    this._target_div = target_div;
    this._root_api = "http://www.jukebo.fr/api/widget";
    this._prefix = "jkbwdgt";
    this._uid = Math.round(Math.random()*100000);
    
    this._ad_duration = 12000;
    this._ad_capping  = 1;
    
    this._transmit_div = this._prefix+"_transmit_"+this._uid;
    this._search_div   = this._prefix+"_search_"+this._uid;

    
    original_text = document.getElementById(this._target_div).innerHTML;
    document.getElementById(this._target_div).innerHTML = ("<div id=\""+this._transmit_div+"\"></div>");
    
    if(options.target !=undefined && options.target != null){
        this._preview_div  = options.target;
    }else{
        this._preview_div  = this._prefix+"_preview_"+this._uid;
        document.getElementById(this._target_div).innerHTML += ("<div id=\""+this._preview_div+"\" class=\"jukebo_widget_preview\"></div>");
    }
    
    document.getElementById(this._target_div).innerHTML += ("<div id=\""+this._search_div+"\" class=\"jukebo_widget_search\">"+original_text+"</div>");
    JukeboRegistry.set(this._transmit_div,this);
}

JukeboWidget.prototype.jscall = function(call_url){

    call_url = this._root_api+call_url+'/n/'+this._maxResults+"/"+'?calling_id='+this._transmit_div+'&mdtk='+this._mdtk;
    document.getElementById(this._transmit_div).innerHTML = '';
    var scr  = document.createElement("script");
    scr.type = "text/javascript";
    scr.src  = call_url;
    document.getElementById(this._transmit_div).appendChild(scr);
}

JukeboWidget.prototype.request_vid = function(ide){
    call_url = '/preview/ide/'+ide+'/autoplay/yes/width/'+this._size.getWidth()+'/height/'+this._size.getHeight();
    this.jscall(call_url);
}

JukeboWidget.prototype.execute = function(query){

    if(typeof query == "string"){
        var query = new JukeboSearchQuery(query);
    }
    
    if(!(query instanceof JukeboSearchQuery)){
        throw("JukeboSearchQuery or string expected in execute");
    }
    
    call_url = query.getCallURL();
    this.jscall(call_url);
}

JukeboWidget.prototype.update_ad = function(){
    var counter = parseInt(document.getElementById("jukebo_counter"+this._uid).innerHTML);
    document.getElementById("jukebo_counter"+this._uid).innerHTML = (counter-1);
}

JukeboWidget.prototype.display_ad = function(data){
    
    if(JukeboCookie.get_capping() > this._ad_capping){
                this.display_vid(data);
                return;
    }
    
    document.getElementById(this._preview_div).innerHTML = "";
    document.getElementById(this._preview_div).innerHTML = ("<div style=\"text-align:center;color:white;\">Votre vidéo dans <strong style=\"color:red\" id=\"jukebo_counter"+this._uid+"\">"+(this._ad_duration/1000)+"</strong> secondes</div>");
    document.getElementById(this._preview_div).innerHTML += ('<div style="text-align:center;clear:both">'+data.ad+'</div>');
    this._vid_data = data;
    clearTimeout(this._current_timeout);
    this._current_timeout = setTimeout("JukeboRegistry.get('"+this._transmit_div+"').display_vid()",this._ad_duration);
    clearInterval(this._current_interval);
    this._current_interval = setInterval("JukeboRegistry.get('"+this._transmit_div+"').update_ad()",1000);
}

JukeboWidget.prototype.display_vid = function(data){

    JukeboCookie.increment_capping();
        
    clearTimeout(this._current_timeout);
    clearInterval(this._current_interval);    
    if(data == undefined){
        if(this._vid_data == undefined || this._vid_data == ""){
            throw("Expected video data");
        }
        data = this._vid_data;
    }
    this._vid_data = data;
    if(this._pre_display != undefined){
        this._pre_display(data);
    }
    document.getElementById(this._preview_div).innerHTML = "";
    document.getElementById(this._preview_div).innerHTML = '<div style="text-align:center;clear:both">'+data.embed+'</div>';
    
    if(this._post_display != undefined){
        this._post_display(data);
    }
}

JukeboWidget.prototype.display_result = function(widget,data){
    
    document.getElementById(this._search_div).innerHTML = "";
    
    for (x in data){       
        row = data[x];
        if(row.ide == "33m03") continue; //false result
        
        var div             = document.createElement('div');
            div.id          = 'jukebo_show_' + row.ide;
            div.className   = 'jukebo_widget_search_result';
            div.value       = row.ide;
            
        var br             = document.createElement('br');
        
        var img             = document.createElement('img');
            img.src         = row.thumb;
            
        var link            = document.createElement('a');
            link.href       = 'javascript:JukeboRegistry.get(\''+this._transmit_div+'\').request_vid(\''+row.ide+'\')';
            link.title      = row.artist+' - '+row.title;
        
        if(this._search_type == "thumbs"){
            var linktext = document.createTextNode("Show !");
            link.appendChild(img);
            link.appendChild(br);
            link.appendChild(linktext);
            div.appendChild(link);
        }
        
        if(this._search_type == "list"){
           link.appendChild(img);
           var songinfo = document.createElement('div');
           
           var spantitle = document.createElement('span');
               spantitle.className = "jukebo_widget_result_title";
           var titletext = document.createTextNode(row.title+" ("+row.format+")");
               spantitle.appendChild(titletext);
               
           var spanartist = document.createElement('span');
               spanartist.className = "jukebo_widget_result_artist";
           var artisttext = document.createTextNode(row.artist);
               spanartist.appendChild(artisttext);
           
           songinfo.appendChild(spantitle);
           songinfo.appendChild(br);
           songinfo.appendChild(spanartist);
           
           link.appendChild(songinfo);
           div.appendChild(link);
        }
        document.getElementById(this._search_div).appendChild(div);
    }
    
        document.getElementById(this._search_div).innerHTML += ('<div class="jukebo_widget_footer"><a href="http://www.jukebo.fr/">Powered by Jukebooooo !</a></div>');
}
