// ==PREPROCESSOR==
// @name "ALBUM COVER FOLOW"
// @version "2.1"
// @author "Vo Thanh Dat and modded by AnonymousGrafix my touch mod_2 "
// ==/PREPROCESSOR==
// @tooltip "custom-paint"
function RGBA(r, g, b, a) { return (a << 24)|(r << 16)|(g << 8)|(b);}
function RGB(r, g, b) { return 0xff000000|(r << 16)|(g << 8)|(b);}

var lbdn = 0;
var y_start = 0;
var y_end = 0;
var y_delta = 0;

var DrawBitmap = true;
var Load_async = true;

var form_text = "",
    form_text_b = "",
    form_his = [],
    form_his_ = [];
var char_index = [];
var font = window.GetProperty("Font_size","25");
var g_time = window.setInterval(on_timer,window.GetProperty("TimerInterval",16)/2);
//var g_time = window.SetInterval(on_timer,16);
var fso = new ActiveXObject("Scripting.FileSystemObject");
var WshShell = new ActiveXObject("WScript.Shell");
var htmlfile = new ActiveXObject('htmlfile');
var touch_sens = window.GetProperty("Touch_sensitivity",5);
var row_count = window.GetProperty("Row",3);
var playlist = window.GetProperty("playlist exclusion","");
var min_song = window.GetProperty("minimum song per group",5);
//================================================================================================= Colors
var select_color = RGBA(144,238,144,0);
var cover_back_color = RGBA(0,139,139,150);
var back_shadow_color = RGBA(0,0,0,50);
var text_color = RGBA(220,200,200,200);
var background_color = RGBA(0,200,0,200);
//=====================================================================================
var cover_path = new RegExp("(artwork)|(cover)|(scan)|(image)");
var cover_img = "*folder*.*-*front*.*-*cover*.*-*.*".split("-");
var g_font = gdi.Font("Segoe UI", 14, 0);
var g_font_m = gdi.Font("Segoe UI", 14, 0);
var g_font_i = gdi.Font("Segoe UI Semibold", 13, 2);
var g_font_c = gdi.Font("Segoe UI Semibold", font, 0);//================ font
var g_font_al1 = gdi.Font("Segoe UI Semibold", 14, 0);
var g_font_al2 = gdi.Font("Segoe UI Semibold", 22, 0);
var g_font_al3 = gdi.Font("Segoe UI Semibold", 16, 0);
var g_font_al4 = gdi.Font("Segoe UI Semibold", 14, 0);
var time_f = fb.CreateProfiler("time_f"),
    time_s = fb.CreateProfiler("time_s"),
    time_r = fb.CreateProfiler("time_r"),
    time_h = fb.CreateProfiler(),
    time_scroll = fb.CreateProfiler("Time delay paint");



var stub_image,cell_null,cell_null_gr;
var mouse_l_hold_f = false,
    on_form = false,
    form_text_cusor_hiden = false,
    repaint_f1 = false,
    repaint_f2 = false,
    repaint_f = true,
    repaint_a = false,
    repaint_main1 = false,
    repaint_main2 = false,
    repaint_main = true,
    hold_shift = false,
    mouse_in = false,
    main_or_form = false,
    hold_scroll = false,
    isvisible = false;
    
var form_text_cusor = 0,
    bold_start=0,
    bold_end=0,
    shift_index = 0,
    text_heigh = 0,//================== def 23 search string height
    time_reset_loadimg = 30,
    postion_load_img = 0.5,
    m_m = -1,
    max_scroll = window.Width,
    max_load_done = 0,
    ww = window.Width,wh = window.Height,m_x = 0,m_y = 0,start = 0,end = 0,start_ = 0,time_dl = 0;

var scroll = 0,scroll_ = 0,scroll__ = 0,scroll___ = 0,
    scr1 = 0,scroll_v = 0,scroll_a = 0,scr2 = window.Width,
    cell = Math.floor((wh - text_heigh - 12)/row_count);
var list = [],list_al = [],list_ar = [],list_ge = [],
    list_dr = [],list_img = [];
    
var ex_al_idx = -1000,
    ex_length_idx = [],
    ex_length_idx_ = [],
    ex_length_idx__ = [],
    ex_length_idx___ = [],
    playlist_ex = null,
    playlist_ex_maxscr = 0,
    check_ex_old = -1,
    ex_opt = true;

window.DlgCode = 0x0081 ;


function get_cusor_index(x){
    var result = form_text.length;
    while(char_index[result] > x )
        result--;
    return (result > 0)?result:0;
}

function refresh_char_index(gr){
    char_index = [];
    for(var i = 0;i < form_text.length + 1;i++)
        char_index[i] = gr.EstimateLineWrap(form_text.substr(0,i),g_font,ww).toArray()[1];
}
//===========================================================================================
function on_mouse_lbtn_up(x,y,mask){
    lbdn = 0;
    y_start = y;
    hold_scroll = mouse_l_hold_f = false;
    scroll = Math.round(scroll / cell / 2) * cell * 2;
}
//=============================================================================================
function on_mouse_lbtn_down(x,y,mask){
    lbdn = 1;
    y_start = x;
    g_drag = true;
    mouse_l_hold_f = on_form = (y < text_heigh);
    mouse_l_hold = !mouse_l_hold_f;
    /*
    if(y < text_heigh){
        if(x < ww - text_heigh){
            form_text_cusor = get_cusor_index(x);
            repaint_f1 = repaint_f2;
            form_text_cusor_hiden = true;
            time_f.Reset(); 
        }else if(x > ww - text_heigh){
            bold_start = bold_end = form_text_cusor = 0;
            form_text = "";
            time_f.Reset(); 
        }
        if(mask == 1.5){
            bold_start = (" " + form_text + " ").lastIndexOf(" ",form_text_cusor);
            bold_end = (" " + form_text + " ").indexOf(" ",form_text_cusor+1)-1;
        }else
            bold_start = bold_end = form_text_cusor;
    }else if(y > wh - 8){
        hold_scroll = true;
        scroll = (x * max_scroll / ww) - ww/2;
    }else if(ex_opt){
        var tmp = check(x,y);
        if(tmp > -1 && tmp == ex_al_idx){
            for(var i = 0;i < ex_length_idx.length;i++)
                ex_length_idx[i] = 0;
            ex_al_idx = -1000;
        }else if(tmp > -1 ){
            var m = 0;
            var col_idx = Math.floor(tmp/row_count)
            playlist_ex = init_album_playlist(list_dr[tmp],tmp);
            
            ex_al_idx = tmp;
            for(var i = 0;i < ex_length_idx.length;i++){
                if(i > col_idx) ex_length_idx[i] = 2;
                else ex_length_idx[i] = 0;
            }
            if(col_idx * cell * 2 < scroll )
                scroll = col_idx * cell * 2;
            else if((col_idx  + 3)* cell * 2 > scroll + ww)
                scroll += ((col_idx  + 3)* cell * 2 - scroll - ww);
            scroll = Math.ceil(scroll / cell / 2) * cell * 2;
            repaint();
        }else if(tmp <= -1.5 && playlist_ex){
            var tmp_ = Math.round((-tmp - 1.5)*1000);
            for(a in playlist_ex.list)
                playlist_ex.list[a].chose = false;
            playlist_ex.list[tmp_].chose = true;
            repaint();
            //fb.trace(tmp_ + " - " + tmp);
        }else if(tmp <= -1.1 && playlist_ex){
            
        }else{
            for(var i = 0;i < ex_length_idx.length;i++)
                ex_length_idx[i] = 0;
            ex_al_idx = -1000;
        }
    }
*/
}


function on_size(){
    ww = window.Width;
    wh = window.Height;
    if(ww == 0 || wh == 0)
        return;
    var scroll_t = Math.floor(scroll/cell/2);
    cell = Math.floor((wh - text_heigh - 12)/row_count);
    scroll____ = scroll__ = scroll_ = scroll = scroll_t * cell * 2;
    max_scroll = scroll_ + ww;
    repaint_f1 = repaint_f2;
    repaint();
}

function on_char(code){
    time333 = (new Date()).getTime();
    if(on_form){
        time_s.Reset();
        form_text_cusor_hiden = true;
        selected_cusor = -1;
        var coppy = false,paste = false,cut = false;     
        var input = String.fromCharCode(code);  
        switch(code){
            case 13://ENTER
                var pllist = plman.GetPlaylistItems(-1);
                for(var i in list_dr)
                    pllist.AddRange(list_dr[i].pl)
                apply_playlist(pllist);
            break;
            
            case 25: 
                form_his.push(form_text);
                if(form_his.length > 30) form_his.shift();
                if(form_his_.length > 0) form_text = form_his_.pop() + "";
                break;
            case 26:
                form_his_.push(form_text);
                if(form_his_.length > 30) form_his.shift();
                if(form_his.length > 0) form_text = form_his.pop() + "";
            break;
            
            case 1://CTRL + A
                bold_start = 0;
                bold_end = form_text.length;
            break;
            
            case 3: // COPPY
                (bold_start != bold_end) && htmlfile.parentWindow.clipboardData.setData('text',form_text.substring(bold_start,bold_end));
            break;
            
            case 24://CUT
                (bold_start != bold_end) && htmlfile.parentWindow.clipboardData.setData('text',form_text.substring(bold_start,bold_end));
            case 8:
                save_form_his();
                if(bold_start == bold_end){
                    form_text = form_text.substring(0,form_text_cusor-1) + form_text.substring(form_text_cusor,200);
                    if(form_text_cusor > 0)
                        form_text_cusor--;
                    bold_end = bold_start = form_text_cusor;
                }else{
                    form_text = form_text.substring(0,bold_start) + form_text.substring(bold_end,200);
                    form_text_cusor = bold_start;
                    bold_end = bold_start;
                }
            break;

            case 22://CTRL + V//PASTE
                input = htmlfile.parentWindow.clipboardData.getData('text');
                if(input == null) input = "";
            default: //CHAR
                save_form_his();
                if(char_index[form_text.length] + text_heigh >= ww - 10)
                    break;
                if(bold_start == bold_end){
                    form_text = form_text.substring(0,form_text_cusor) + input + form_text.substring(form_text_cusor,200);
                    form_text_cusor += input.length;
                    bold_end = bold_start = form_text_cusor;
                }else{
                    form_text = form_text.substring(0,bold_start) + input + form_text.substring(bold_end,200);
                    form_text_cusor = bold_start + input.length;
                    bold_end = bold_start;
                }
            break;

        }
        repaint_f1 = repaint_f2;
    }
}

function save_form_his(){
    if(time_h.Time < 100)
        return;
    form_his.push(form_text);
    form_his_ = [];
    if(form_his.length > 30) form_his.shift();
    time_h.Reset();
}

function on_key_down(vkey) {
    switch(vkey){
        case 0x25:
            if(!on_form)return;
            if(form_text_cusor > 0){
                form_text_cusor--;
            }
            if(hold_shift){
                bold_start = (form_text_cusor < shift_index)?form_text_cusor:shift_index;
                bold_end = (form_text_cusor > shift_index)?form_text_cusor:shift_index;
            }else
                bold_start = bold_end = form_text_cusor;
        break;
        case 0x27:
            if(!on_form)return;
            if(form_text_cusor < form_text.length){
                form_text_cusor++;
            }
            if(hold_shift){
                bold_start = (form_text_cusor < shift_index)?form_text_cusor:shift_index;
                bold_end = (form_text_cusor > shift_index)?form_text_cusor:shift_index;
            }else
                bold_start = bold_end = form_text_cusor;
        break;
        case 0x10:
            hold_shift = true;
            shift_index = form_text_cusor;
        break;
        case 0x11:
        break;
        case 13:

        break;
        case 40:case 38:

        break;
    }
    repaint_f1 = repaint_f2;
    form_text_cusor_hiden = true;
}



function on_key_up(vkey){
    switch(vkey){
        case 0x10:
            hold_shift = false;
            shift_index = form_text_cusor;
        break;
        case 0x11:
            hold_ctrl = false;
        break; 
    }
}
//=========================================================================================== Touch mod
function on_mouse_move(x,y){
    if (lbdn) {
           y_end = x;
           y_delta = (y_end - y_start);    
      if (x < ww){
	       
      if (y_delta > wh/touch_sens) {
         on_mouse_wheel(1);
	     repaint_f1 = repaint_f2;
         //window.Repaint()
         y_start = y_end;  
    } 
      if (y_delta < -wh/touch_sens) {
	     on_mouse_wheel(-1)
	     repaint_f1 = repaint_f2;
         //window.Repaint()
         y_start = y_end;   
	};

}
//scroll = check_scroll(scroll);   
}
    
    if(m_x == x && m_y == y)
        return;
    mouse_in = y > text_heigh;
    if(y < text_heigh && x < ww - text_heigh)
        //window.SetCursor(32513);
    //else
        window.SetCursor(32512);
    
    if(y < text_heigh && mouse_l_hold_f){
        bold_start = form_text_cusor;
        bold_end = get_cusor_index(x);
        if(bold_start > bold_end){
            var tam = bold_start;
            bold_start = bold_end;
            bold_end = tam;
        }
        repaint_f1 = repaint_f2;
    }
    if(m_x > ww-text_heigh && m_y < text_heigh)
        repaint_f1 = repaint_f2;
    if(hold_scroll){
        scroll = (x * max_scroll / ww) - ww/2;
    }
    m_x = x;m_y = y;
    
    
}

function on_mouse_leave(){
    hold_scroll = mouse_hold = mouse_in = false;
    repaint();
}


//=============================================================== ON PAINT//Search bar
function on_paint(gr){
    !window.IsTransparent && gr.FillSolidRect(0, 0, ww, wh, background_color);
    if(ww == 0 || wh == 0)
        return;
    //if(!repaint_f && !repaint_main)
        repaint_f = repaint_main = true;
    /*if(repaint_f){
        repaint_f = false;
        refresh_char_index(gr);
        if(bold_start < 0) bold_start = 0;
        if(bold_end < 0) bold_end = 0;
        if(bold_start > form_text.length) bold_start = form_text.length;
        if(bold_end > form_text.length) bold_end = form_text.length;
        if(form_text_cusor < 0) form_text_cusor = 0;
        if(form_text_cusor > form_text.length) form_text_cusor = form_text.length;
        form_text_cusor_x = char_index[form_text_cusor];
        gr.DrawLine(3,text_heigh/2,ww,text_heigh/2,text_heigh,0x60000000);
        on_form && form_text_cusor_hiden && (bold_start == bold_end) && gr.DrawLine(form_text_cusor_x + text_heigh/10,text_heigh/10,form_text_cusor_x + text_heigh/10,text_heigh*0.9,1,0xffffffff);
        bold_end = (bold_end < form_text.length)?bold_end:form_text.length;
        (bold_start != bold_end) && gr.DrawLine(char_index[bold_start] + text_heigh/10,text_heigh/2,char_index[bold_end] + text_heigh/10,text_heigh/2,text_heigh-3,0xff0099ff);
        gr.GdiDrawText(form_text, g_font, RGB(225,225,225), text_heigh/4, text_heigh/10, ww, text_heigh, 0);
        (form_text == "") && gr.GdiDrawText(" Search Library", g_font_i, RGB(180,180,180), text_heigh/4, text_heigh/40, ww, text_heigh, 0);
        
        //gr.DrawLine(ww-text_heigh*0.7,text_heigh*0.7,ww - text_heigh*0.3,text_heigh*0.3,text_heigh/10,(m_x > ww-text_heigh && m_y < text_heigh)?RGBA(255,255,255,200):RGBA(255,255,255,130));
        //gr.DrawLine(ww-text_heigh*0.7,text_heigh*0.3,ww - text_heigh*0.3,text_heigh*0.7,text_heigh/10,(m_x > ww-text_heigh && m_y < text_heigh)?RGBA(255,255,255,200):RGBA(255,255,255,130));
    } */

    if(repaint_main){
        var time_reset = (Math.abs(scroll - scroll_) > postion_load_img * cell);
        repaint_main = false;
        var hg = Math.floor((wh - text_heigh - 12)/row_count);
        var width_ = 0,x_ = 0,y_ = 0;
        var paint_continue = true;
        start = Math.floor(Math.max(0,Math.round(scroll_  / hg / 2 - 0.5)) * row_count);
        end = Math.min(start + Math.round(ww/ hg / 2 + 1.5)*row_count,list_dr.length);
        var sss = (1-Math.pow(0.9,time_dl/10));
        for(var i = 0;i < list_dr.length;i++){
            if(Math.abs(list_dr[i].i - i )*cell >  1 ){
                list_dr[i].i += (i - list_dr[i].i)*sss;
                repaint();repaint_f1 = repaint_f2;
                if(Math.abs(list_dr[i].i - i ) > postion_load_img)
                    time_reset = true;
                if(Math.abs(list_dr[i].i - i ) < 3 && list_dr[i].al < 250)
                    list_dr[i].al = 255*(1 - Math.abs(list_dr[i].i - i)/3);
            }
        }
        
        var row_ex_idx = Math.floor(ex_al_idx/row_count);
        if(start > ex_al_idx && ex_al_idx > -1){
            start = Math.min(0,start - row_count * 2);
        }
        for(var i = start;i < end;i++){
            if(!list_dr[i] || list_dr[i].al == 0 || Math.abs(list_dr[i].i - i ) > row_count)
                continue;
            var row_el_idx = Math.floor(i/row_count);
            x_ = Math.floor(Math.round((list_dr[i].i+0.5)/row_count - 0.5)*hg*2 - scroll_);
            y_ = hg * ((list_dr[i].i+0.5)%row_count) + text_heigh + 4 -0.5*hg ;
            x_ += cell * 2 * ex_length_idx_[Math.floor(i/row_count)];
            if(x_ + cell*2 < 0)
                continue;
            if(x_ > ww )
                break;
            if(list_dr[i].alpha > 0 && !(list_dr[i].alpha >= 240 && i == check(m_x,m_y))) {
                list_dr[i].alpha -= 8*time_dl/16;
                repaint();
            } 
            gr.SetSmoothingMode(4);
            list_dr[i].alpha = Math.min(list_dr[i].alpha,220);
            (list_dr[i].alpha > 0)  && gr.FillGradRect(x_-0.5,y_-2,hg * 2+3,hg+2,3,3,select_color|(list_dr[i].alpha << 24),0x2a2a2a|(list_dr[i].alpha << 24)); //========== sel color
            //(list_dr[i].alpha > 0)  && gr.FillRoundRect(x_-0.5,y_-2,hg * 2+3,hg+2,3,3,0xffffff|(list_dr[i].alpha << 24));
            var wid = cell * 2 - 3,hei =  cell - 3;//cell * 2-3, cell-3
            if(list_dr[i].imgcell && list_dr[i].imgcell.Width == (cell*2-3)){
                var alpha = list_dr[i].al;
                (alpha > 240) && (alpha = 255);
                DrawBitmap && gr.GdiAlphaBlend(list_dr[i].imgcell,x_ + 3,y_+1,2 * cell - 3,cell - 3,0,0,list_dr[i].imgcell.Width, list_dr[i].imgcell.Height,alpha);
                !DrawBitmap && gr.DrawImage(list_dr[i].imgcell,x_ + 3,y_+1,wid,hei,0,0,list_dr[i].imgcell.Width, list_dr[i].imgcell.Height,0,alpha);    
                //gr.GdiAlphaBlend(list_dr[i].imgcell,x_ + 3,y_+1,2 * cell - 3,cell - 3,0,0,cell * 2-3, cell-3,list_dr[i].al);
            }else if(paint_continue && list_dr[i].img_ && time_scroll.Time < 17){
                list_dr[i].imgcell = Draw_cell(list_dr[i].img_,list_dr[i].name + "\r\n(" + list_dr[i].pl.Count + " Tracks)");
                DrawBitmap && gr.GdiAlphaBlend(list_dr[i].imgcell,x_ + 3,y_+1,2 * cell - 3,cell - 3,0,0,cell * 2-3, cell-3,list_dr[i].al);
                !DrawBitmap && gr.DrawImage(list_dr[i].imgcell,x_ + 3,y_+1,2 * cell - 3,cell - 3,0,0,wid, hei,0,list_dr[i].al);
                time_r.Reset();
                repaint();
                paint_continue = false;
                //break;
            }else if(paint_continue && time_scroll.Time < 17){
                list_dr[i].imgcell = Draw_cell(null,list_dr[i].name + "\r\n(" + list_dr[i].pl.Count + " Tracks)");
                DrawBitmap && gr.GdiAlphaBlend(list_dr[i].imgcell,x_ + 3,y_+1,2 * cell - 3,cell - 3,0,0,cell * 2-3, cell-3,list_dr[i].al);
                !DrawBitmap && gr.DrawImage(list_dr[i].imgcell,x_ + 3,y_+1,wid,hei,0,0,wid, hei,0,list_dr[i].al);
                time_r.Reset();
                repaint();
                paint_continue = false;
                //break;
            }else{
                var alpha = list_dr[i].al;
                (alpha > 240) && (alpha = 255);
                DrawBitmap && cell_null_gr && gr.GdiAlphaBlend(cell_null_gr,x_ + 3,y_+1,2 * cell - 3,cell - 3,0,0,cell * 2-3, cell-3,alpha);
                !DrawBitmap && cell_null_gr && gr.DrawImage(cell_null_gr,x_ + 3,y_+1,wid,hei,0,0,wid, hei,0,alpha);
            }
        }
        
        var delta = 0;//repaint_a
        if(playlist_ex && playlist_ex.idx >= start && playlist_ex.idx <= end){
            delta = (ex_length_idx_[playlist_ex.col_idx + 1] - ex_length_idx_[playlist_ex.col_idx]);
            playlist_ex.delta = delta;
            if(delta * cell * 2 > 5){
                var x = Math.floor(Math.round(playlist_ex.col_idx+1) * hg * 2 + 3 + ex_length_idx_[playlist_ex.col_idx] * hg * 2 - scroll_),
                    y = text_heigh + 3,
                    w = Math.floor(hg * 2 * delta - 3.5),
                    h = hg * row_count - 2;
                if(x + w > 0 && x < ww)
                     draw_album_playlist(gr,playlist_ex,x,20,w,h);
            }
        } 

        !paint_continue && time_r.Reset();

        if(time_dl > 18 && postion_load_img > 0.3){
            fb.trace("Reset : " + postion_load_img);
            postion_load_img = 0.1;
            time_r.Reset();
        }else if(time_dl < 17 && postion_load_img < 3){
            postion_load_img *= 1.01;
        }
        if(!delta) delta = 0;
        time_reset && time_r.Reset();
        var lenf_ = cell * 2 * Math.round( list_dr.length / row_count + 0.499) + ww%(cell * 2) + delta * cell * 2; 
        var scr2_ = Math.min(Math.round(ww*ww/lenf_) + 1,ww+20);
        if(Math.round(list_dr.length / row_count+0.499) * (cell*2) > ww)
            max_scroll = lenf_;
        scr1 = scroll_/lenf_ * ww;
        scr2 += (scr2_ - scr2)*sss;
        if(scr2 < ww){
            gr.DrawLine(3,wh-4,ww,wh-4,7,0x60000000);
            gr.DrawLine(scr1+4 ,wh-4,scr1 + scr2 - 3,wh-4,5,0xa0ffffff);
            ((scr2_ - scr2)*sss > 1) && repaint();
        }
    }
}

function on_timer(timer_id){
    if(window.IsVisible && ww * wh > 0){
        on_timer_();    
    }else if(time_scroll.Time > 30 && max_load_done + 2 < list_dr.length){
        main_or_form = true;
        time_scroll.Reset();
        on_timer_();   
    }
}

//======================================================================================
function on_timer_(){
    //if(!window.IsVisible || ww == 0 || wh == 0)
    //    return;  
    var repaint_1 = false,repaint_2 = false,repaint_3 = false;
    main_or_form  = !main_or_form;
    if(main_or_form){   ///////////////////////////////////////////////////////////
        if(repaint_f1 == repaint_f2 ){
            repaint_f2 = !repaint_f1;
            repaint_1 = true;
        }
        if(time_f.Time > 500){
            time_f.Reset();
            repaint_1 = true;
            form_text_cusor_hiden = !form_text_cusor_hiden;
        }
    }else{              ///////////////////////////////////////////////////////////
        time_dl = time_scroll.Time;
        var delta = (1-Math.pow(0.9,time_dl/9));
        time_scroll.Reset();
        if(form_text_b != form_text &&  time_s.Time > 150){
            time_s.Reset();
            repaint_2 = true;
            form_text_b = form_text;
            time_s.Reset();
            search(form_text);
        }
        var id = check(m_x,m_y);
        
        if(id > -1 && mouse_in && list_dr[id].alpha < 255){
            list_dr[id].alpha += 24*time_dl/16;
            repaint_2 = true;
        }

        
    
        if(scroll < 0)
            scroll = 0;
        else if(scroll + ww > max_scroll)
            scroll = max_scroll - ww;

        if(Math.abs(scroll - scroll_) > 0.4){
            scroll___  += (scroll - scroll___) * delta;
            scroll__  += (scroll___ - scroll__) * delta;
            scroll_  += (scroll__ - scroll_) * delta;
            repaint_2 = true;
        }else
            scroll___ = scroll__ = scroll_ = scroll;
        //ex_length_idx_
        var col_idx_s = Math.max( Math.floor(start/row_count) - 3,0),
            col_idx_e = Math.min(Math.floor(end/row_count) + 2,ex_length_idx.length);
        
        var al_ex = false;
        for(var i = 0;i < ex_length_idx.length;i++){
            if(Math.abs(ex_length_idx[i] - ex_length_idx_[i]) > 0.001){
                ex_length_idx___[i]  += (ex_length_idx[i] - ex_length_idx___[i]) * delta;
                ex_length_idx__[i]  += (ex_length_idx___[i] - ex_length_idx__[i]) * delta;
                ex_length_idx_[i]  += (ex_length_idx__[i] - ex_length_idx_[i]) * delta;  
                al_ex = repaint_2 = true;
            }else
                ex_length_idx___[i] = ex_length_idx__[i] = ex_length_idx_[i] = ex_length_idx[i];
        }
        
        
        if(playlist_ex && Math.abs(playlist_ex.scroll_ - playlist_ex.scroll) > 0.01){
            playlist_ex.scroll___ += (playlist_ex.scroll - playlist_ex.scroll___) * delta;
            playlist_ex.scroll__ += (playlist_ex.scroll___ - playlist_ex.scroll__) * delta;
            playlist_ex.scroll_ += (playlist_ex.scroll__ - playlist_ex.scroll_) * delta;
            al_ex = repaint_2 = true;  
        } else if(playlist_ex){
            playlist_ex.scroll____ = playlist_ex.scroll___ = playlist_ex.scroll__ = playlist_ex.scroll_ = playlist_ex.scroll;
        }
        
        if(playlist_ex && check_ex(m_x,m_y) !=check_ex_old){
            check_ex_old = check_ex(m_x,m_y);
            repaint_2 = true;
        }
        
        end = Math.min(end,list_dr.length);
        start = Math.max(0,start);
        var repaint_temp = repaint_2;
        //fb.trace("time_max_img : " + time_max_img)
        if(time_r.Time > time_reset_loadimg && Math.abs(scroll - scroll_) < postion_load_img * cell){
            var repaint_temp = repaint_2,i = 0;
            if(Math.abs(scroll - scroll_) < 1 && !al_ex)
                end = list_dr.length;
            for(i = start;i < end;i++){
                if(time_scroll.Time > 3) break;
                else if(list_dr[i].state == 3)
                    continue;
                else if(list_dr[i].state == 0 ){
                    var tmp_ = load_image(list_dr[i].pl.Item(0),true);
                    list_dr[i].id = tmp_[0];
                    list_dr[i].string_cache = tmp_[1];
                    if(list_dr[i].id % 1 == 0.5){
                        list_dr[i].img_ = list_img[Math.floor(list_dr[i].id)].img;
                        list_dr[i].state = 2;
                        i--;
                        continue;
                    }else if(list_dr[i].id == -1){
                        list_dr[i].Time = fb.CreateProfiler();
                        list_dr[i].state = -1; 
                    }else if(list_dr[i].id == 0){
                        list_dr[i].state = 3;
                        continue;
                    }else if(list_dr[i].id == -1000){
                        list_dr[i].img_ = tmp_[2];
                        list_dr[i].state = 3;
                        max_load_done = i;
                    }else{
                        repaint_2 = true;
                        time_r.Reset();
                        list_dr[i].state = 1;
                    }
                    break;
                }else if(list_dr[i].state == 2 && list_dr[i].img_){
                    max_load_done = i;
                    list_dr[i].state = 3;
                    list_dr[i].imgcell = Draw_cell(list_dr[i].img_,list_dr[i].name + "\r\n(" + list_dr[i].pl.Count + " Tracks)");
                    repaint_2 = true;
                    break;
                }else if((list_dr[i].state == -1 && list_dr[i].Time.Time > 400 )
                        ||(list_dr[i].state < -1 && list_dr[i].Time.Time > 2000 ) ){//wait to load image from script
                     var tmp_ = load_image(list_dr[i].pl.Item(0),false);
                     list_dr[i].id = tmp_[0];
                     list_dr[i].string_cache = tmp_[1];
                     if(list_dr[i].id > 0){
                        repaint_2 = true;
                        time_r.Reset();
                        list_dr[i].state = 1;                         
                        break;
                     }else{
                         list_dr[i].Time.Reset();
                         list_dr[i].state--;
                         if(list_dr[i].state < -6)
                            list_dr[i].state = 3;
                     }
                }
            }
            
        }
        if(Math.abs(scroll - scroll_) < 1){
            repaint_2 = repaint_temp;
        }

        if(repaint_main1 == repaint_main2){
            repaint_main2 = !repaint_main1;
            repaint_2 = true;        
        }

    }
    //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////  

    if(repaint_1 && repaint_2){
        repaint_f = true;
        repaint_main = true;
        window.Repaint();
    }else if(repaint_1){
        repaint_f = true;
        window.RepaintRect(0,0,ww,text_heigh);
    }else if(repaint_2){
        repaint_main = true;
        window.RepaintRect(0,text_heigh,ww,wh-text_heigh);
    }
}


function repaint(){
    repaint_main1 = repaint_main2;
}

function read_list(reload){
    list = [];
    read_library(reload);
}

function match(input, string){
    var temp = "";
    input = input.toLowerCase();
    string = string.toLowerCase();
    while(input !=(temp = input.replace("  "," ")))
        input  = temp;
    while(string !=(temp = string.replace("  "," ")))
        string  = temp;
    var str = string.split(" ");
    for(var i in str){
        if(str[i] == "" || input !=(temp = input.replace(str[i],"")))
            input = temp;
        else
            return false;
    }
    return true;
}

function search(string){
    list_dr = [];
    var back_s = -1.5;
    
    var bbb = Math.ceil(row_count * ww /cell / 2);
    for(var i in list){
        if(match(list[i].name,string)){
            back_s = list_dr.length;
            list_dr.push(list[i]);
            if(Math.abs(list[i].i - back_s) > row_count * (ww /cell / 2))
                list[i].al = 0;
        }else{
            list[i].i = (back_s - i < row_count)?(back_s + 0.5):i-row_count;
            list[i].al = 0;
        }
    }
    scroll___ = scroll__ = scroll_ = scroll = 0;
    repaint();
    
    ex_al_idx = -1000;
    var max_row_ex = Math.ceil(list_dr.length/row_count) + 1;
    for(var i = 0;i < max_row_ex;i++)
        ex_length_idx___[i] = ex_length_idx__[i] = ex_length_idx_[i] = ex_length_idx[i] = 0;
   
}


function check(x,y){
    if(!mouse_in || y < text_heigh || y > wh - 7)
        return -1;
    var row = Math.floor((y - text_heigh - 4)/cell);//ex_al_idx
    var col = Math.floor((x + scroll_)/(cell*2));
    
    var row_ex_idx = Math.floor(ex_al_idx/row_count);
    if(playlist_ex && (col == row_ex_idx + 1 || col == row_ex_idx + 2)){
        //cell * 1.6 + y + 20*i - playlist_ex.scroll_ * 20;
        //playlist_ex
        var track_idx = Math.floor((y - (1.6*cell + 20))/20 + playlist_ex.scroll_);
        if(track_idx > -1 && track_idx < playlist_ex.list.length){
            return (-1.500 - track_idx/1000);
        }else return -1.1;
    }else if( playlist_ex && ex_al_idx > -1 && col > row_ex_idx + 2){
        col -= ex_length_idx[col];
    }
    if(row  < 0 || row > row_count-1)
        return -1;
    var index = row + row_count * col;
    if(index <  list_dr.length && index >=0){
        return Math.floor(index);
    }else 
        return -1;
}

//===========================================================================================
function on_mouse_wheel(step){
    if(utils.IsKeyPressed(0x11)){
        var scroll_t = Math.floor(scroll/cell/2) * row_count;
        row_count -= step;
        row_count = Math.max(1,row_count);
        row_count = Math.min(10,row_count);
        window.SetProperty("Row",row_count);

        cell = Math.floor((wh - text_heigh - 12)/row_count);
        scroll____ = scroll__ = scroll_ = scroll = Math.round(scroll_t/row_count) * cell * 2;
        max_scroll = scroll_ + ww;
        repaint_f1 = repaint_f2;
        repaint();
        return;
    }else if(check_ex(m_x,m_y) > -2){
        scr_tmp = playlist_ex.scroll;
        scr_tmp -= step * 2;
        scr_tmp = Math.min(scr_tmp,playlist_ex.list.length - playlist_ex.max_idx);       
        scr_tmp = Math.max(0,scr_tmp);
        if(scr_tmp != playlist_ex.scroll){
            playlist_ex.scroll = scr_tmp;
            return;
        }else if(playlist_ex.scroll != playlist_ex.scroll_){
            return;
        }
    }
    scroll -= step * cell *2;
    var al_ex = 0;//.delta
    if(playlist_ex && playlist_ex.delta > 0) al_ex = playlist_ex.delta;
    //fb.trace(al_ex)
    if(scroll < 0 ||  Math.round(list_dr.length / row_count + 0.499 + al_ex) * (cell*2) < ww)//||  Math.round(list_dr.length / row_count + 0.499) * (cell*2) < ww
        scroll = 0;
    if(scroll > max_scroll - ww)
        scroll = max_scroll - ww;

    //time_reset_loadimg = 15;
}
function check_ex(x,y){
    var a = check(x,y);
    if(a <= -1.5)
        return Math.round((-a-1.5)*1000);
    else if(a == -1.1)
        return - 1;
    else 
        return -2;
}

//================================================================================ On mouse dbclk
function on_mouse_lbtn_dblclk(x,y,mask){
    var a = check(x,y);
    if(a > -1){
        switch(list_dr[a].type){
            case "pl":
         
            break;
            case "al":
                add_playlist(list_dr[a].pl);
                //apply_playlist(list_dr[a].pl);
                //on_mouse_lbtn_down(x,y,mask);
            break;
        }
    }else if(a <= -1.5){
        var idx = Math.round((-a-1.5)*1000);
        if(playlist_ex){
            apply_playlist(playlist_ex.pl,idx);
        }
    }else if(y < text_heigh && x < ww - text_heigh){
        on_mouse_lbtn_down(x,y,1.5);
    }
        
}

//========================================================================================= Album List
function init_album_playlist(pl,idx){
    var text_render = gdi.CreateStyleTextRender();
    
    var ob = new Object();
    var TrackTitleFormat = fb.TitleFormat("[%tracknumber%] ^^ $caps(%title%) ^^ $caps(%artist%)");
    var pllength = pl.pl.Count;
    ob.list = [];
    ob.ob = pl;
    ob.name = pl.name.split("\r\n")[1];
    ob.artist  = pl.name.split("\r\n")[0];
    ob.idx = idx; 
    ob.pl = pl.pl;
    ob.tr_c = pl.pl.Count;
    ob.scroll = 0;ob.scroll_ = 0;ob.scroll__ = 0;ob.scroll___ = 0;
    ob.pl.OrderByFormat(fb.TitleFormat("%tracknumber% - %title%"),1);
    if(fb.IsPlaying)
        ob.nowplaying = ob.pl.Find(fb.GetNowPlaying());
    ob.col_idx = Math.floor(idx/row_count);
    pl.pl.img_ && (ob.img = pl.pl.img_.Resize(cell * 1.4,cell * 1.4,7).CreateRawBitmap());
    ob.x = 0;ob.y = 0;ob.w = 0;ob.h = 0;
    for(var i = 0;i < pllength;i++){
        var info = TrackTitleFormat.EvalWithMetadb(ob.pl.Item(i)).split(" ^^ ");
        ob.list[i] = new Object();
        ob.list[i].chose = false;
        var imgtemp = gdi.CreateImage(cell * 4, 20);
        var gp = imgtemp.GetGraphics();
        gp.SetTextRenderingHint(3);
        gp.SetSmoothingMode(4);
        gp.SetInterpolationMode(7);
        text_render.GlowText( 0xffffffff|0x00 , 0xffffffff|0x00, 0);    
        text_render.RenderStringRect(gp, info[0] , g_font_al1, 08, 0, 20, 20, 0);
        text_render.GlowText( 0xffffffff|0x00 , 0x00ffffff|0x00, 0); 
        text_render.RenderStringRect(gp, info[1] , g_font_al1, 45, 0, cell*2.8, 20, 0);
        text_render.GlowText( 0xffffffff|0x00 , 0x00ffffff|0x00, 0); 
        text_render.RenderStringRect(gp, info[2] , g_font_al1, cell*3.0, 0, cell * 0.9, 20, 1);
        imgtemp.ReleaseGraphics(gp);
        ob.list[i].tr_render = DrawBitmap ? imgtemp.CreateRawBitmap() : imgtemp.Clone(0,0,imgtemp.Width,imgtemp.Height);
        ob.list[i].tr = info[0];ob.list[i].tl = info[1];ob.list[i].ar = info[2];
    }
    ob.max_idx = Math.floor(cell * (row_count - 1.6)/20);
    fb.trace(ob.max_idx);
    return ob;
}

//========================================================================Selected Album
function draw_album_playlist(gr,ob,x,y,w,h){
    ob.x = x + cell * 1.6;ob.y = y-5;ob.w = w - cell * 1.6;ob.h = h;
    var list_lg = ob.list.length;
    gr.SetTextRenderingHint(3);
    gr.SetSmoothingMode(4);
    gr.SetInterpolationMode(7);
    var tmp = check_ex(m_x,m_y);
    var delta = (w + 3) /2 /cell;
    var y_ = cell * (ob.idx%row_count + 0.5) + text_heigh + 4 ;
    var thx = x+1,thy = y_,ver = cell * 0.125 * delta;
    var point = [x,y + 7,thx,thy-ver + 7,thx - ver,thy + 7,thx,thy + ver + 7,x,y+h + 6,x + w,y + h + 6,x + w,y + 7];
    gr.FillPolygon(0x60000000,0,point);//cover_back_color 0x60000000
    if(ob.img){
        gr.GdiAlphaBlend(ob.img,x+3,y+9,Math.min(cell * 1.4,(w - 10)), cell*1.3,0,0,Math.min(cell * 1.4,(w - 10)),cell * 1.4,255);
        ob.ob.img_ && gr.DrawImage(ob.ob.img_,x+3,y+9,Math.min(cell * 1.4,(w - 10)),cell*1.3,0,0,ob.ob.img_.Width * Math.min(1,(w - 10)/cell/1.4),ob.ob.img_.Height,0,255);
    }else if(ob.ob.img_){
        ob.img = ob.ob.img_.Resize(cell * 1.4,cell * 1.4,7).CreateRawBitmap();
    }else if(stub_image){
        gr.DrawImage(stub_image,x+5,y+7,Math.min(cell * 1.4,(w - 10)),cell*1.4,0,0,stub_image.Width * Math.min(1,(w - 10)/cell/1.4),stub_image.Height,0,255);
    }
    gr.GdiDrawText(ob.name,g_font_al2,0xffffff,x + 5 + cell * 1.5,y + 15,w - cell * 1.6,30,0x8000);//0xffffff    
    gr.GdiDrawText(ob.artist,g_font_al3,0xffffff,x + 5 + cell * 1.5,y + 45,w - cell * 1.6,30,0);
    gr.GdiDrawText(ob.tr_c + " Tracks",g_font_al4,0xaaaaaa,x + 5 + cell * 1.5,y + 65,w - cell * 1.6,30,0);//0xaaaaaa
    for(var i = 0;i < list_lg;i++){
        y_ = cell * 1.6 + y + 20*i - ob.scroll_ * 20;
        if(y_ > h) break;
        else if(y_ < cell * 1.6 + 10) continue;
        var render = ob.list[i].tr_render
        var img_w = Math.min(render.Width,w),img_h = render.Height;
        var y_1 = Math.max(y_,cell * 1.6 + 10),
            y_2 = Math.min(h + 20,y_ + 20),
            y_w = y_2 - y_1;
            
        if(ob.list[i].chose){
            gr.FillGradRect( x + 3, y_, w - 6, 20, 0, RGBA(255,255,255,40), RGBA(255,255,255,80));//RGBA(255,255,255,40), RGBA(255,255,255,80));
        }else if(playlist_ex.nowplaying == i){
            gr.FillGradRect( x + 3, y_, w - 6, 20, 0, RGBA(255,255,255,40), RGBA(255,255,255,80));//RGBA(255,255,255,40), RGBA(255,255,255,80));
        }
        //if()playlist_ex.nowplaying
        DrawBitmap && gr.GdiAlphaBlend(ob.list[i].tr_render,x,y_1,img_w, y_w,0,0,img_w,y_w,255);
        !DrawBitmap && gr.DrawImage(ob.list[i].tr_render,x,y_1,img_w, y_w,0,0,img_w,y_w,0,255);
    }
    
    /*
    if(list_lg > ob.max_idx){
        var st = y + cell * 1.6 - 5,ed = y + h - 5,
            st2 = st + cell * (row_count - 1.6) * ob.scroll_ / list_lg,
            ed2 = st + cell * (row_count - 1.6) * (ob.scroll_ + ob.max_idx) / list_lg;
        gr.DrawLine(x + w - 5,st,x + w - 5,ed,7,0x30000000);
        gr.DrawLine(x + w - 5,st2,x + w - 5,ed2,5,0x50ffffff);
    }*/
    
    if((ob.scroll * 20 > 0) && (cell * 1.6 + y  + 20 * list_lg - ob.scroll * 20 < h))
        ob.scroll--;
}

function read_library(reload){
    var Time = fb.CreateProfiler("Time Load library");
    var TitleFormat = "[%album artist%]^^[%album%]";
    var FoobarTitleFormat = fb.TitleFormat(TitleFormat);
    var pl_name = "", pl_idx = -1,list_;
    for(var i=0; i < plman.PlaylistCount; i++) {
        pl_name = plman.GetPlaylistName(i);
        if(pl_name == "WSH Album Filter") {
            pl_idx = i;
            break;
        }
    }
	if(pl_idx < 0) {
        pl_idx = plman.PlaylistCount;
        fb.CreateAutoPlaylist(pl_idx,"WSH Album Filter","ALL",TitleFormat);
		list_ = plman.GetPlaylistItems(pl_idx);
    }else if(reload){
        fb.RemovePlaylist(pl_idx);
        fb.CreateAutoPlaylist(pl_idx,"WSH Album Filter","ALL",TitleFormat);
		list_ = plman.GetPlaylistItems(pl_idx);
    }else
		list_ = plman.GetPlaylistItems(pl_idx);
    var string_compare = "123456789123456789",string = "",k = 0,i = 0,item,count = 0;
    var a = "",b = "",tmp,total = list_.Count;
    Time.print();Time.Reset();
    while(k < total){
        string = FoobarTitleFormat.EvalWithMetadb(list_.Item(k));
        tmp = string.split("^^");
        a = tmp[0];b = tmp[1];
        if(a.length < 3){
            k++;
            continue;
        }
        if(string_compare != string){
            string_compare = string;
            item = new Object();
            item.name = a + "\r\n" + b;
            item.type = "al";
            item.al = 255;
            item.i = list.length - 3;
            item.i_ = item.i;
            item.alpha = 0;
            item.state = 0;
            item.id = 0;
            item.img = null;
            item.pl = plman.GetPlaylistItems(-1);
            item.pl.Add(list_.Item(k));
            count = 1;
            (min_song == 1) && list.push(item);
        }else{
            count++;
            item.pl.Add(list_.Item(k));
            if(count == min_song)
                list.push(item);
        }
        k++;
    }
    time_scroll.Reset();
    Time.print();
}

//=================================================== add apply to playlist
function apply_playlist(playlist,start){
    var pl_idx = check_playlist("Library view");
    if(pl_idx == -1){
        pl_idx = fb.PlaylistCount; 
        fb.CreatePlaylist(pl_idx,"Library view");
    }else
        fb.RunMainMenuCommand("Edit/Clear");
    fb.ActivePlaylist = pl_idx;    
    var playlist_ = playlist.Clone();
    //!start && playlist_.OrderByFormat(fb.TitleFormat("$if([%album artist%],%album artist%,zzzz)|$if([%album%],[%date%]%album%,zzzz)|$if(%track number%,%track number%,zzzz)|$sub(5,%rating%)|%title%"),1);
    !start && playlist_.OrderByFormat(fb.TitleFormat("%path%"),1);
    plman.InsertPlaylistItems(pl_idx,1,playlist_);
    plman.ExecutePlaylistDefaultAction(pl_idx,start?start:0);
    fb.RunMainMenuCommand("Edit/Remove Duplicates");
}

function add_playlist(playlist){
    var pl_idx = check_playlist("Library view");
    fb.ActivePlaylist = pl_idx;
    playlist.OrderByFormat(fb.TitleFormat("%path%"),1);
    //plman.InsertPlaylistItems(fb.ActivePlaylist,plman.PlaylistItemCount(fb.ActivePlaylist),playlist);
    plman.InsertPlaylistItems(fb.ActivePlaylist,0,playlist);
    plman.ExecutePlaylistDefaultAction(pl_idx,0);
    fb.RunMainMenuCommand("Edit/Remove Duplicates");
}

function on_mouse_mbtn_up(x,y,mask){
    var a = check(x,y);
    if(a > -1){
        switch(list_dr[a].type){
            case "pl":
            break;
            case "al":
                add_playlist(list_dr[a].pl);
            break;
        }
    }
}

var textrender = gdi.CreateStyleTextRender();
textrender.EnableShadow(true);
//textrender.GlowText( 0xffffffff|0x00 , 0x00ffffff|0x00, 0);
textrender.GlowText( text_color|0x00 , 0x00ffffff|0x00, 0); //======================= Text color
textrender.DiffusedShadow(RGBA(0,0,0,50)|0x0,1,1,1);
   
//=============================================================Album Art  
function Draw_cell(image,string){
        if(cell_null?(cell_null.Width != cell * 2-3):true)
            install_cell();
        var tmp_img = cell_null.Clone(0,0,cell * 2-3, cell-3);
        var gp = tmp_img.GetGraphics();
        gp.SetTextRenderingHint(3);
        gp.SetSmoothingMode(4);
        gp.SetInterpolationMode(7);
        image && gp.DrawImage(image,3, 2, cell+15, cell-7, 0, 0, image.Width, image.Height, 0,255);
        textrender.RenderStringRect(gp, string , g_font_c, cell + 35, 10, cell - 40, cell, 0);
        return DrawBitmap ? tmp_img.CreateRawBitmap() : tmp_img;
    }

function on_load_image_done(tid,image){
    for(var i in list){
        if(!list[i].id) continue;
        if(list[i].id == tid && list[i].state == 1){
            list[i].state = 2;
            list[i].img_ = image;
            repaint_main1 = repaint_main2;
            var img_cache = new Object();
            img_cache.img = image;
            img_cache.string = list[i].string_cache;
            list_img.push(img_cache);
            break;
        }
    }
}

var notifi_nostub_img = false;

function install_cell(){
    try{
        stub_image = gdi.Image(window.GetProperty("Stub_Image_Path",".\\themes\\album_stub.png"));
    }catch(err){
        stub_image = null;
    }
    cell_null = gdi.CreateImage(cell * 2-3, cell-3);
    var gp = cell_null.GetGraphics();
    gp.SetTextRenderingHint(3);
    gp.SetSmoothingMode(4);
    gp.SetInterpolationMode(7);
    gp.FillGradRect(0,0,cell * 2-3, cell-3,45,cover_back_color,back_shadow_color,1);//0x55000000,0x33000000,1); //================ cover back cover
    stub_image && gp.DrawImage(stub_image,1, 1, cell - 5, cell - 5, 0, 0, stub_image.Width ,stub_image.Height, 0,255);
    cell_null.ReleaseGraphics(gp);
    cell_null_gr = DrawBitmap ? cell_null.CreateRawBitmap() : cell_null;
}



function on_mouse_rbtn_up(x, y){
    var MF_SEPARATOR = 0x00000800;
    var MF_STRING = 0x00000000;
    var _menu = window.CreatePopupMenu();
    var _menu1 = window.CreatePopupMenu();
    var Context = fb.CreateContextMenuManager();
    var idx;
    if(y < text_heigh){
        (form_his.length > 0)   && _menu.AppendMenuItem(MF_STRING, 1, "Undo  ");
        (form_his_.length > 0)  && _menu.AppendMenuItem(MF_STRING, 2, "Redo  ");
        (bold_start != bold_end)&& _menu.AppendMenuItem(MF_STRING, 3, "Coppy ");
        (bold_start != bold_end)&& _menu.AppendMenuItem(MF_STRING, 4, "Cut   ");
        (htmlfile.parentWindow.clipboardData.getData('text') != null) && _menu.AppendMenuItem(MF_STRING, 5, "Paste ");
    }else{
        var check__  = check(x,y);
        if(check__ > -1) {
            Context.InitContext(list_dr[check__].pl);
            Context.BuildMenu(_menu, 100, -1);
            on_mouse_move(x,y);
        }
    }
    _menu1.AppendMenuItem(MF_STRING, 8, "Refresh library");
    _menu1.AppendMenuItem(MF_STRING, 7, "Show Properties ");
    _menu1.AppendMenuItem(MF_STRING, 6, "Show Script");
    _menu.AppendMenuSeparator();
    _menu1.AppendTo(_menu,MF_STRING, "Preferences");
    idx = _menu.TrackPopupMenu(x,y);
    switch(idx) {
        case 0:break;
        case 1:
            on_char(26);
            break;
        case 2:
            on_char(25);
            break;          
        case 3:
            on_char(3);
            break;
        case 4:
            on_char(24);
            break;
        case 5:
            on_char(22);
            break;
        case 6:
            window.ShowConfigure();
            break;  
        case 7:
            window.ShowProperties();
            break;
        case 8:
            read_list(true);
            search(form_text);
        break;
        default:
            (idx > 0) && Context.ExecuteByID(idx - 100);
        break;
    }
    Context.Dispose();
    _menu.Dispose();
    return true;
}

function check_playlist(name){
    var pl_name = "", pl_idx = -1;
    for(var i=0; i < plman.PlaylistCount; i++) {
        pl_name = plman.GetPlaylistName(i);
        if(pl_name == name) {
            pl_idx = i;
            break;
        }
    }
    return pl_idx;
}


function getpath(path){
    var img_path = "";
    var path_,temp,subFlds,tmp;
    for(var iii = 0;iii<2;iii++){
        if(tmp = getpath_(iii==0?path:(path + "..\\")))
            return tmp;
        try{
        subFlds = new Enumerator(fso.GetFolder((iii==0?path:(path + "..\\"))).SubFolders);
        }catch(err){return null};
        for (; !subFlds.atEnd(); subFlds.moveNext()) {
            temp = subFlds.item()+"\\";
            if(temp.toLowerCase().match(cover_path)){
                if(tmp = getpath_(temp))
                    return tmp;
            }
        }
    }
    return null;
}

function getpath_(temp){
    var img_path = "",path_;
    for(var iii in cover_img){
        path_ = utils.Glob(temp + cover_img[iii]).toArray();
        for(var j in path_){
            if(path_[j].toLowerCase().indexOf(".jpg") > -1 || path_[j].toLowerCase().indexOf(".png") > -1 ||path_[j].toLowerCase().indexOf(".gif") > -1 ){
                return path_[j];
            }
        }
    }
    return null;
}


function load_imagecache(string){
    for(var i = 0;i < list_img.length;i++){
        if(list_img[i].string == string)
            return i;
    }
    return -1;
}


function load_image(metadb,first,path_){
    if(!path_){
        var tran = false;
        var path = fb.TitleFormat("$directory_path(%path%)\\").EvalWithMetadb(metadb);
        path_ = getpath(path);
        if(!path_)
            path_ = getpath_(fb.FoobarPath + "cache\\artist_pic\\" + fb.TitleFormat("[%artist%]\\").EvalWithMetadb(metadb));
        if(!path_){
            return 0;
        }
    }
    
    var string = processpath(path_),
        tmp = load_imagecache(string);
        
    if(tmp > -1){
        time_reset_loadimg = 0;
        return Array(tmp + 0.5,string);
    }else if(fso.FileExists(fb.FoobarPath + "cache\\album\\" + string)){ //Image cache
        time_reset_loadimg = 0;
        if(Load_async)
            return Array(gdi.LoadImageAsync(window.ID,fb.FoobarPath + "cache\\album\\" + string),string);
        else {
            var img = gdi.Image(fb.FoobarPath + "cache\\album\\" + string);
            var img_cache = new Object();
            img_cache.img = img;
            img_cache.string = string;
            list_img.push(img_cache);
            return Array(-1000,string,img);
        }
    }else if(first && fso.FileExists(path_)){ //jscript resize and save image cache
        var comm = "wscript //E:jscript \"" + fb.FoobarPath + "cache\\LoadIMG.js\" \""
            + fb.FoobarPath + "\" \""+ path_ + "\" \"" + string + "\" \"" + tran + "\"";
        WshShell.Run(comm,false,false);
        time_reset_loadimg = 150;
        return Array(-1,string);
    }
    return Array(0,string);
}


function processpath(path){
    var str_return = "";
    path = path.toLowerCase();
    var length = path.length;
    for(var i  = 0;i < length; i++){
        var charcode = path.charCodeAt(i);
        if(charcode > 96 && charcode < 123)
            str_return += path.charAt(i);
        else if(charcode > 47 && charcode < 58)
            str_return += path.charAt(i);
        else if(charcode == 46)
            str_return += path.charAt(i);
    }
    return str_return;
}

var nowmetadb = null;
function on_playback_new_track(metadb){
    nowmetadb = metadb;
    if(playlist_ex){
        playlist_ex.nowplaying = playlist_ex.pl.Find(metadb);
        repaint();
    }
}

function on_playback_stop(reason){
    nowmetadb = null;
    playlist_ex && (playlist_ex.nowplaying = -1);
}




function on_load(){
    var fso = new ActiveXObject("Scripting.FileSystemObject");
    if(!fso.FolderExists(fb.FoobarPath + "cache"))
        fso.CreateFolder(fb.FoobarPath + "cache");
    if(!fso.FolderExists(fb.FoobarPath + "cache\\album"))
        fso.CreateFolder(fb.FoobarPath + "cache\\album");
    if(!fso.FileExists(fb.FoobarPath + "cache\\LoadIMG.js")){
        var data = "var fso = new ActiveXObject(\"Scripting.FileSystemObject\");\r\n"
         + "var Img = new ActiveXObject(\"WIA.ImageFile.1\");\r\n"
         + "var IP = new ActiveXObject(\"WIA.ImageProcess.1\");\r\n"
         + "IP.Filters.Add(IP.FilterInfos(\"Scale\").FilterID);//ID = 1\r\n"
         + "IP.Filters.Add(IP.FilterInfos(\"Crop\").FilterID);//ID = 2\r\n"
         + "IP.Filters.Add(IP.FilterInfos(\"Convert\").FilterID);//ID = 3\r\n"
         + "function resize_image(path,string,tranparent)\r\n"
         + "{\r\n"
         + "    var cachesize = 300;\r\n"
         + "    var img_w = cachesize,img_h = cachesize,cr_x = 0,cr_y = 0;\r\n"
         + "    try{\r\n"
         + "    Img.LoadFile(path);\r\n"
         + "    }catch(err){\r\n"
         + "		return false;\r\n"
         + "    }\r\n"
         + "    if (Img.Width > Img.Height){\r\n"
         + "        img_w *= Img.Width / Img.Height;\r\n"
         + "        cr_x = (img_w - img_h)/2;\r\n"
         + "    }else {  \r\n"
         + "        img_h *= Img.Height / Img.Width;\r\n"
         + "        cr_y = (img_h - img_w)/2;\r\n"
         + "    }\r\n"
         + "    IP.Filters(1).Properties(\"MaximumWidth\") = img_w;\r\n"
         + "    IP.Filters(1).Properties(\"MaximumHeight\") = img_h;\r\n"
         + "    if(tranparent == \"true\"){\r\n"
         + "        IP.Filters(3).Properties(\"FormatID\").Value = '{B96B3CAF-0728-11D3-9D7B-0000F81EF32E}';\r\n"
         + "    }else{\r\n"
         + "        IP.Filters(3).Properties(\"FormatID\").Value = '{B96B3CAE-0728-11D3-9D7B-0000F81EF32E}';\r\n"
         + "        IP.Filters(3).Properties(\"Quality\").Value = 100; \r\n"
         + "    }\r\n"
         + "    IP.Filters(2).Properties(\"Left\") = cr_x;\r\n"
         + "    IP.Filters(2).Properties(\"Top\") = cr_y;\r\n"
         + "    IP.Filters(2).Properties(\"Right\") = cr_x;\r\n"
         + "    IP.Filters(2).Properties(\"Bottom\") = cr_y;\r\n"
         + "    Img = IP.Apply(Img);\r\n"
         + "    try{\r\n"
         + "        if(fso.FileExists(WScript.arguments(0) + \"cache\\\\album\\\\\" + string))\r\n"
         + "            fso.DeleteFile(WScript.arguments(0)+ \"cache\\\\album\\\\\" + string);\r\n"
         + "        Img.SaveFile(WScript.arguments(0) + \"cache\\\\album\\\\\" + string);\r\n"
         + "    }catch(err){\r\n"
         + "		return false;\r\n"
         + "    }\r\n"
         + "	return true;\r\n"
         + "}\r\n"
         + "resize_image(WScript.arguments(1),WScript.arguments(2),WScript.arguments(3));";
        var file = fso.CreateTextFile(fb.FoobarPath + "cache\\LoadIMG.js", true,65001);
        file.WriteLine(data);
        file.Close();
    }

}

on_load();
var t____ = window.SetTimeout(function(){
    window.ClearTimeout(t____);
    read_list();
    search("");
    
},200);

function on_library_items_added(){
            read_list(true);
            search(form_text);
    }
function on_library_items_removed(){
            read_list(true);
            search(form_text);
    }