KDV / Говноконтактик media download

// ==UserScript==
// @id             Guanokontaktik-media-download
// @name           Говноконтактик media download
// @version        1.0
// @namespace      gk.media.dl
// @author         KDV
// @description    
// @include        http://vk.com/audios*
// @run-at         document-idle
// ==/UserScript==

addLink = function(destElement, urlConfig){
	if(!document.getElementById(urlConfig.id)){
		var el = document.createElement('span');
		el.innerHTML = ' ';
		destElement.insertBefore(el, destElement.children[0]);
	
		el = document.createElement('a');
		el.href = urlConfig.href;
		el.id = urlConfig.id;
		el.innerHTML = '<B style="color: red">' + urlConfig.text + '</B>';
		
		//destElement.appendChild(el);
		destElement.insertBefore(el, destElement.children[0]);
	} else {
		console.log('Item exists: ' + urlConfig.id);
	}
}

guessTarget = function(data_item){
	var tgs = data_item.parentNode.parentNode.children;
	
	for(var k = 0; k < tgs.length; k++){
		if(tgs[k].className && tgs[k].className.indexOf('info') >= 0){
			return tgs[k].children[0];
		}
	}
	
	return null;
}

populate = function(){
	var items = document.getElementsByTagName("input");

	var item, tgs;
	for (var i = 0; i < items.length; i++) {

		item = items[i];

		if(item.id.startsWith("audio_info")){
		
			addLink(guessTarget(item), { href: item.value, id: 'direct_ref-' + item.id.substring(10), text: 'DL'});
		}
	}
}

setTimeout(populate, 1000);

mu = new MutationObserver(function(mutations) {
	mutations.forEach(function(mutation) {

		if(mutation.addedNodes && mutation.addedNodes.length > 0){
			for(var i = 0; i < mutation.addedNodes.length; i++){
				var id = mutation.addedNodes[i].id;
				if(id.startsWith('audio')){
					// replacing 'audio' prefix with 'audio_info' since dancing around the 'audio_infoXXXXXX' <input> tag
					var tg = document.getElementById('audio_info' + id.substring(5));
					if(tg){
						// Modify item after a timeout, or FF crashes when item modified in handler
						setTimeout(function(){addLink(guessTarget(tg), { href: tg.value, id: 'direct_ref-' + id.substring(5), text: 'DL'});}, 50);
					}
				}
			}
		}
	});    
});

mu.observe(document.getElementById('initial_list'), { childList: true });
mu.observe(document.getElementById('search_list'), { childList: true });