// ==PREPROCESSOR==
// @name "Biography Text && Picture. www.last.fm"
// @feature "v1.4"
// @feature "watch-metadb"
// ==/PREPROCESSOR==

function RGB(r,g,b) { return (0xff000000|(r<<16)|(g<<8)|(b)); }
function RGBA(r,g,b,a) { return ((a << 24) | (r << 16) | (g << 8) | (b)); } 
function getRed(color) {return ((color >> 16) & 0xff);};
function getGreen(color) {return ((color >> 8) & 0xff);};
function getBlue(color) {return (color & 0xff);};

var a_font = gdi.Font("Arial",12, 1);
var b_font = gdi.Font("Arial",12, 0);
var ww,wh;

var on_mouse = false;

DT_LEFT = 0x00000000;
DT_RIGHT = 0x00000002;
DT_CENTER = 0x00000001;
DT_VCENTER = 0x00000004;
DT_SINGLELINE = 0x00000020; 
DT_WORD_ELLIPSIS = 0x00040000;
DT_WORDBREAK = 0x00000010;
DT_CALCRECT = 0x00000400;
DT_NOPREFIX = 0x00000800;

var bgcolor = RGB(30,30,30);
var a_color = RGB(220,220,220);
var b_color = RGB(255,255,230);
var transparent = 200;

var xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); 
var doc = new ActiveXObject("htmlfile");
var fso = new ActiveXObject("Scripting.FileSystemObject"); 
//var Stream = new ActiveXObject("ADODB.Stream");

var tmp_b_path = fb.ProfilePath + "\\tmp_Biography\\";
//if(!fso.FolderExists(tmp_b_path)) {fso.CreateFolder(tmp_b_path)};
var nocover_path = fb.ProfilePath + "nocover.png";

var g_img;
var text = "";
var artist, old_artis;
var files = [], selected = 0;

var txt_x = window.GetProperty("txt_x", window.Width / 2);
var txt_y = window.GetProperty("txt_y", window.Height / 2);

var abc_lang = new Array("", "ru/");
var abc = window.GetProperty("abc", 0);
var if_not_found = new Array(". . .", ". . ."); 

var artist_x;
var artist_y;
var b_x;
var b_y;
var t_margin = 15;
var string_width;
var b_text_row_height = 0;
var b_text_rows = 0;
var b_text_height = 0;

var s_text = 0;
var strings_array = [];
var b_text_array = [];
var delta_x, delta_y;
var k_down = false;
var text_scroll = false;

var limit = window.GetProperty("download_limit",5);
var p_margn = 10;

var metadb;
on_item_focus_change();

var WshShell = new ActiveXObject("WScript.Shell");
var script_path = fb.ProfilePath + "\\tmp_Biography\\download\\";
var vbs = "cscript //nologo \"" + script_path + "download.vbs\""; 


function on_paint(gr){	
	!window.IsTransparent && gr.FillSolidRect(0, 0, ww, wh, bgcolor);

    paint(gr);	

    gr.FillSolidRect(txt_x, txt_y, ww - txt_x, wh - txt_y, RGBA(getRed(bgcolor),getGreen(bgcolor),getBlue(bgcolor),transparent));	

    gr.GdiDrawText(artist, a_font, a_color, artist_x, artist_y, ww - artist_x, wh, DT_LEFT | DT_WORD_ELLIPSIS );	

  for (var i = 0; i < b_text_height; i++) { 	
    gr.GdiDrawText(b_text_array[i + s_text], b_font, b_color, b_x, b_y + b_text_row_height * i, ww, wh, DT_LEFT );	
  }

    var txt_cycle = set_cycle ? cycle + " s" : "";
    gr.GdiDrawText(txt_cycle, a_font, a_color, 30, 30, ww, wh, DT_LEFT | DT_WORD_ELLIPSIS );	

}

function on_mouse_wheel(delta) {
    ShiftDown = utils.IsKeyPressed(0x10) ? true : false;
    
    if (!delay && !text_scroll && !ShiftDown){
        delay = true;
        fdelay();
        get_files_from_dir();  
        if (delta < 0) {selected = selected <= 0 ? files.length - 1 : selected = selected - 1};
        if (delta > 0) {selected = selected >= files.length - 1 ? 0 : selected = selected + 1};
    } 
    if (text_scroll && !ShiftDown){
      if (b_text_rows > b_text_height){ 
        if (delta < 0) {s_text = b_text_rows - s_text <= b_text_height ? b_text_rows - b_text_height : s_text += 1}
        if (delta > 0) {s_text = s_text <= 0 ? 0 : s_text -= 1}
      } 
    }
    
    if (ShiftDown) {
        set_cycle = true;
        if (delta < 0) {cycle = cycle <= 0 ? 0 : cycle - 5;};
        if (delta > 0) {cycle = cycle >= 60 ? 60 : cycle + 5;};
    } 

    window.Repaint();
}

function on_playlist_switch() {
    on_item_focus_change();
}

function on_playback_new_track() {
    on_item_focus_change();
}

function on_playback_dynamic_info_track() {
    on_item_focus_change();
}

function on_playback_stop() {	
    on_item_focus_change();	
}	

function on_selection_changed(metadb) {	
   on_item_focus_change();  	
}	

function on_item_focus_change() {	
	metadb = fb.IsPlaying ? fb.GetNowPlaying() : fb.GetFocusItem();
    if (metadb) on_metadb_changed();	
}	

function Eval(field) {	
    if (!metadb || field == "") return "";	
    path = fb.Titleformat("%path%").EvalWithMetadb(metadb);	
    return path.indexOf('://') > 0 ? fb.TitleFormat("[" + field + "]").Eval(true) : fb.TitleFormat("[" + field + "]").EvalWithMetadb(metadb);
}

//var work = false;

function on_metadb_changed() {    
    artist = Eval("%artist%");
    if (artist != old_artis){
        try {
            fso.deleteFile(tmp_b_path + "*.jpg" );
        } catch(e) {};
        selected = 0;
        s_text = 0;
        //work = false;
        files = [];
    b_text_array = [];
        get_pic();
    old_artis = artist;
    }
    window.Repaint();
}

function get_pic(){
    var url = ("http://www.last.fm/music/" + encodeURIComponent(artist) + "/+images"); 
    xmlhttp.open("GET", url, true);
    xmlhttp.setRequestHeader("If-Modified-Since", "Sat, 1 Jan 2000 00:00:00 GMT");
    xmlhttp.send();
    xmlhttp.onreadystatechange = function () {
        if (xmlhttp.readyState == 4) {
            if (xmlhttp.status == 200) {
                //work = true;                
                doc.open();			
		        var div = doc.createElement("div");	
		        div.innerHTML = xmlhttp.responsetext;	
		        var data = div.getElementsByTagName("img");	
		        var urls = [];	
               			
                for (i = 0; i < data.length; i++) {			
			        if (data[i].src.indexOf("http://img2-ak.lst.fm/i/u/avatar170s") == 0) urls.push(data[i].src.replace("avatar170s", "ar0"));
                }			
                for (i = 1; i < Math.min(urls.length, limit) + 1; i++) {			
                    file = "\"" + tmp_b_path + artist + "_"  + i + ".jpg" + "\"";			
                    WshShell.Run(vbs + " " + urls[i] + " " + file, false); 			
                }			
		        doc.close();	
                //do{
                //    get_files_from_dir();
                //} while (work && files.length == 0);
                get_b_text();  
            } 
        }
    }
}

function get_p(url, i){ 
    xmlhttp.open("GET", url, true);
    xmlhttp.send();
    if (xmlhttp.readyState == 4) {
        if (xmlhttp.status == 200) {
            Stream.Open;
            Stream.Type = 1;
            Stream.Write(xmlhttp.ResponseBody);
            Stream.Position = 0;
            try {
                Stream.SaveToFile(tmp_b_path + artist + "_" + i + ".jpg");
            } catch(e) {};
            Stream.Close;
        }
    }
}

function get_files_from_dir() {
    files = [];
    var e = new Enumerator( fso.GetFolder(tmp_b_path).Files );
    while ( !e.atEnd() ) {
        var name = e.item().Name;
        if (name.indexOf(artist) == 0){
            files.push(tmp_b_path + name);
        }
        e.moveNext();
    }
    window.Repaint();
}


var delay = false;

function fdelay(){
    var delay_timer = window.SetTimeout(function() { 
        delay = false;
        window.Repaint();
    }, 200); 
}

function paint(gr){
    g_img = gdi.Image(files[selected]);  
    if (!g_img){
        try {
            g_img = gdi.Image(nocover_path);  
        } catch(e) {};
    }
    if (g_img){
        var scale_w = (ww - p_margn * 2) / g_img.Width;
        var scale_h = (wh - p_margn * 2) / g_img.Height;
        var scale = Math.min(scale_w, scale_h);
        gr.DrawImage(g_img, p_margn, p_margn, g_img.Width * scale, g_img.Height * scale, 0, 0, g_img.Width, g_img.Height);
    }
}

function on_mouse_move(x, y) {
    on_mouse = true;
    window.SetCursor(32649);
    if (k_down){
        txt_x = x - delta_x ;
        txt_y = y - delta_y; 

        txt_x = txt_x <= 0 ? 0 : txt_x > ww - 50 ? ww - 50: txt_x;
        txt_y = txt_y <= 0 ? 0 : txt_y > wh - 50 ? wh - 50: txt_y;
    }

    if (x  >= txt_x && y  >= txt_y){
        text_scroll = true;
    } else {
        text_scroll = false;
    }
    
    get_b_text_array();
    window.Repaint();
}

function on_mouse_leave() {
    on_mouse = false;
    window.SetCursor(32512);
    window.Repaint();
}

function on_mouse_lbtn_down(x,y){
    if (x  >= txt_x && y  >= txt_y){
        k_down = true;
        delta_x = x - txt_x;
        delta_y = y - txt_y;
    }
}

function on_mouse_lbtn_up(x,y){
    window.SetProperty("txt_x", txt_x);
    window.SetProperty("txt_y", txt_y);
    k_down = false;
}

function on_size(){
    ww = window.Width;   
    wh = window.Height;
    
    txt_x = window.GetProperty("txt_x");
    txt_y = window.GetProperty("txt_y");

    txt_x = txt_x >= ww - 50 && txt_x > 0 ? ww - 50 : txt_x;
    txt_y = txt_y >= wh - 50 && txt_y > 0 ? wh - 50 : txt_y;
    
    get_b_text_array();
}

function get_b_text(){
    if (artist == null) return;
  var url = ("http://www.last.fm/" + abc_lang[abc] + "music/" + encodeURIComponent(artist) + "/+wiki");
  xmlhttp.open("GET", url, true);
  xmlhttp.setRequestHeader("If-Modified-Since", "Sat, 1 Jan 2000 00:00:00 GMT");
  xmlhttp.send();
  xmlhttp.onreadystatechange = function () {
    if (xmlhttp.readyState == 4) {
      if (xmlhttp.status == 200) {
        doc.open();
        var div = doc.createElement("div");
        div.innerHTML = xmlhttp.responsetext;
        var data = div.getElementsByTagName("div");
        for (i = 0; i < data.length; i++) {
          if (data[i].className == "wiki-content") {
            text = strip_tags(data[i].innerHTML);
            break;
          } else {
            text = if_not_found[abc];
          }
        }
        doc.close();
        get_b_text_array(); 
        window.Repaint();
      }
    }
  }
}

function strip_tags(t) {
  doc.open();
  var div = doc.createElement("div");
  div.innerHTML = t.replace(/<[Pp][^>]*>/g, "").replace(/<\/[Pp]>/g, "<br>").replace(/\n/g, "<br>");
  var text = div.innerText;
  doc.close();
  return text;
}

function get_b_text_array() {
    artist_x = txt_x + t_margin;
    artist_y = txt_y + t_margin;
  strings_array = [];
  b_text_array = [];
 
  temp_bmp = gdi.CreateImage(1, 1);
  temp_gr = temp_bmp.GetGraphics();

    b_x = txt_x + t_margin;
    b_y = txt_y + temp_gr.CalcTextHeight("text", a_font) + t_margin * 2;

  b_text_row_height = temp_gr.CalcTextHeight("text", b_font)
  string_width = Math.max(ww - b_x - t_margin, 0);

  strings_array = temp_gr.EstimateLineWrap(text, b_font, string_width).toArray();

  for (var i = 0; i < strings_array.length; i += 2) {
    b_text_array.push(strings_array[i].replace(/^\s+|\s+$/g, ""));
  }
  
  b_text_rows = b_text_array.length;
  b_text_height = Math.ceil((wh - b_y - 20) / b_text_row_height);

  temp_bmp.ReleaseGraphics(temp_gr);
  temp_bmp.Dispose();
  temp_gr = null;
  temp_bmp = null;
}

function on_mouse_rbtn_up (x, y){  
  var _menu = window.CreatePopupMenu();
  var i = 1;

  MF_ENABLED = 0x00000000;
  MF_GRAYED = 0x00000001;
 
  _menu.AppendMenuItem(MF_ENABLED, i++, "EN text");
  _menu.AppendMenuItem(MF_ENABLED, i++, "RU text");
  _menu.CheckMenuRadioItem(1, i, abc + 1);  
 _menu.EnableMenuItem(abc + 1, 1); 
 
  ShiftDown = utils.IsKeyPressed(0x10) ? true : false;
 
//  if (ShiftDown) {
    _menu.AppendMenuItem(0x00000800, 0, 0);
    _menu.AppendMenuItem(0x00000000, 10, "Reload");
    _menu.AppendMenuItem(0x00000800, 0, 0);
    _menu.AppendMenuItem(0x00000000, 20, "Properties");
    _menu.AppendMenuItem(0x00000000, 30, "Configure ...");
//  }

  ret = _menu.TrackPopupMenu(x,y);

  switch (ret) {
  case 1:
    if (metadb){
      abc = 0;
      window.SetProperty("abc", abc);
      text = "";
      get_b_text();
    }
    break;
  case 2:
    if (metadb){
      abc = 1;
      window.SetProperty("abc", abc);
      text = "";
      get_b_text();
    }
    break;
  case 10:
    window.Reload();
    break;
  case 20:
    window.ShowProperties();
    break; 
  case 30:
    window.ShowConfigure(); 
    break; 
 }
  _menu.Dispose(); 
  return true; 
} 		

var cycle = 0;
var set_cycle = false;

var timer = window.SetInterval(on_timer, 1000);
var step = 0;
var dis;

function on_timer(id) {
    ShiftDown = utils.IsKeyPressed(0x10) ? true : false;
    step++; 
    if (files.length == 0) get_files_from_dir();
    if (cycle > 0 && step >= cycle && !ShiftDown){
        selected = selected >= files.length - 1 ? 0 : selected = selected + 1;
        window.Repaint();
        step = 0;
    }
    
    if (!ShiftDown) {
        dis--;
        if (dis <= 0){
            set_cycle = false;
            window.Repaint();
        }
    } else {
        dis = 5;
    }
}


