var currentRequest = 0;
var currentResult = 0;
var cachedArtist;
var cachedAlbum;
var lastResult;

var rGoogle;
var tryGoogle = true;
var useWhiteList = false;
var aR = new Array();
var aResult = new Array();
var reswlnum = 0;
var whitelist = new Array("grooveshark.com", "coveralia.com", "jazz.com", "bandzone.cz", "7digital.com", "7static.com", "ecover.to", "deejay.de", "deezer.com", "discogs.com", "djshop.de", "ebreggae.com", "eclassical.com", "textalk.se",
	"esenshop.com", "hitparade.ch", "hmv.ca", "chartstats.com", "itunes.apple.com", "juno.co.uk", "kalahari.com", "audioscrobbler.com", "maniadb.com", "mndigital.com", "mega-media.nl", "metal-archives.com",
	"metallibrary.ru", "nuclearblast.de", "psyshop.com", "qobuz.com", "revhq.com", "musique.sfr.fr", "soundstation.dk", "takealot.com", "theorchard.com", "vgmdb.net", "wantitall.co.za", "yesasia.com", "uulyrics.com");

function WebRequest() {
    this.host = '';
    this.name = '';
    this.className = '';
    this.onSuccess = null;
    this.onFailure = null;
}

function ImageResult() {
    this.imglink = '';
    this.height = '';
    this.width = '';
    this.thumblink = '';
}

function NotifyWebReq(str) {
   var headers = SDB.NewStringList;
   headers.Add( 'User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/31.0.1650.57 Safari/537.36');   
   var Content = SDB.Downloader.GetURLContentEx( str, headers, '');
   if (Content == '') 
     LoadWebPageFailed();
   else
     LoadedWebPage( Content);
}

function NotifyResult(res) {
    lastResult = res.imglink;
     //res.thumblink
     //res.width + 'x' + res.height
}

function NotifyDebug(str) {
  SDB.Tools.OutputDebugString( 'aaSearch.js: '+str)
}

function NotifyEnd() {
    
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////
var rNextGoogle = function () { NotifyDebug('rNextGoogle'); whatNext(); }
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////
var searchSend = function (r, a, t) {
    NotifyDebug('SearchSend');
    var site = r.className;   
    var host = r.host.replace('%artist%', a).replace('%album%', t);
    host = encodeURI(host).replace('%2526', '%26');
    try {
        NotifyWebReq(host);
    } catch (err) { }
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////
var whatNext = function (init) {
    var a; var t;
    if (init) {
        NotifyDebug('whatNext init');
        a = cachedArtist; t = cachedAlbum;
    } else {
        NotifyDebug('whatNext continue');
        a = cachedArtist; t = cachedAlbum;
        currentRequest++;
    }
    if (currentRequest < aR.length) {
        NotifyDebug('Calling search send');
        searchSend(aR[currentRequest], a, t);
    } else
        NotifyEnd();
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////
var AddResult = function (res) {
    NotifyDebug('AddResult');
    var iswl = false;
    if (useWhiteList) {
        for (var i = 0; whitelist[i]; i++) {
            if (res.imglink.search(whitelist[i]) != -1) {
                iswl = true;
                break;
            }
        }
    }
    if (iswl) {
        aResult.splice(reswlnum, 0, res);
        reswlnum++;
    } else {
        aResult.push(res);
    }
    NotifyDebug('AddResult END');
}
var rSuccessGoogle = function (html) {
    NotifyDebug('rSuccessGoogle');
    try {        
        var re = /imgurl=[^>]+>/g;
        var reW = /;w=(\d+)/;
        var reH = /;h=(\d+)/;
        var reTbnid = /;tbnid=([^:]+)/;
        var reImg = /imgurl=([^&]+)&amp/;
        var larray = html.match(re);
        
        if (!larray)
            NotifyDebug('rSuccessGoogle larray is NULL');
        else {
            for (var i = 0; larray[i]; i++) {
                var res = new ImageResult();
                var s = larray[i].match(reImg);
                if (!s)
                    continue;
                res.imglink = decodeURIComponent(s[1]);
                NotifyDebug('rSuccessGoogle 2');
                s = larray[i].match(reW);
                if (!s)
                    continue;
                res.width = s[1];
                NotifyDebug('rSuccessGoogle 3');
                s = larray[i].match(reH);                
                if (!s)
                    continue;
                res.height = s[1];
                NotifyDebug('rSuccessGoogle 4');
                s = larray[i].match(reTbnid);
                if (!s)
                    continue;
                res.thumblink = 'http://tbn0.google.com/images?q=tbn:' + s[1];
                NotifyDebug('rSuccessGoogle 5');
                AddResult(res);
            }
        }
        NotifyDebug('rSuccessGoogle 3');
    } catch (ex) { NotifyDebug(ex.message);}
    if (aResult.length > 0) {
        for (var i = 0; i < aResult.length; i++) {
            if (i == currentResult)
              NotifyResult(aResult[i]);
        }
        NotifyEnd();
        aResult.length = 0;
    } else
        whatNext();
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////
var init = function () {
    NotifyDebug('init');
    aResult.length = 0;
    aR.length = 0;
    reswlnum = 0;
    currentRequest = 0;
    if (tryGoogle) {
        rGoogle = new WebRequest();
        rGoogle.onSuccess = rSuccessGoogle;
        rGoogle.onFailure = rNextGoogle;
        rGoogle.host = 'https://www.google.com/search?safe=active&tbs=iar:s,ift:jpg&q="%artist%"+"%album%"&tbm=isch';        
        rGoogle.sendString = '';
        rGoogle.name = 'Google';
        rGoogle.className = 'Google';
        aR.push(rGoogle);

        // second request - try without quotation marks
        rGoogle = new WebRequest();
        rGoogle.onSuccess = rSuccessGoogle;
        rGoogle.onFailure = rNextGoogle;        
        rGoogle.host = 'https://www.google.com/search?safe=active&tbs=iar:s,ift:jpg&q=%artist%+%album%&tbm=isch';
        rGoogle.sendString = '';
        rGoogle.name = 'Google';
        rGoogle.className = 'Google';
        aR.push(rGoogle);
    }
    whatNext(true);
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////
var SearchAA = function (artist, title) {
    NotifyDebug('SearchAA: Artist: '+artist+' ,Album: '+title+' ,currentResult = '+currentResult);    
    cachedArtist = artist;
    cachedAlbum = title;
    init();  
    currentResult++; // so that next time another image is used            
    return lastResult;
}

var LoadedWebPage = function (webcontent) {
    NotifyDebug('LoadedWebPage');
    if ((currentRequest < aR.length) && (aR[currentRequest].onSuccess != null)) {
        aR[currentRequest].onSuccess(webcontent);
    }
}
var LoadWebPageFailed = function () {
    NotifyDebug('LoadWebPageFailed');
    if ((currentRequest < aR.length) && (aR[currentRequest].onFailure != null)) {
        aR[currentRequest].onFailure();
    }
}