
// Se esta página for aberta como conteúdo de iframe, ajusta hash
(function() {
	if (window.name === 'vlWrapper') {
		var	vlWrapper = window.parent,
			newHash = location.href.replace(/http:\/\/[^\/]+/,'');
		if (vlWrapper.location.href.replace(/http:\/\/[^\/]+/,'').replace(/#.*/,'') == newHash) {
			vlWrapper.vagalume.myPlayerTray.trayOff();
			location.href='about:blank';
		} else {
			vlWrapper.location.hash = location.href.replace(/http:\/\/[^\/]+/,'');
			vlWrapper.vagalume.myPlayerTray.lastHash = vlWrapper.location.hash;
		};
	} else {
		var vlWrapper = false;
	}
})();

// chk home
var homechk = new RegExp("^http://[^/]+/$");
var vagalume_home = (homechk.test(document.location)?1:0);

// mobile
var is_mobile = /iphone/gi.test(navigator.userAgent);
if (is_mobile && vagalume_home) {
	var cookieNoMovileRedir = getCookie("no_mobile_redir");
	if (cookieNoMovileRedir !== "true") {
		// verificação #no_mobile_redir
		if (/\#no\_mobile\_redir/gi.test(location.href)) {
			// se veio do m. com o parâmetro #no_mobile_redir e ainda não possui o cookie, ele cria o cookie
			setCookie("no_mobile_redir", "true", (5 * 365 * 24), "/");
		} else {
			// caso seja um mobile, redireciona para o m.vagalume.com
			location.href = "http://m.vagalume.com/";
		}
	}
};

// variaveis estaticas
var static1 = "http://static1.vagalume.com.br";
var static2 = "http://static2.vagalume.com.br";
var vagalume_1024 = false;
var is_plugin=false;

// Usada para obter dependências em outros scripts
window.requireOnceControl = {};
window.requireOnceControl['scripts'] = {};
(function($) {
        $.requireOnce=function(req,callback,caller) {
		if (! caller) {
			alert('Erro: Verifique chamada requireOnce\nreq: '+req+'\ncallback: '+callback+'\ncaller: '+caller);
		} else {
			if (typeof(req) == "string") {
				req = [req];
			};
			$.requireOnce.startControl(req,callback,caller);
	                setTimeout(function(){$.requireOnce.start(req,caller);},1);
		};
        };
	$.requireOnce.start = function(req,callerJS) {
		$.requireOnce.loadScripts(req);
	};
	$.requireOnce.checkCallback = function(script) {
		var ctrl = window.requireOnceControl['scripts'][script];
		// Verifica os scripts abaixo para ver se está pronto para executar
		if (typeof(ctrl['callback']) == 'object') {
			for (var c in ctrl['callback']) {
				if (typeof(ctrl['callback'][c]) == "object" &&
				    typeof(ctrl['callback'][c]['function']) == "function" &&
				    ctrl['callback'][c]['status'] == "queued") {
					if(typeof(ctrl['callback'][c]['requires']) == 'object') {
						var thisIsClear = 0;
						for (var cReq in ctrl['callback'][c]['requires']) {
							if (isClear(ctrl['callback'][c]['requires'][cReq])) {
								thisIsClear++;
							};
						};
						if (thisIsClear >= ctrl['callback'][c]['requires'].length && ctrl['callback'][c]['status'] == "queued") {
							ctrl['callback'][c]['status'] = "executed";
							ctrl['callback'][c]['function']();
						};
					};
				};
				checkPreviousScripts(ctrl['requiredby']);
			};
		} else {
			// Aqui significa que o script não tem nada para executar, é o último da fila.
			// Vamos checar se podemos executar o script de cima (requiredby)
			checkPreviousScripts(ctrl['requiredby']);
		};

		function isClear (req) {
			var ctrl = window.requireOnceControl['scripts'][req];
			if (ctrl['status'] == "loaded") {
				var ok = true;
				for (var subS in ctrl['requires']) {
					if (! isClear(subS)) {
						ok = false;
						break;
					} else {
						ctrl['requires'][subS] = 2;
					};
				};
				return ok;
			};
			return false;
		};

		function checkPreviousScripts (scripts) {
			for (var s in scripts) {
				$.requireOnce.checkCallback(s);
			};
		};
	};
	$.requireOnce.loadScripts = function(req) {
		var scripts = window.requireOnceControl['scripts'];
		for (var s in req) {
			if (typeof(scripts[req[s]]) == "object") {
				if (scripts[req[s]]['status'] == 'loaded') {
					$.requireOnce.checkCallback(req[s]);
				} else if (scripts[req[s]]['status'] == 'queued') {
					scripts[req[s]]['status'] = 'loading';
					var scp = document.createElement('script');
					scp.charset = 'iso-8859-1';
					scp.type = 'text/javascript';
					scp.id = req[s]; // dominio e pode confundir
					if (typeof(scp.onload) != "object") {
						scp.onreadystatechange = function() {
										if (this.readyState == 'complete' || this.readyState == 'loaded') {
											this.onload();
											this.onreadystatechange = function() {};
										};
									};
					};
					scp.onload = function() {
								window.requireOnceControl['scripts'][this.id]['status'] = 'loaded';
								$.requireOnce.checkCallback(this.id);
							};
					scp.onerror = function() {
								window.requireOnceControl['scripts'][this.id]['status'] = 'error';
								$.requireOnce.checkCallback(this.id);
							};
					if (req[s].substring(0,6) != "http:/") {
						req[s] = req[s];
					};
					scp.src = req[s];
					$('head')[0].appendChild(scp);
				};
			} else {
				scripts[req[s]] = {};
				scripts[req[s]]['status'] = 'error';
			};
		};
	};
	$.requireOnce.startControl = function(req,callback,callerJS) {
		var scripts = window.requireOnceControl['scripts'];
		if (typeof(scripts[callerJS]) != "object") { // Se o caller é chamado por alguem
			scripts[callerJS] = {};
			scripts[callerJS]['status'] = 'loaded'; // Se é caller, é pq foi carregado
			scripts[callerJS]['requiredby'] = {};
			scripts[callerJS]['requires'] = {};
		};
		if (typeof(callback) == "function") { // Se houver alguma função para adicionar ao callback do callerJS
			if (typeof(scripts[callerJS]['callback']) != "object") {
				scripts[callerJS]['callback'] = new Array();
			};
			var addRequires = new Array();
			for (var i in req) {
				if (typeof(req[i]) == "string") {
					addRequires.push(req[i]);
				};
			}
			var newCallback = {};
			    newCallback['function'] = callback;
			    newCallback['status']   = 'queued';
			    newCallback['requires'] = addRequires;
			scripts[callerJS]['callback'].push(newCallback);
		};
		for (var s in req) {
			// scripts: Atualiza array
			if (typeof(scripts[req[s]]) != "object") {
				scripts[req[s]] = {};
				scripts[req[s]]['status'] = 'queued';
				scripts[req[s]]['requiredby'] = {};
				scripts[req[s]]['requires'] = {};
			};
			scripts[req[s]]['requiredby'][callerJS] = 1;
			scripts[callerJS]['requires'][req[s]] = 1;
		};
	};
}) (jQuery);
var vagalume = {
	popbox:{},	// Popup DHTML
	page:{},	// Page content
	menus:{},	// Default Menuitems
	menusmask:{},	// Replacements
	defaults:{	// Padrões do site
		framing:{	// Brilho das fotos
			image:static1+'/images/backgrounds/picframe.png',
			sizedImages:{
				s115x74 : static1+'/images/backgrounds/picframe_115x74.png',
				s220x121: static1+'/images/backgrounds/picframe_220x121.png',
				s404x223: static1+'/images/backgrounds/picframe_404x223.png'
			}
		}
	},
	newItemStamp:function(domExpr,css) {		// Coloca icone "Novo" sobre elementos
		var	domExpr = $(domExpr),
			css = css || {top:0,right:0};
		domExpr.css({position:'relative'});
		/* --- RETIRAR STYLE DA TAG SPAN DEPOIS DE 16/06/2010 */
		$('<span class="newgif" style="right:-7px;top:-1px;background:url(/images/icons/icons_21x21.gif) 0 -641px no-repeat;height:10px;width:21px;position:absolute;z-index:100"></span>').css(css).prependTo(domExpr);
	},
	google:{					// Atributos para publicidade do Google
		dfpBusiness:function(){
			// Informaçoes do usuario
			var uinfo = getCookie('uinfo');
			if(uinfo){
				var splitInfo = uinfo.split('.');
				GA_googleAddAttr("gender",(splitInfo[0]=="M"?"male":"female"));
				GA_googleAddAttr("birthyear",splitInfo[1]);
			};

			// Informações do artista
			if(window.vData && window.vData['banda_url']){
				GA_googleAddAttr("band_descr",window.vData['banda_url']);
			};

			// Informações do estilo
			var songstyle = $('.songstyle dd a');
			if(songstyle.is('a')){
				if(songstyle[0]){
					GA_googleAddAttr("style1",$(songstyle[0]).attr('href').replace('/browse/style/','').replace('.html',''));
				};

				if(songstyle[1]){
					GA_googleAddAttr("style2",$(songstyle[1]).attr('href').replace('/browse/style/','').replace('.html',''));
				};
			};
		}
	}
};
function parse_xml_return (objXML, array_campos) {
        var ret=[],tobj,tobj2;
        if (! objXML) return ret;
        for (var cc=0; cc<array_campos.length; cc++) eval("var "+array_campos[cc]+" = new Array()");
        tobj=objXML.getElementsByTagName("return")[0];
        for (i=0;i<tobj.childNodes.length;i++){
                if (tobj.childNodes[i].nodeName == 'msg') {
                        tobj2=tobj.childNodes[i];
                        for (n=0;n<tobj2.childNodes.length;n++){
                                if (tobj2.childNodes[n].nodeType == 1) {
                                        for (var c=0; c<array_campos.length; c++) {
                                                if (tobj2.childNodes[n].nodeName == array_campos[c]) {
                                                        eval(array_campos[c]+".push(tobj2.childNodes[n].firstChild.nodeValue)");
                                                };
                                        };
                                };
                        };
                };
        };
        for (var cv=0; cv<array_campos.length; cv++) eval("ret["+cv+"] = "+array_campos[cv]);
        return ret;
};

// Replace Static menus
vagalume.geramenus=function (menuname) {
	var html,container;
	if (! vagalume.menus[menuname]) return false;
	var menu = vagalume.menus[menuname];
	var testRE = new RegExp("^http\:");
	switch (menu.type) {
		case 'main':
			html='<ul>';
			for (var t in menu.skel) {
				var tab = menu.skel[t].shift();
				html += '<li><div class="button" area="'+tab.sitearea+'" >'+
						(tab.url ? "<a href='"+tab.url+"'>"+tab.title+"</a>" : tab.title)+
						'</div><ul class="colorSoft hide">';
				for (var i in menu.skel[t]) {
					//Teste criado para caso o link seja externo ir para uma página em branco
					testRE.test(menu.skel[t][i].url) ? lnkVl = "<a href='"+menu.skel[t][i].url+"' target='blank'>" : lnkVl = "<a href='"+menu.skel[t][i].url+"'>";
					html += '<li class="'+(menu.skel[t][i].flag!='normal'?menu.skel[t][i].flag+' ':'')+(i > 0 ? 'plural' : '')+'">'+lnkVl+ menu.skel[t][i].title+'</a></li>';
				}
				html += '</ul></li>';
			}
			html+='</ul>';
			$("#menubar").html(html);			
			break;
		case 'distinct':
			html='<ul title="'+menu.title+'">';
			for (var i=0,ml=menu.skel.length;i<ml;i++) if (! menu.ignore || ! menu.ignore[menu.skel[i].name]) {
				html +=	'<li'+(menu.skel[i].flag!="normal"?' class="'+menu.skel[i].flag+'"':'')+'>'+menu.skel[i].html+'</li>';
			};
			html+='</ul>';
			html = html	.replace(/&amp;/gi,'&')
					.replace(/&lt;/gi,'<')
					.replace(/&gt;/gi,'>')
					.replace(/&quot;/gi,'"')
					.replace(/&#039;/gi,"'");
			if (menu.vars) for (var v in menu.vars)	html = html.replace(RegExp('\\{\\$'+v+'\\}','g'),menu.vars[v]);
			document.getElementById('vlmenu_'+menuname).innerHTML = html;
			break;
	};
	return true;
};

// partners e country
window.partner = location.host.match(RegExp("\.bol\."))? 'BOL' : 'UOL';
var country = "br";
var countrychk = new RegExp("^http://[^/]+\.(br|ar)[/:]");
if (countrychk.test(document.location)) {
	var countrymatch = countrychk.exec(document.location);
	if (countrymatch[1].length == 2) {
		var country = countrymatch[1];
	} else {
		var country = "br";
	};
} else {
	var country = "br";
};

// ad uol
var	d = document,
	DEt = new Date(),
	DEaff = "parvagalume",
	DErand;
DEt = DEt.getTime();
DErand = Math.floor(DEt*1000*Math.random());
if (country == "ar") DEaff = "parvagalumear";

// skyscraper
if (country == "ar" && ! vagalume_home) {
	_adscript = true;
} else if (country == "br" && ! vagalume_home) {
	_adscript = false;
} else {
	_adscript = false;
};

// browser test
var	agt = navigator.userAgent.toLowerCase(),
	is_ie = (agt.indexOf('msie') != -1),
	is_ie5 = (agt.indexOf('msie 5') != -1),
	is_ie6 = (agt.indexOf('msie 6') != -1),
	is_ie7 = (agt.indexOf('msie 7') != -1),
	is_not_firefox1 = (agt.indexOf('firefox/1.0.') != -1),
	is_firefox = (agt.indexOf('firefox') != -1),
	is_opera8 = (agt.indexOf('opera 8') != -1),
	is_opera = (agt.indexOf('opera') != -1 || window.opera),
	is_win = (agt.indexOf('windows') != -1),
	is_linux = (agt.indexOf('linux') != -1),
	is_fedora = (agt.indexOf('fedora/1.0') != -1),
	is_fedora15 = (agt.indexOf('fedora/1.5') != -1),
	is_konqueror = (agt.indexOf('konqueror') != -1),
	is_gecko = (agt.indexOf('gecko') != -1),
	is_netscape = (agt.indexOf('netscape') != -1),
	is_chrome = (agt.indexOf('chrome') != -1),
	is_safari = (agt.indexOf('safari') != -1);

function add_data(art,title) {
	var	script = art=='addband' ? 'addbanda' : 'addmusic' ,
		extra = title != null ? "&titlemusic="+encodeURIComponent(title)+"&action=add" : "",
		art = art ? art : (window.vData && window.vData['bandaID'] ? window.vData['bandaID'] : '');
	if (art!='addband' && art!='addmusic') {
		window.location.href='/'+script+'.php?artistID='+art+extra;
	} else {
		window.open('/'+script+'.php?artistID='+art+extra,'','toolbar=no,width=550,height=500,directories=no,status=yes,scrollbars=yes,resize=no,menubar=no');
	}
};

function add_pointer_fix(id) {
	if ($("#reviewBox-translation")[0]) {
		vagalume.lyrics.correction.add("tab_traducao");
		return void(0);
	};
	window.open('/pointer_fix.php?letraID='+id,'','toolbar=no,width=550,height=500,directories=no,status=yes,scrollbars=no,resize=no,menubar=no');
};

//Remover funcao no dia 20/01 de 2010
function indique_mus(id) {
	send_lyric(id);
};

function cpaste(hidid, print) {
	if (print == 'print'){
		game_palavras(print);
	} else {
		window.open('/cpaste.php?id='+hidid,'','width=550,height=500,toolbar=no,directories=no,status=yes,scrollbars=yes,resizable=yes,menubar=no');
	};
};

function open_popup (file, window, larg, altura, scroll, resize) {
	if (!resize) resize = 'no';
        msgWindow=open(file,window,'directories=no,toolbar=no,location=no,status=no,menubar=no,scrollbars=' + scroll + ',copyhistory=no,resizable='+ resize +',width=' + larg + ',height='  + altura);
        msgWindow.moveTo(screen.width/2-larg/2,screen.height/2-altura/2-20);
};

function BannerShow (ad,pos,Expble) {};

function CreateXmlHttpReq(handler) {
        var xmlhttp = null;
        if (is_ie && !is_opera) { // Prevents ie emulation from opera
	        var control = (is_ie5) ? "Microsoft.XMLHTTP" : "Msxml2.XMLHTTP";
	        try {
			xmlhttp = new ActiveXObject(control);
			xmlhttp.onreadystatechange = handler;
	        } catch(e) {
			alert("You need to enable active scripting and activeX controls");
	        };
	} else {
		xmlhttp = new XMLHttpRequest();
		xmlhttp.onload = handler;
		xmlhttp.onerror = handler;
	};
	return xmlhttp;
};

function DummyHandler() { };

var uniqnum_counter = (new Date).getTime();

function XmlHttpGET(xmlhttp, url) {
	xmlhttp.open('GET', url, true);
	xmlhttp.send(null);
};

function SendRequest(url) {
	var xmlhttp = CreateXmlHttpReq(DummyHandler);
	++uniqnum_counter;
	XmlHttpGET(xmlhttp, url + "&rand=" + uniqnum_counter);
};

function addLoadEvent(func) {
	var oldonload = window.onload;
	if (typeof window.onload != 'function') {
		window.onload = func;
	} else {
		window.onload = function() {
			if (oldonload) oldonload();
			func();
		};
	};
};

var pageTracker;
var IGTracker;
var _gaq = [];
function analytics (loc,url) {
	if (loc == "ar") {
		_gaq.push(function() {
			pageTracker = _gat._createTracker("UA-2854418-2");
			pageTracker._setAllowAnchor(true);
			pageTracker._trackPageview(url);
			pageTracker_sections(pageTracker);
			pageTracker._setDomainName("www.vagalume.com.ar");
		});
	} else {
		//IG 
		_gaq.push(function() {
			IGTracker = _gat._createTracker("UA-3531175-1");
			IGTracker._setAllowAnchor(true);
			IGTracker._trackPageview(url);
			IGTracker._setDomainName("www.vagalume.com.br");
		});
		_gaq.push(function() {
			pageTracker = _gat._createTracker(loc=="plugin"?"UA-2854418-3":"UA-2854418-1");
			pageTracker._setAllowAnchor(true);
			pageTracker_sections(pageTracker);
			pageTracker._trackPageview(url);
			pageTracker._setDomainName("www.vagalume.com.br");
		});
	};
	$.requireOnce(['http://www.google-analytics.com/ga.js'],function(){},'/js.js');
};

function pageTracker_sections (obj) {
	var gender = getCookie("user_gender");
	if (gender == "male" || gender == "female") {
		obj._setVar(gender);
	}
	if (window.vData && window.vData['banda']) {
		obj._setCustomVar(1,'Section','Artistas',3);
		if (window.vData['dync']) {
			obj._setCustomVar(2,'Pags de Artistas',window.vData['dync'],3);
		} else if (window.vData['pointer']) {
			obj._setCustomVar(2,'Pags de Artistas','letra',3);
		} else if ($('#conteudoMeio p.head').html() == 'Artista') {
			obj._setCustomVar(2,'Pags de Artistas','artista',3);
		};
	};
};

function vagaTracker (url) {
	window.vagatracker = 1;
	analytics(country,url);
};

function video_show(type,id,url,width,height,elementId) {
	if (type == "youtube") {
		swf("http://www.youtube.com/v/"+id+"&autoplay=1&color1=0x96BC00&color2=0xccff00&border=1",width,height,null,id,elementId);
	} else if (type == "youtube_noap") {
		swf("http://www.youtube.com/v/"+id+"&color1=0x96BC00&color2=0xccff00&rel=0",width,height,null,id,elementId);
	};
};

function swf(file,width,height,vars,objID,domPlace) {
	var	objID=objID?objID:"",
		content='<object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" codebase="http://fpdownload.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=7,0,0,0" width="'+width+'" height="'+height+'" id="'+objID+'" align="middle" type="application/x-shockwave-flash">'+
			(vars ? '<param name="FlashVars" value="'+vars+'">' : '') +
			'<param name="movie" value="'+file+'" />'+
			'<param name="quality" value="high" />'+
			'<param name="wmode" value="Transparent" />'+
			'<embed src="'+file+'" flashvars="'+vars+'" quality="high" width="'+width+'" height="'+height+'" id="'+objID+'embed" name="flashobj" align="middle" allowScriptAccess="sameDomain" type="application/x-shockwave-flash" wmode="Transparent" pluginspage="http://www.macromedia.com/go/getflashplayer" />'+
			'</object>';
	if (! domPlace) {
		document.write(content);
	} else {
		return $(content).appendTo(domPlace);
	};
};

function lyrics_noload(img) {
	if (typeof(vData) == 'object') {
		document.location = "/search.php?t=let&f=ft&q=" + encodeURIComponent(vData['pointer']);
	};
};

function img_notfound(obj,width,height) {
	var vrfyUtube = new RegExp("(youtube\\.com\\/vi\\/.+)","i");
	if (vrfyUtube.test(obj.src)) {
		var urlstr = obj.src.match(vrfyUtube);
		obj.src = "http://img." + urlstr[1];
	} else {
		obj.src = static1+"/images/youtube-nopreview.gif";
	};
};

function ppc (width, height, channel) {};

function url_encode(strOrig) {
	var str = String(strOrig);
	var hex_chars = "0123456789ABCDEF";
	var noEncode = new RegExp("[a-zA-Z0-9\\_\\-\\.]");
	var n, strCode, hex1, hex2, strEncode = "";
	for(n = 0; n < str.length; n++) {
		if (noEncode.test(str.charAt(n))) {
			strEncode += str.charAt(n);
		} else {
			strCode = str.charCodeAt(n);
			hex1 = hex_chars.charAt(Math.floor(strCode / 16));
			hex2 = hex_chars.charAt(strCode % 16);
			strEncode += "%" + (hex1 + hex2);
		};
	};
	return strEncode;
};

function url_decode(strOrig) {
	var str = String(strOrig);
	var hex_chars = "0123456789ABCDEF";
	var noEncode = new RegExp("[a-zA-Z0-9\\_\\-\\.]");
	var n, strCode, hex1, hex2, strEncode = "";
	i = 0;
	for(n = 0; n < str.length; n++) {
		if (str.charAt(n + i) == "%") {
			var charcode = (hex_chars.indexOf(str.charAt(n + 1 + i)) * 16) + hex_chars.indexOf(str.charAt(n + 2 + i));
			strEncode += String.fromCharCode(charcode);
			i+=2;
		} else {
			strEncode += str.charAt(n + i);
		}
	};
	return strEncode;
};

function htmlentities (string, quote_style, flagDecode) {
	// http://kevin.vanzonneveld.net
	// *     example 1: htmlentities('Kevin & van Zonneveld');
	// *     returns 1: 'Kevin &amp; van Zonneveld'
	// *     example 2: htmlentities("foo'bar","ENT_QUOTES");
	// *     returns 2: 'foo&#039;bar'
	// *     flagDecode: caso TRUE, tira a codificação das entidades.

	flagDecode = (flagDecode !== undefined && flagDecode !== null && flagDecode !== false && flagDecode !== void(0));

	var hash_map = {}, symbol = '', tmp_str = '', entity = '';
	tmp_str = string.toString();

	if (false === (hash_map = this.get_html_translation_table('HTML_ENTITIES', quote_style))) {
		return false;
	}
	hash_map["'"] = '&#039;';
	for (symbol in hash_map) {
		entity = hash_map[symbol];
		var	codeOut	= (flagDecode ? entity : symbol),
			codeIn	= (flagDecode ? symbol : entity);
		tmp_str = tmp_str.split(codeOut).join(codeIn);
	}

	return tmp_str;
};

function get_html_translation_table (table, quote_style) {
    // http://kevin.vanzonneveld.net
    // *     example 1: get_html_translation_table('HTML_SPECIALCHARS');
    // *     returns 1: {'"': '&quot;', '&': '&amp;', '<': '&lt;', '>': '&gt;'}
    
    var entities = {}, hash_map = {}, decimal = 0, symbol = '';
    var constMappingTable = {}, constMappingQuoteStyle = {};
    var useTable = {}, useQuoteStyle = {};
    
    // Translate arguments
    constMappingTable[0]      = 'HTML_SPECIALCHARS';
    constMappingTable[1]      = 'HTML_ENTITIES';
    constMappingQuoteStyle[0] = 'ENT_NOQUOTES';
    constMappingQuoteStyle[2] = 'ENT_COMPAT';
    constMappingQuoteStyle[3] = 'ENT_QUOTES';
 
    useTable       = !isNaN(table) ? constMappingTable[table] : table ? table.toUpperCase() : 'HTML_SPECIALCHARS';
    useQuoteStyle = !isNaN(quote_style) ? constMappingQuoteStyle[quote_style] : quote_style ? quote_style.toUpperCase() : 'ENT_COMPAT';
 
    if (useTable !== 'HTML_SPECIALCHARS' && useTable !== 'HTML_ENTITIES') {
        throw new Error("Table: "+useTable+' not supported');
        // return false;
    }
 
    entities['38'] = '&amp;';
    if (useTable === 'HTML_ENTITIES') {
        entities['160'] = '&nbsp;';
        entities['161'] = '&iexcl;';
        entities['162'] = '&cent;';
        entities['163'] = '&pound;';
        entities['164'] = '&curren;';
        entities['165'] = '&yen;';
        entities['166'] = '&brvbar;';
        entities['167'] = '&sect;';
        entities['168'] = '&uml;';
        entities['169'] = '&copy;';
        entities['170'] = '&ordf;';
        entities['171'] = '&laquo;';
        entities['172'] = '&not;';
        entities['173'] = '&shy;';
        entities['174'] = '&reg;';
        entities['175'] = '&macr;';
        entities['176'] = '&deg;';
        entities['177'] = '&plusmn;';
        entities['178'] = '&sup2;';
        entities['179'] = '&sup3;';
        entities['180'] = '&acute;';
        entities['181'] = '&micro;';
        entities['182'] = '&para;';
        entities['183'] = '&middot;';
        entities['184'] = '&cedil;';
        entities['185'] = '&sup1;';
        entities['186'] = '&ordm;';
        entities['187'] = '&raquo;';
        entities['188'] = '&frac14;';
        entities['189'] = '&frac12;';
        entities['190'] = '&frac34;';
        entities['191'] = '&iquest;';
        entities['192'] = '&Agrave;';
        entities['193'] = '&Aacute;';
        entities['194'] = '&Acirc;';
        entities['195'] = '&Atilde;';
        entities['196'] = '&Auml;';
        entities['197'] = '&Aring;';
        entities['198'] = '&AElig;';
        entities['199'] = '&Ccedil;';
        entities['200'] = '&Egrave;';
        entities['201'] = '&Eacute;';
        entities['202'] = '&Ecirc;';
        entities['203'] = '&Euml;';
        entities['204'] = '&Igrave;';
        entities['205'] = '&Iacute;';
        entities['206'] = '&Icirc;';
        entities['207'] = '&Iuml;';
        entities['208'] = '&ETH;';
        entities['209'] = '&Ntilde;';
        entities['210'] = '&Ograve;';
        entities['211'] = '&Oacute;';
        entities['212'] = '&Ocirc;';
        entities['213'] = '&Otilde;';
        entities['214'] = '&Ouml;';
        entities['215'] = '&times;';
        entities['216'] = '&Oslash;';
        entities['217'] = '&Ugrave;';
        entities['218'] = '&Uacute;';
        entities['219'] = '&Ucirc;';
        entities['220'] = '&Uuml;';
        entities['221'] = '&Yacute;';
        entities['222'] = '&THORN;';
        entities['223'] = '&szlig;';
        entities['224'] = '&agrave;';
        entities['225'] = '&aacute;';
        entities['226'] = '&acirc;';
        entities['227'] = '&atilde;';
        entities['228'] = '&auml;';
        entities['229'] = '&aring;';
        entities['230'] = '&aelig;';
        entities['231'] = '&ccedil;';
        entities['232'] = '&egrave;';
        entities['233'] = '&eacute;';
        entities['234'] = '&ecirc;';
        entities['235'] = '&euml;';
        entities['236'] = '&igrave;';
        entities['237'] = '&iacute;';
        entities['238'] = '&icirc;';
        entities['239'] = '&iuml;';
        entities['240'] = '&eth;';
        entities['241'] = '&ntilde;';
        entities['242'] = '&ograve;';
        entities['243'] = '&oacute;';
        entities['244'] = '&ocirc;';
        entities['245'] = '&otilde;';
        entities['246'] = '&ouml;';
        entities['247'] = '&divide;';
        entities['248'] = '&oslash;';
        entities['249'] = '&ugrave;';
        entities['250'] = '&uacute;';
        entities['251'] = '&ucirc;';
        entities['252'] = '&uuml;';
        entities['253'] = '&yacute;';
        entities['254'] = '&thorn;';
        entities['255'] = '&yuml;';
    }
 
    if (useQuoteStyle !== 'ENT_NOQUOTES') {
        entities['34'] = '&quot;';
    }
    if (useQuoteStyle === 'ENT_QUOTES') {
        entities['39'] = '&#39;';
    }
    entities['60'] = '&lt;';
    entities['62'] = '&gt;';
 
 
    // ascii decimals to real symbols
    for (decimal in entities) {
        symbol = String.fromCharCode(decimal);
        hash_map[symbol] = entities[decimal];
    }
    
    return hash_map;
};

function setCookie(name, value, expires, path, domain, secure) {
	if (expires != null) {
		var datenow = new Date();
		datenow.setTime(datenow.getTime() + Math.round(3600000*expires));
		var expires = datenow.toGMTString();
	}
	var curCookie = name + "=" + escape(value) +
	   ((expires) ? "; expires=" + expires : "") +
	   ((path) ? "; path=" + path : "") +
	   ((domain) ? "; domain=" + domain : "") +
	   ((secure) ? "; secure" : "");
	document.cookie = curCookie;
};

function getCookie(Name) {
	var cookies = document.cookie;
	if (cookies.indexOf(Name + '=') == -1) return null;
	var start = cookies.indexOf(Name + '=') + (Name.length + 1);
	var finish = cookies.substring(start,cookies.length);
	finish = (finish.indexOf(';') == -1) ? cookies.length : start + finish.indexOf(';');
	return unescape(cookies.substring(start,finish));
};

function select_get_letras (banda_descr_url, local, wopen) {
	var myajax = new Ajax('/' + banda_descr_url + '/index.xml','GET','text',true);
	myajax.orig = document.getElementById(local);
	myajax.state4 = function() {
		for (var i=0; i!=1;) {
			if (Ajax) {
			var returned = AjaxGetLetraXMLInfo(myajax.output('xml'));
			if (returned[0].length > 0) {
				var html = "<select id='selectlyrlist' onchange='javascript:";
				if (wopen == '_blank') {
					html += "window.open(this.options[this.selectedIndex].value)";
				} else {
					html += "self.document.location=this.options[this.selectedIndex].value";
				};
				html += ";'>";
				html += "<option>--- ";
				if (country == "ar") {
					html += "Seleccioná";
				} else {
					html += "Selecione";
				};
				html += " ---</option>";
				var searchreplace = new RegExp("^[^\:]+(?:letras)?\s*\:\s*");
				for (var iret = 0; iret < returned[0].length; iret++) {
					html += "<option value='" + returned[0][iret] + "'>";
					html += returned[1][iret].replace(searchreplace,"") + "</option>";
				};
				html += "</select>";
			} else {
				var html = 'Nada';
			};
			myajax.orig.innerHTML = html;
			i = 1;
			} else {
				i = 0;
			};
		};
	};
	myajax.state1 = function() {
		myajax.orig.innerHTML = '<img src="/images/processing.gif" border="0" style="display:inline;" /><b>Carregando...</b></center>';
	};
	myajax.stateError = function() {
		myajax.orig.innerHTML = '<font color=red>Erro: N&atilde;o foi poss&iacute;vel baixar a lista de letras!</font>';
	};
	myajax.send();
};

vagalume.trackPageview = function(url,delay) {
	try {
		if (delay) {
			setTimeout(function() { pageTracker._trackPageview(url); },delay);
		} else {
			pageTracker._trackPageview(url);
		}
	} catch(e){}
};

vagalume.setAnalyticsEvent = function(category,event,value,optional_value) {
	try {
		pageTracker._trackEvent(category,event,value,optional_value);
	} catch(e) {}
	return true;
};

// Verifica se usuário está logado ou seta um valor de sessão
vagalume.userSession = function(session,expire) {
	expire = expire ? expire : null;
	if (session) session == 'unset'
		?setCookie('sessionID',null,0.001,'/') // Cookie Baixo para eliminá-lo em seguida
		:setCookie('sessionID',session,expire,'/');
		
	var session = getCookie('sessionID');
	return typeof(session) == 'string' && session !== 'null' ? session : false;
};

// Remover em 15/08
vagalume.PartnerBar = function() { }

function hide_loading()		{$("#loading").css('display','none');};
function strip_tags(str)	{return str.replace(RegExp("<\S[^>]*>","g"),"");};
function trim(str)		{return str.replace(RegExp("^\s*|\s*$"),"");};
function wr (str)		{ document.write(str); };

function playphone_open(descr_url,loc) {
	var repl = new RegExp("\-","g");
	if (loc == 'artmenu') {
		var bNum = 113;
	} else if (loc == 'breadcrumb') {
		var bNum = 114;
	} else {
		var bNum = 112;
	}
	var url = "http://www.vagalume.com.br/click.php?b="+ bNum +"&kw=" + descr_url.replace(repl,"+");
	if (loc) {
		url += "&loc=" + loc;
	};
	setTimeout(function() { pageTracker._trackPageview('/outgoing/playphone/'); },3000);
	window.open(url);
};

vagalume.setDHTML = function() {
	if (document.getElementById('lyrics')) {
		try {
			if (vData["banda_url"] != "suel") {
				var playAdHTML = "<table border=0><tr><td><img src='"+static1+"/images/ad/phone.png'></td><td style='font:bold 12px Verdana'>Baixe agora o Ringtone desta música!<br/><a style='color:#0092B5;text-decoration:underline' href=\"javascript:playphone_open('" + vData['banda_url'] + "','letbot')\">Clique aqui!</a></td></tr></table>";
				if(is_plugin){
					var playAd = document.createElement("div");
					playAd.id = 'playphoneAd';
					playAd.style.backgroundColor = "#FFFFFF";
					playAd.style.padding = "15px";
					playAd.innerHTML = playAdHTML;
					$("#mainPlugin .lateralDireita").prepend(playAd);			
				}else{
					$('#playphoneAd').html(playAdHTML);
				}
				
			};
		} catch (e) {};
	};
	if (window.vData && window.vData.banda_url != "suel" && $('#artist-menu').is('div') && country == "br") {
		if ($('#breadcrumb').is('div')) {
			$('#breadcrumb').prepend('<span style="float:right"><a href="javascript:playphone_open(\''+vData['banda_url']+'\',\'breadcrumb\')">Baixar <b>'+vData['banda']+'</b> no seu celular!</a></span>');
		};
	};
	
	vagalume.background.show_bgAplic();
	if(vagalume_home){
		// Track homespot
		$("#homespot a").click(function() {
			try {
				pageTracker._trackEvent('Homespot','click',$("#homespot abbr.homespotID").attr("value"));
			} catch(e) {}
			return true;
		});
		// Track drops
		$("div.itemspot a").click(function() {
			try {
				pageTracker._trackEvent('Homespot Drops','click',$(this).parents("div.itemspot").prev(".dropID").attr("value"));
			} catch(e) {}
			return true;
		});
	}
	
	// verifica se existe a ancora de login e se o usuario está logado
	if(!$("#loginUser").is('div')){
		$("#searchbar").prepend('<div id="loginAbs"><div id="loginUser"><a href="javascript:void(0)" class="btLogin contentLogin"></a></div><div class="cadastrese"><a href="/my.php?action=add">Cadastre-se</a></div></div>');
	};
	if($("#loginUser").is('div')){
		vagalume.login.changeButtonAction(vagalume.userSession()?'logout':'login');
	}
	setTimeout(function(){
		var uinfo = getCookie('uinfo');
		if(!uinfo) {
			$.requireOnce(
				['http://www.google.com/jsapi'],
				function(){vagalume.GeoIP();},
				'/js.js'
			);
		}
	}, 1);
};

vagalume.login = {
	count:0,
	elemClicked: false, //salva o id do botao de login que foi clicado
	// Altera a função do botão de login
	changeButtonAction:function(login) {
		var login = login === 'login' ? true : false;
		$("#loginUser a").html(login==true?'Login':'Sair')[0].onclick=function(){
			if(login==true){
				vagalume.login.openBalloon($('#loginUser'));	
			}else{
				vagalume.login.logout();
			}
		}		
		if(!login){
			var infoUser = getCookie('user_login');
			$("#loginUser").prepend('<span class="contentLogin"><a href="/my/'+(infoUser?infoUser+'/':'')+'" class="contentLogin">Meu Vaga-lume</a> | </span>');
			$("#loginAbs .cadastrese").hide();
		}
	},
	returnFormLogin: function(flagExternalConnection){
		return	'<form onsubmit="return false;">'+
			'	<div class="loginFields">'+
			'		<label for="loginUsuario">Login</label>'+
			'		<input class="loginDataInput" type="text" id="loginUsuario" />'+
			'	</div>'+
			'	<div class="loginFields pswd">'+
			'		<label for="senhaUsuario">Senha</label>'+
			'		<input class="loginDataInput" type="password" id="senhaUsuario" />'+
			'	</div>'+
			'	<input type="submit" class="inpSubmit" onclick="vagalume.login.send('+(flagExternalConnection?'\''+flagExternalConnection+'\'':'')+')" value="Entrar" style="padding:0 0 2px 0" />'+
			'	<div class="logged"><input type="checkbox" id="checkLogin" value="1"><label for="checkLogin">Salvar minhas informações neste computador</label></div>'+
			'	<div class="loginFields auth">'+
			'		<strong style="line-height:16px;float:left">Autenticar via:</strong>'+
			/* EXTERNAL CONNECTION CSS - COLOCADO EM 2010-02-04 - RETIRAR O STYLE DEPOIS QUE SAIR O CACHE */
			'		<a href="javascript: void(0);" onclick="vagalume.login.externalConnection.showLoading(true); vagalume.login.externalConnection.connectTo.facebook(true)"	style="display:block;float:left;margin:0 0 0 10px;width:16px;height:16px;background:transparent url(/images/icons/external-connection.png) no-repeat scroll -26px -26px"	class="externalConnection facebook"	title="Facebook"></a>'+
			'		<a href="javascript: void(0);" onclick="vagalume.login.externalConnection.showLoading(true); vagalume.login.externalConnection.connectTo.twitter()"		style="float:left;margin:0 0 0 10px;width:16px;height:16px;background:transparent url(/images/icons/external-connection.png) no-repeat scroll -26px  -1px"			class="externalConnection twitter"	title="Twitter"></a>'+
			'		<a href="javascript: void(0);" onclick="vagalume.login.externalConnection.showLoading(true); vagalume.login.externalConnection.connectTo.mslive()"		style="display:block;float:left;margin:0 0 0 10px;width:16px;height:16px;background:transparent url(/images/icons/external-connection.png) no-repeat scroll -26px -101px"	class="externalConnection mslive"	title="Windows Live, MSN ou Hotmail"></a>'+
			'		<a href="javascript: void(0);" onclick="vagalume.login.externalConnection.showLoading(true); vagalume.login.externalConnection.connectTo.orkut()"		style="display:block;float:left;margin:0 0 0 10px;width:16px;height:16px;background:transparent url(/images/icons/external-connection.png) no-repeat scroll -26px -76px"	class="externalConnection orkut"	title="Orkut"></a>'+
			/* EXTERNAL CONNECTION CSS - FIM */
			'		<span class="loading" style="white-space:nowrap;display:none"><img style="margin:0 0 0 10px" align="left" src="/images/processing.gif" /></span>'+
			'		<br class="clean" />'+
			'	</div>'+
			'	<div class="optionsLogin">'+
			'		<a href="/my.php?action=forgot">Esqueci meu login ou senha</a>'+
			'		<a href="/my.php?action=add">Cadastrar no Vaga-lume</a>'+
			'	</div>'+
			'</form>';
	},
	openBalloon:function(elem,top,left,spritePosition){
		is_my_autent = (location.pathname.indexOf("my.php") >= 0 && (location.search.indexOf("action=autent") >= 0 || location.search.indexOf("action=logoff") >= 0));
		if (is_my_autent) {
			$("#loginUsuario")[0].focus();
			return false;
		};
		$.requireOnce(["/js/my.js", "http://static.ak.connect.facebook.com/js/api_lib/v0.4/FeatureLoader.js.php/pt_BR"], function(){
			$.requireOnce(["/js/external_connection.js"], function(){
				FB.init(vagalume.login.externalConnection.def.facebook.api_key, "/xd_receiver.htm");
				if(is_plugin=="wmp"){
					var urlRE = new RegExp("^http://[^/]+");
					window.open('http://plugin.vagalume.com.br/my.php?action=autent&redirect='+encodeURIComponent(document.location.href.replace(urlRE,'')));
				}else{
					if(vagalume.login.elemClicked!=elem[0].id){
						vagalume.login.elemClicked=elem[0].id;
						$('#myBalloon.loginUser').remove();
						vagalume.login.openBalloonCallback(elem,top,left,spritePosition);
						if(spritePosition=='left') $('#myBalloon .arrow').attr('style','').css('right','auto');
					}else{
						vagalume.login.elemClicked=false;
						$('#myBalloon.loginUser').slideUp('normal',function(){
							vagalume.myBalloon._pop();
						});
					}
				}
				vagalume.login.externalConnection.start();
			}, "http://static.ak.connect.facebook.com/js/api_lib/v0.4/FeatureLoader.js.php/pt_BR");
		}, "/js.js");
	},
	openBalloonCallback:function(elem,top,left,spritePosition) {
		var posElem = elem.offset();
		var html = vagalume.login.returnFormLogin();
		// Cria objeto balloon
		vagalume.myBalloon.create({
			spriteX: '220px', spriteY:'0',
			pos: 'r',	  arrow: 'up',
			width:	'250px',  height:'237px',
			heightInt: '240px',
			x:(posElem.left + (left?left:-210)), y:(posElem.top + (top?top:28)),
			name:'loginUser', title:'', content:html
		});
		// Mostra balloon e verifica onde o usuario está clicando para o fechamento correto
		$('#myBalloon.loginUser').slideDown('normal',function(){
			$('#loginUsuario').focus();
			$(document).mousedown(function(e){
				var 	balloon = $('#myBalloon.loginUser'),
					balloonOffset = balloon.offset() || 0,
					balloonW = balloon.width() || 0,
					balloonH = balloon.height() || 0,
					pageX = e.pageX || e.clientX + $(document).scrollLeft || 0,
					pageY = e.pageY || e.clientY + $(document).scrollTop || 0;
				if(pageX!=0 && pageY!=0 &&  !$(e.target).hasClass('btLogin') && 
				   ((pageX>balloonOffset.left+balloonW || pageX<balloonOffset.left) || 
				   (pageY>balloonOffset.top+balloonH || pageY<balloonOffset.top))){
					$('#myBalloon.loginUser').slideUp('normal',function(){
						vagalume.login.elemClicked=false;
						vagalume.myBalloon._pop();
					});
				}
			});				
		});
		$('#loginUsuario,#senhaUsuario').focus(function(){$(this).css('backgroundColor','#CCFF00');}).blur(function(){$(this).css('backgroundColor','#FFFFFF');});
	},
	send:function(flagExternalConnection){
		// Caso nao tenha sido digitado o login e/ou senha
		if($("#loginUsuario"+(flagExternalConnection === "facebook" ? "FB" : "")).val()=='' || $("#senhaUsuario"+(flagExternalConnection === "facebook" ? "FB" : "")).val()==''){
			// Caso nao tenha mensagem de erro, mostra, caso contrario faz fadeOut e fadeIn na mesma msg
			if(!$('.loginUser .loginFail').is('span')){
				$('.loginUser .optionsLogin').after('<span class="loginFail">Não foi possível efetuar o Login!</span>');
			} else {
				$('.loginUser .loginFail').fadeOut('normal',function(){$(this).fadeIn()});
			};
			return false;
		};
		$.post('/my.php',{action:'autentRequest', usuario:url_encode($("#loginUsuario"+(flagExternalConnection === "facebook" || flagExternalConnection=="connectFromFacebook" ? "FB" : "")).val()), senha:url_encode($("#senhaUsuario"+(flagExternalConnection === "facebook" || flagExternalConnection=="connectFromFacebook"? "FB" : "")).val()), authFrom:url_encode($("#authFrom").val())},function(ret){
			// Verifica se o usuário foi logado (através do retorno)
			if(eval(ret)!=undefined){
				// Grava Cookies caso esteja cheacado a opçao de lembrar
				$("#checkLogin").attr('checked')
					? vagalume.userSession(ret,99999)
					: vagalume.userSession(ret);
				// caso seja uma conexão externa, como o twitter
				if (flagExternalConnection === "twitter") {
					location.href = $(".externalConnectionSuccessURL").val();
				} else if (flagExternalConnection === "facebook") {
					location.reload();
					return false;
				} else if (flagExternalConnection === "connectFromFacebook") {
					vagalume.login.externalConnection.connectFrom.facebook();
				} else if (flagExternalConnection === "mslive") {
					loc = "/externalConnection.php?action=connection&external=mslive&mslive_uid="+$("#mslive_uid").val();;
					location.href = loc;
				} else if (flagExternalConnection === "orkut") {
					window.location.reload();
				} else if (flagExternalConnection === "connectFromOrkut") {
					//window.location.href = '/my/?myVgl_min=orkutMin';
					window.location.reload();
				} else if(flagExternalConnection === "chrome"){
					window.location.reload();
					return false;
				};

				if (flagExternalConnection) {
					return false;
				};
				// Fecha balloon
				$('.loginUser').slideUp('normal',function(){
					vagalume.myBalloon._pop();
				});
				
				// Insere mensagem de boas vindas
				$("#loginUser").html("<span class='contentLogin'><a href=\"/my/"+$("#loginUsuario").val()+"/\">Meu Vaga-lume</a>&nbsp;&nbsp;|&nbsp;<a href=\"javascript:void(0)\" class=\"logoutUser\">Sair</a></span>");
				$("#loginAbs .cadastrese").hide();
				
				// Se possuir variaveis de controle, redireciona				
				if(window.onLoginRedir!=undefined){					
 					window.location = window.onLoginRedir;
				} else if(window.onLoginReload){
 					document.location.reload();
				}
				
				//se for login através do botão de comentários
				if($('#comments').is('div') && vagalume.login.elemClicked=='btSendComment'){
					vagalume.comments.openComment();
				}
					
				// Altera onclick para o logout
				var alterButtonLogin=$('#loginUser a.logoutUser')[0];
				if(alterButtonLogin){
					alterButtonLogin.onclick = vagalume.login.logout;
				}
			} else {
				// Se houver o flagExternalConnection mas nao ter a interação com o chrome
				if (flagExternalConnection && flagExternalConnection!='chrome') {
					$(".loginFields.erro").html("Login ou senha incorreto");
					return false;
				};
				// Caso nao tenha mensagem de erro, mostra, caso contrario faz fadeOut e fadeIn na mesma msg
				$obj = ($(".loginUser").html() ? $(".loginUser") : ($(".amvLogin").html() ? $(".amvLogin") : false));
				if(!$(".loginFail", $obj).is("span")){
					$(".optionsLogin", $obj).after('<span class="loginFail">Não foi possível efetuar o Login!</span>');
				} else {
					$(".loginFail", $obj).fadeOut("normal", function(){
						$(this).fadeIn();
					});
				}
			}
		});
	},
	logout:function(cback){
		//sessionID = getCookie("sessionID")
		//$.get('/my.php?action=logoutRequest&sessionID='+sessionID,function(ret){
		var cback = cback || false;
		$.get('/my.php?action=logoutRequest&r='+(new Date()).getTime(),function(ret){
			if (typeof(cback) == "function") {
				cback();
				return false;
			};
			if(ret){
				vagalume.userSession('unset');
				$("#loginUser").html('<span class="contentLogin">Obrigado por utilizar o Vaga-lume!</span>')[0].onclick=function(){return false;};
				
				// Se possuir variaveis de controle, redireciona
				if(window.onLogoutRedir!==undefined){
					window.location = window.onLogoutRedir;
				} else if(window.onLogoutReload){
					document.location.reload();
				}
					
				setTimeout(function(){
					$("#loginUser").fadeOut('slow',function(){
						$("#loginUser").html('<a href="javascript:void(0)" class="btLogin contentLogin">Login</a>').fadeIn('slow');
						$("#loginAbs .cadastrese").fadeIn('slow');
						$("a",this).click(function(){vagalume.login.openBalloon($("#loginUser"));});
					});
				},1500);
			}
		});
	}
};

vagalume.imgLoader = function(obj) {
	var staticChk = new RegExp("http://static[1-4]\.vagalume\.com\.br(/.+)");
	var attr = $(obj).attr('src');
	if (staticChk.test(attr)) {
		var match = attr.match(staticChk);
		obj.src = "http://www.vagalume.com.br"+match[1];
	};
	obj.onerror = "";
};

vagalume.prepare = {
	top: function() {
		vagalume.siteArea = $('body').attr('class');
		if (typeof(vagalume.siteArea) == 'undefined') {
			vagalume.siteArea = "general";
		}
	},
	bottom: function() {
		navbar.menu.start();
		navbar.loadform();
		if (! window.vagatracker) {
			analytics(country,'');
		};
		vagalume.setDHTML();
	},
	positionAds:function (selector, positioner) {
		if($(selector).is('div') && $(positioner).is('div')){
			var pos = $(positioner).position();
			$(selector).css("top",pos.top);
			$(selector).css("left",pos.left);
		}
	}
};

vagalume.background = {
	show_bgAplic:function () {
		if (!($.browser.msie == true && $.browser.version <= 6) && screen.width >= 1152 && !is_ie6) {
			if(!$("#bg_aplicVagalume").is("div"))
				$("#vagalume").before('<div id="bg_aplicVagalume"></div><div id="bg_aplicVagalume_bottom"></div>');
			var cssBottom	= {"background": "url('http://static1.vagalume.com.br/images/backgrounds/aplic/bg_bottom.png') repeat-x scroll center 0 transparent","bottom": "0px","height": "338px","left": "0px","position": "fixed","width": "100%","z-index": "-1"},
			    cssBkg	= {"background": "url('http://static1.vagalume.com.br/images/backgrounds/aplic/pote.png') no-repeat scroll center 0 transparent","display": "block","top": "0px","position": "absolute","left": "0px","width": "100%","height": "900px","z-index": "-1"}
			$('#bg_aplicVagalume').css(cssBkg);
			$('#bg_aplicVagalume_bottom').css(cssBottom);
		}
	}
};

vagalume.songstyle = {
	// Calcula proximidade entre duas listas de estilos musicais
	intersection:function(arrA,arrB){
		var matchval=0;
		for (var i in arrA) if (arrB[i]) matchval+=(arrA[i]<arrB[i])?arrA[i]:arrB[i];
		return matchval;
	},
	// Gera e retorna array com informações de estilo do usuário armazenados em cookie
	loggedUserInfo:function(){return this.loggedUserSongstyle || function() {
		this.data={};
		var info, styles=window.getCookie('userSongstyle');
		if (!styles || typeof(styles) != 'string' || !getCookie('sessionID')) return false;
		styles = styles.split('x');
		for (var i in styles) {
			info = styles[i].split('-');
			this.data[info[0].toString()] = parseFloat(info[1]);
		};
		return this.data;
	}();},
	// Gera e retorna array com informações de estilo contida em um conjunto de tags.
	domSongstyleInfo:function($query){ return this.domSongstyleInfo.data || function() {
		this.data={};
		var _this=this;
		$('var',$query).each(function(){
			_this.data[this.className.toString()]=parseFloat(this.innerHTML);
		});
		return this.data;
	}()},
	open:function() {
		$.requireOnce(['/js/songstylebox.js'],function(){vagalume.songstyle.show();},'/js.js');
		return false; // para nao seguir o href
	}
};

vagalume.GeoIP = function() {
	try {
		// try/catch p/ evitar erros externos
		if (window.google) {
			var regiao={"AC":"01","AL":"02","AM":"03","AP":"04","BA":"05","CE":"06","DF":"07","ES":"08","GO":"29","MA":"13","MG":"15","MS":"11","MT":"14","PA":"16","PB":"17","PE":"30","PI":"20","PR":"18","RJ":"21","RN":"22","RO":"24","RR":"25","RS":"23","SC":"26","SE":"28","SP":"27","TO":"31"}			
			if (window.google.loader.ClientLocation.address.country_code == 'BR') {
				setCookie('uinfo','....'+window.google.loader.ClientLocation.address.country_code+'.'+regiao[window.google.loader.ClientLocation.address.region]+'.'+window.google.loader.ClientLocation.address.city,24*365*5,"/");
			} else if(window.google.loader.ClientLocation.address.country_code != ''){
				var vRegion;
				$.ajax({
					type: "GET",
					url: "/ajax/geodata.php",
					data:"action=get&query=region&country="+window.google.loader.ClientLocation.address.country_code,
					success:$( function(html) {
						var arrRegion = html.replace("{","").replace("}","").split(',');
						for (var i=0;i<arrRegion.length;i++) {
							vRegion = arrRegion[i].split(":");
							if (vRegion[1].replace('"','').replace('"','') == window.google.loader.ClientLocation.address.region) {
								setCookie('uinfo','....'+window.google.loader.ClientLocation.address.country_code+'.'+vRegion[0].replace('"','').replace('"','')+'.'+window.google.loader.ClientLocation.address.city,24*365*5,"/");
							}
						}
					})
				});
			};
		}
	} catch(e) {}
}

// navbar.js (navbar.menu.start() e loadform)

function getCoord(e){
	var elem=$(e);
	var tp=elem.offset();
	var w=elem.width();
	var h=elem.height();
	var pos={
		x:tp.top,
		y:tp.left,
		w:w,
		h:h
	};
	return pos;
}

var navbar = {
	tOptions:{
			art:(country=="ar")?["Artista","b&uacute;squeda por nombre de artista"]:["Artista","pesquisa artista pelo nome"],
			let:(country=="ar")?["Canci&oacute;n","b&uacute;squeda por t&acute;tulo de la canci&Oacute;n"]:["M&uacute;sica","pesquisa pelo t&iacute;tulo da m&uacute;sica"],
			tre:(country=="ar")?["Extracto","b&uacute;squeda de palabras y frases en letras"]:["Trecho","pesquisa m&uacute;sica por termos e frases encontrados em letras e t&iacute;tulos"],
			gen:(country=="ar")?["General","B&uacute;squeda por general"]:["Geral","pesquisa geral"]
	},
	inputValueColor:{
		typing:		window.opera?'#000000':(document.all?'rgb(0,0,0)':	'rgb(0, 0, 0)'),	// Cor a ser usada quando usuário digitar algo - equiv. a #000 
		description:	window.opera?'#aaaaaa':(document.all?'rgb(170,170,170)':'rgb(170, 170, 170)')	// Cor da instrução de valor - equiv. a #AAA
	},
	searchtype:undefined,
	instance:[],
	select: {
		open: function(e,n) {
		// Cria a lista de opções de busca (artista, trecho, etc)
			// Note: 'n' will be used as listbox className;
			if(!$('.'+n).is('div')){
				var options=$(e).data('options');
				var pos = getCoord(e),
				box='<div class="'+n+'" style="position:absolute;top:'+(pos.x+pos.h-3)+'px;left:'+pos.y+'px;cursor:pointer;padding:0 0 4px 0;background-position:-176px '+(-90+pos.h)+'px"><ul style="margin:0;padding:0;list-style-position:outside;text-align:left"></ul></div>';
				$('body').append(box);
				navbar.instance[n] = {element:$(box)};
				for (var i in options) {
					var li = '<li title="'+options[i][1]+'" class="navbar_select_blurred" style="margin:0;padding:2px 0 1px 4px;list-style-type:none;line-height:16px"><i class="'+i+'"></i>'+options[i][0]+'</li>';
					$('.'+n+' ul').append(li);				
				}
				$('.'+n+' ul li').click(function(){
					navbar.select.choose($('i',this).attr('class'));
					$('.'+n).fadeOut();
				});
				$('.'+n+' ul li').mouseover(function(){
					$(this).toggleClass('navbar_select_focused');
					$(this).toggleClass('navbar_select_blurred',false);
				});
				$('.'+n+' ul li').mouseout(function(){
					$(this).toggleClass('navbar_select_blurred');
					$(this).toggleClass('navbar_select_focused',false);
				});
				$('.'+n+' ul').mouseleave(function(){
					$('.'+n).fadeOut();			 
				});
			}else{
				$('.'+n).fadeIn();	
			}
		},		
		choose: function(val){
			//Bloco para Alterar o texto default do input quando se alterar a opção no select e manter o texto digitado caso o usuário venha a escolhe outra opção
			var	inp = $('#q'),
				text;
			switch (val) {
				case 'art':
					text = country == 'br'?'Digite o nome do artista...':'Digite el nombre de artista...';					
					break;
				case 'let': 
					text = country == 'br'?'Digite o nome da música...':'Digite el nombre de la musica...';
					break;
				case 'tre':
					text = country == 'br'?'Digite o trecho da música...':'Digite el trecho de la musica...';
					break;
				case 'gen':
				default:
					val = 'gen';
					text = country == 'br'?'Digite o que deseja buscar...':'Digite o que desea buscar...';
					break;
			};			
			setCookie('search',val);
			navbar.searchtype=val;
			$('#t').selected=val;
			inp.focus(function(){
				if($(this).css('color') == navbar.inputValueColor.description){
					$(this).val('');	
				}		   
				$(this).css('color',navbar.inputValueColor.typing);
			});
			if(inp.css('color') == navbar.inputValueColor.description) {
				inp.css('color',navbar.inputValueColor.description).val(text);
			}
			inp.blur(function(){
				if ($(this).val() == '') 
					inp.css('color',navbar.inputValueColor.description).val(text);		  
			});
			var typeSelect = $('#t');
			$('span',typeSelect).html('<i class="'+val+'"></i>'+navbar.tOptions[val][0])[0].selected = val;
			navbar.showStrictSearch();
			if($('#searchbar span.searchLyrics').css('display')=='none') { 
				$('#searchbar span.searchLyrics').show();
			}
			navbar.enableSuggest();
		}
	},	
	submit: function(e) {
		if ($('#q').css('color') == navbar.inputValueColor.description || ! /[^ ]/.test($('#q').val())) {
			alert(country == 'br'?'Digite o que você quer procurar':'Digite o que usted quer buscar');
			$('#q').focus();
			return false;
		};

		// Tira três pontos do final e caracteres espaços do início
		$('#q').val($('#q').val().replace(/\.+$/g,'').replace(/^ +/,''));

		// Parses pseudo-form-elements creating hidden inputs for each them
		var form = $('#searchform');
		form.append('<input type="hidden" name="t" value="'+navbar.searchtype+'" />');
		if (navbar.searchtype=="gen"){
			// Ads
			form.append('<input type="hidden" name="cof" value="FORID:10" />');
			// Id do código personalizado
			form.append('<input type="hidden" name="cx" value="'+(country == 'br'?'000206117440595566957:wug29ougm6c':'000206117440595566957:cf-hr502wec')+'" />');
			// Pesquisa restrita a um artista
			if ($('label.artistStrict input:checked').is('input')) {
				form.append('<input type="hidden" name="as_q" value="site:http://www.vagalume.com.'+window.country+'/'+vData.banda_url+'/" />');
			};
		}
	},	
	showStrictSearch:function() {
		// Alterna entre exibição das letras iniciais de artistas
		// e checkbox que limita abrangência de pesquisa ao artista atual

		// Se não existe o conteúdo "organizado" dos links de iniciais
		if (! navbar.searchBarLetters) {
			var letterList = $('#browse ul');
			$('li',letterList).css({"float":"left","margin":"2px 0 0 3px","display":"inline","font-weight":"bold","font-size":"14px","letter-spacing":"-1px"});
			navbar.searchBarLetters=$('#searchbar_letters');
			navbar.searchBarLetters.append(letterList);
			$("#searchbar_letters").after('<span class="txtSlogan">Artistas</span>');
			$("#searchbar .searchLyrics").show();
		};
		if (window.vData && window.vData.banda && !navbar.artistStrictFormField) {
			navbar.artistNameShortened = vData.banda.length > 22 ? vData.banda.substring(0,21)+'...' : vData.banda;
			navbar.artistStrictFormField = $('<input class="artistStrict" type="hidden" name="busca_ia" value="'+vData.bandaID+'" />')[0];
		};

		// Alterna letras e checkbox no searchbar
		if (window.vData && window.vData.banda && navbar.searchtype != 'art'){
			var label=$('<label style="display:none" class="artistStrict">'+
				'<input value="'+window.vData.bandaID+'" type="checkbox" /> '+
				(window.country == 'br' ? 'Buscar somente nas músicas de' : 'Buscar sólo en canciones de')+
				' <strong>'+navbar.artistNameShortened+'</strong>'+
			'</label>');
			label.bind('click',function() {
				var elem = $('input',this);
				if (elem[0].checked) {
					$('#searchform').append(navbar.artistStrictFormField);
				} else {
					$('#searchform input.artistStrict').remove();
				};	
			});
			if (/busca_ia=/.test(location.search)) {
				$('input',label)[0].checked = true;
				label.unbind('click');
			};
			
			
			if(!$('.artistStrict').is('label')){
				$("#searchbar .searchLyrics").remove();
				$("#searchbar").append(label.show());					
			}
			
		} else {
			//Remover insercao de slogan após dia 20/01/2010
			if(!vagalume_home && !$("#searchbar .searchLyrics").is('span')) {
				var wds = country=='ar' ? 'Más de <b>1 MILLÓN</b> de <b>Letras de Canciones, Acordes e Traducción</b>!':'Mais de <b>1 MILHÃO</b> de <b>Letras de Músicas, Cifras e Traduções!</b>';
				$('#searchbar').append('<span class="searchLyrics">'+wds+'</span>')
			}
			
			$('.artistStrict').remove();
			$(navbar.searchBarLetters).fadeIn();
		};
	},

	loadform: function() {
		$('#searchform .tCw .tC').attr('autocomplete','off');
		$('#t').data('options',navbar.tOptions);
		// Altera propriedades do formulário para uso com as demais funções
		navbar.searchtype = getCookie('search');
		if (!navbar.searchtype || navbar.searchtype.length != 3) navbar.searchtype = 'gen';

		$(function() { navbar.select.choose(navbar.searchtype); });

		// Get field name and use it as part of classname
		var	field = $('#t'), options;

		// Remove filtros de pesquisa do Google
		$('#q').val($('#q').val().replace(/^ *(allintitle:|inurl:|site:)/,''));

		if (/\.\.\.$/.test($('#q').val())) $('#q').css('color',navbar.inputValueColor.description); // Se terminar em três pontos no início, torna cor clara
		$('#q').blur(function(){
			$(this).focus(function(){});
		});
		field.bind('click',function(){navbar.select.open($(this),'navbar-t')});
		options=field.data('options');
		field = field.html('<span><i class="'+navbar.searchtype+'"></i>'+options[navbar.searchtype][0]+'</span>')[0];		
		field.selected=navbar.searchtype;	
	},
	// Habilita ajaxsuggest e ajusta seu comportamento
	enableSuggest:function() {
		var bindevent = (document.all && !window.opera) || /Chrome/i.test(navigator.userAgent) ? 'keydown' : 'keypress';
		var input = $('#q'), from='/browse/ajax', opt;
		if (navbar.searchtype != 'art') {
			input.unbind('keyup');
			suggest.unset(input);
			$(document).unbind(bindevent);
			return false;
		};
		opt ={
			refpos	 : input.parent(),
			className: 'art_sug',
			cache	 : true,
			wrappers : true,
			subinfo  : navbar.art_sug_subinfo,
			morelink : '/browse/$-all.html'
		};
		// Get suggest script and start-it
		if (typeof(suggest) == "object") {
			input.bind('keyup',function() {
				suggest.set(input,from,opt);
				suggest.listPreserve=false;
			});
			
			$(document).bind(bindevent,function(e){suggest.keyBindings(e);});
		};
		
	},

	menu: {
		start :	function() {
			var arrAreas = ['general','myvl','addons','top100','newsbody','special','interview','enquete','game','plugin','widgets'];
			$("#menubar ul li div").each(function(i) {
				$(this).attr('area',arrAreas[i]);
			});

			$("#menubar ul li ul li a").each(function(){
				if (this.href.replace(location.protocol+'//'+location.host,'') == location.pathname) $(this).addClass("mnu_selected");
			});

			//mouseover das abas
			$('#menubar ul li div a').mouseover(function(){
				$('#menubar ul li div').each(function(){
					$(this).removeClass('buttonspot colorSoft');
				});
				var tab=$(this).parent();
				tab.addClass('buttonspot colorSoft');
				
				$('#menubar ul li ul').each(function(){
					$(this).hide()				     
				});
				var ul=tab.parent();
				$('ul',ul).show();
			});
			//seleciona a aba inicial
			$('#menubar ul li div').each(function(){
				if($(this).attr('area')==vagalume.siteArea){
					var li=$(this).parent();
					$('ul',li).show();
					$(this).addClass('buttonspot colorSoft');
				}				      
			});

		}
	},

	// This object contains functions to configure the sub-suggest behavior.
	art_sug_subinfo:{
		// This gets an array and returns an object containing named properties.
		// Each property stores a field used by draw();
		store:function(rawinfo) {			
			var subinfo = {
				lyr_count: rawinfo.shift(),
				art_pict : rawinfo.shift(),
				art_views: rawinfo.shift()
			};
			subinfo.special = rawinfo.shift();

			if (subinfo.special) {
				subinfo.special = subinfo.special.split('#');
				for (var s in subinfo.special) {
					subinfo.special[s] = subinfo.special[s].split('|');
					subinfo.special[s] = {
						name: subinfo.special[s][0],
						url : subinfo.special[s][1]
					};
				};
			} else {
				subinfo.special=false;
				return subinfo;
			};
			return subinfo;
		},

		// This function draws subinfo when a main list suggest is hovered 
		draw:function(e) {
			var self = navbar.art_sug_subinfo;
			self.subclose();
			self.open(e);
		},

		// This function create de box and put its contents.
		open:function(e) {			
			var p,b,handler,html,img,spc='';		
			p = getCoord(e);
			b='<b class="art_sug_subinfo" style="position:absolute;top:'+(p.x - 20)+'px;left:'+(p.y + p.w -50)+'px;z-index:100"></b>';
			handler='<div class="art_sug_subinfo_handle" style="position:absolute;top:7px;left:-10px;z-index:101"></div>';
			
			$('body').append(b);
			this.box = $('.art_sug_subinfo');
			$('.art_sug_subinfo').mouseover(function(){
				suggest.listPreserve=true;
			});
			$('.art_sug_subinfo').mouseout(function(){
				suggest.listPreserve=false;
			});			
			var info=e.suggestinfo;
			if (info.subinfo.special) {
				spc = '<p>Veja também '+info.urlname+' em:<br/>';
				for (var i in info.subinfo.special) {
					spc+= i > 0 ? ',&nbsp;&nbsp;' : '';
					spc+='<a href="'+info.subinfo.special[i].url+'">'+info.subinfo.special[i].name+'</a>';
				};
				spc += '</p>';
			}
			img = info.subinfo.art_pict != '' ? '<a class="art_sug_pict" href="/'+info.urlpart+'/"><div class="art_sug_pict_op"></div><img style="width:115px;height:74px;" src="/'+info.urlpart+'/images/'+info.subinfo.art_pict+'.jpg" alt="'+info.urlname+'"/></a>' : '';
			html =	"<div class='art_sug_subinfo_top_border'></div>"+
				"<div class='art_sug_subinfo_inner'><div class='art_sug_subinfo_descr'>"+
					img+
					"<a class='art_sug_name' href='/"+info.urlpart+"/'>"+info.urlname+"</a><br/>"+
					"<span><i></i><a href='/"+info.urlpart+"/' style='text-decoration:none'>Veja todas as músicas deste artista</a></span>"+
					'<ul>'+
					'<li class="lyrics" onmouseover="this.className=\'lyrics_hovered\'" onmouseout="this.className=\'lyrics\'"><a href="/'+info.urlpart+'/letras/"><i></i>Letras</a></li>'+
					'<li class="albums" onmouseover="this.className=\'albums_hovered\'" onmouseout="this.className=\'albums\'"><a href="/'+info.urlpart+'/discografia/"><i></i>&Aacute;lbums</a></li>'+
					'</ul>'+				
				'</div>'+
				'<span class="clean"></span>'+
				'</div>'+
				'<div class="art_sug_subinfo_bottom_border"></div>';
			
			$('.art_sug_subinfo').html(html);
			$('.art_sug_subinfo').append(handler);	
		},	
		// This function closes subinfo box
		subclose:function() {
			var self = navbar.art_sug_subinfo;
			if(self.box) $(self.box).remove();
		}
	}
}

var suggest = {
	dom:{	// Elements created by object that should be removed when closed
		box:undefined, // Suggest box
		sub:undefined  // Suggest box sub box
	},
	ref:{	// Reference elements shouldn't be removed from DOM
		pos:undefined,   // suggestbox position anchor
		input:undefined  // Input with value to search
	},
	subinfo:{ // Store reference for functions that will handle the subinfo
		store:undefined,
		draw:undefined,
		open:undefined,
		subclose:undefined
	},
	set:	function(input,from,opt) {
		var opt = opt ? opt : false;
		input.attr('autocomplete','off');
		input.unbind('focus');		
		
		if (input.lockRefresh == true) {
			input.lockRefresh = false;
			return false;
		};
		this.recordedValue = this.value; 
		suggest.show(input,from,opt);			
		input.bind('blur',function(){
			suggest.close();
			this.lockRefresh=false
		});
		
	},
	// Show box with suggestions. Should be placed as onkeyup event
	show:	function(input,from,opt) {
		this.close();
		if (input.val().length > 0) {
			if (input.val() == '' ) return false;
			var list, opt = opt ? opt : {};
			opt.input = input;
			opt.from  = from;
			if (! input.suggest) input.suggest = {};
			this._prepare(opt);			
			this._create();
		};
	},
	// Close suggest and clear environment
	close:	function() {
		if (this.listPreserve && (this.ref.input && this.ref.input.val() != '')) return false;
		var self = this;
		if (this.subinfo.subclose) this.subinfo.subclose();
		for (var i in this.dom) if (typeof(this.dom[i]) == 'object') {
			// These "t" reduce errors when 2 letters are typed at
			// the same time. "Try" don't let any errors be shown 
			var t = this.dom[i]; this.dom[i] = undefined;
			try { $(t).remove(); } catch(e) {};
		};
		// Unregister subinfo, element references and className
		for (var i in this.subinfo) this.subinfo[i] = undefined;
		if (this.onclose) {
			this.onclose = false;
		};
		this.className = undefined;
	},
	// This function detects the type of key pressed
	keyBindings: function(E) {
		
		E=E||window.event;
		if (E && E.keyCode && this.dom.box != undefined) 
			switch(E.keyCode) {				
				case 27: // ESCAPE pressed
					suggest._resetInput();
					break;
				case 38: // arrowUp pressed
					suggest._listFocus('-');
					break;
				case 40: // arrowDown pressed
					suggest._listFocus('+');
					break;
				default: return true;
			};
		return false;
	},
	_resetInput:function() {
		this.ref.input.val(this.ref.input.recordedValue);
		this.ref.input.lockRefresh = true;
		this.close();
	},
	_listFocus: function(opt) {
		var	step = selected = undefined,
			list = $('li',this.dom.box);

		switch (country) {
			case 'ar':
				msg = 'Ver más resultados...';
				break;
			case 'br':
				msg = 'Ver mais resultados...';
				break;
			default:
				msg = 'See more results...';
				break;
		};
		if (list.length < 1) return false;
		switch (opt) {
		// String type means that was fired by a keypress
			case '-': step = -1; break;
			case '+': step = 1; break;
			case 'focus':break;
			default:      return false;
		};
		for (var i=0,l=list.length; i<l; i++) {
			if ($(list[i]).hasClass('selected'))
				selected = i;
			$(list[i]).removeClass('selected');
		}
		if (selected == undefined && step == undefined) return true;
		if (step) this.ref.input.lockRefresh = true;
		selected = selected == undefined ? -1 : selected;
		selected = ((selected+step) < 0 || (selected+step) > (list.length-1)) ? selected : selected+step ;
		$(list[selected]).addClass('selected');
		
		//Linha referente a mais opções
		if(selected+step > list.length-1) navbar.art_sug_subinfo.subclose();
		if (list[selected]) {
			if ($(list[selected]).text() == msg) {
				this.ref.input.val(this.ref.input.recordedValue);
			}else{
				this.ref.input.val($(list[selected]).text());
			}
		};
		if (typeof(this.subinfo.draw) == 'function' && !$(list[selected]).hasClass('more'))
			this.subinfo.draw(list[selected]);
		return true;
	
	},
	// Set basic environment
	_prepare:function(o) {
		this.className = o.className;
		if (o.cache == false) {
			o.input.suggest.cache = false;
		} else if (typeof(o.input.suggest.cache) != 'object') {
			// Prepare the object that stores the cache
			o.input.suggest.cache = {};
		};
		o.input.suggest.from = o.from;
		if (o.subinfo) {
			this.subinfo.draw =  typeof(o.subinfo.draw)  == 'function' ? o.subinfo.draw : undefined;			
			this.subinfo.store = typeof(o.subinfo.store) == 'function' && o.subinfo.draw ? o.subinfo.store : undefined;
			this.subinfo.subclose = typeof(o.subinfo.subclose) == 'function' && o.subinfo.draw ? o.subinfo.subclose : undefined;
		};

		this.singleUrlSource = o.singleUrlSource ? true : false;  //Makes suggest 'ajax' from a single url and store it at once.
		this.cachestrName = o.cachestrName ? o.cachestrName : false;	// used with singleUrlSource to name the cache container
		this.suggestSimple = o.suggestSimple ? true : false;	// Creates a simple list (value returned to input)

		this.matchtype = o.match ? o.match : 'all';
		this.height = o.height ? o.height : false;
		this.onopen = o.onopen ? o.onopen : false;
		this.onclose= o.onclose? o.onclose: false;

		this.suggestStrict = o.suggestStrict ? true : false;
		this.suggestStrictColor = o.suggestStrictColor ? o.suggestStrictColor : "#c00";

		this.className = o.className ? o.className : 'suggestbox';
		this.ref.input = o.input;
		this.ref.pos = o.refpos ? o.refpos : o.input;
		this.wrappers = o.wrappers ? o.wrappers : true;
		this.limit = o.limit ? o.limit : 20;
		this.alt = o.alt ? o.alt : '/';

	},
	// Create suggest box
	_create:function() {
		var box;
 		box = '<div class="'+this.className+'" style="display:none"></div>';
		$('body').append(box);
		box.className = this.className;
		this.dom.box = $('.'+this.className);
		this._setBoxPos();		
		if (this.suggestSimple) {
			// Process typed values by its first letter, searches via
			// cache|ajax and mounts simple suggest that fills the input
			// with selected item
			this._processInputSimple();

		} else {
			// Process typed values, searches in cache|ajax and mounts list
			// doing after this the rest of work;
			this._processInput();
		}
	},
	// Sets the box position on the screen
	_setBoxPos: function() {
		var p = getCoord(this.ref.pos);
		this.dom.box.css({position:'absolute',left:p.y+'px',top:(p.x+p.h)+'px'});
		if (! this.className) 
			this.dom.box.css({overflow:'hide',width:'200px'});
	},
	// Get typed value and create suggest list for it
	_processInputSimple: function() {
		var	searchstr,list;
		searchstr = this._strSimplify(this.ref.input.val(),3);
		if (searchstr) {
			// If the list for designed prefix already has catched,
			// calls the list generator. Else require it via ajax,
			// that, so, calls the list generator
			if (this.ref.input.suggest.cache[searchstr]) {
				this._listGenSimple(searchstr);
			} else {
				var file, self=this;
				// For use in inner functions
				RExp = new RegExp("[^a-z0-9]+","i");
				searchstring = searchstr.replace(RExp,'');
				if (searchstring !=''){
					file = this.ref.input.suggest.from+'/'+searchstring.substring(0,1)+'/'+searchstring+'.txt';
					$.ajax({url:file,
						cache:true,
						beforeSend:function(xhr) {xhr.setRequestHeader('Encoding','iso-8859-1');},
						success:function(data){
							self._searchResultFilter(data,searchstr);
							self._listGenSimple(searchstr);
						}
					});
				}
			};
		};
	},
	// Calls the list generator, after get typed value and search
	// for its first three 'valid' letters
	_processInput: function() {
		var	searchstr,list;
		searchstr = this._strSimplify(this.ref.input.val(),3);
		if (searchstr) {
			// If the list for designed prefix already has catched,
			// calls the list generator. Else require it via ajax,
			// that, so, calls the list generator
			if (this.ref.input.suggest.cache[searchstr]) {
				this._listGen(searchstr);
			} else {
				var file, self=this;
				// For use in inner functions
				RExp = new RegExp("[^a-z0-9]+","i");
				searchstring = searchstr.replace(RExp,'');
				if (searchstring !=''){
					file = this.ref.input.suggest.from+'/'+searchstring.substring(0,1)+'/'+searchstring+'.txt';
					$.ajax({url:file,
						cache:true,
						beforeSend:function(xhr) {xhr.setRequestHeader('Encoding','iso-8859-1');},
						success:function(data){							
	                                        	self._searchResultFilter(data,searchstr);
							self._listGen(searchstr);
						}
					});
				}
			};
		};
	},
	// Simplify text for match and to correspond to remote search files
	_strSimplify: function(str,f) {
		if (!str) return false;
		str=str.toLowerCase();
		var RE={a:/[àáãäâ]/g, e:/[èéëêæ]/g, i:/[ìíïî]/g, o:/[òóõöôø]/g,
			u:/[ùúüû]/g, c:/[ç]/g, n:/[ñ]/g, " ":/[- \\\/+,.:;`´'"?!¡¿&%]+/g };
		for (var re in RE) {
			str = str.replace(RE[re],re);	
		};
		str = str.replace(/ /g,'');
		if (f) str = this._trim(str.substr(0,f));
		return str.length > 0 ? str : false;
	},
	// Remove spaces from start or end of a string
	_trim:function(str) {
		return str.replace(/(^ +)|( +$)/g,'');
	},
	_searchResultFilter:function(rawstr,cacheitem) {
		var	cache = [],
			lines = rawstr.split('\n');

		//Treat each line...
		for (var l in lines) {
			lines[l] = lines[l].split('~');
			cache[l] = {
				urlpart:lines[l].shift(),
				urlname:lines[l].shift(),

				// Main list uses only 2 indexes (URL and description);
				// So, the other data found that remain from third index
				// should be processed from an specific submenu handler.
				// The return of this processing is stored below.
				subinfo: lines[l] && typeof(this.subinfo.store) == 'function' ? this.subinfo.store(lines[l]) : false
			};
		};
		this.ref.input.suggest.cache[cacheitem] = cache;
	},
	// Generates simplified list with form select field behavior
	_listGenSimple:function (cachestr) {
		var	cache = this.ref.input.suggest.cache[cachestr],
			ul = '<ul></ul>',
			self = this,
			li,ulobj,a,wrap1=wrap2=match=false,
			tempevent = false,
			typed = this.ref.input.val(),
			length = 0,
			letter,value,str;
		
		if(this.dom.box){
			this.dom.box.append(ul);
			ulobj=$('ul',this.dom.box);
			
			for (var i in cache) if (length < this.limit) {
				matched = this._highlightMatch(typed,cache[i].urlname);
				matched_simple = this._simpleMatch(typed,cache[i].urlname);
				if (matched) {
					li = $('<li>'+matched+'<abbr title="'+cache[i].urlname+'" class="icoHover"></abbr></li>').appendTo(ulobj);
					li[0].suggestinfo=cache[i];
					length++;
				};
			}
			$('ul li',this.dom.box).bind('mousedown',function(){
				self.ref.input.val($('abbr',this).attr('title'));
				self.close();
			});
			if ($('ul li',this.dom.box).length < 1) {
				this.close();
				return false;
			};
			this.dom.box.show();
		}
	},
	// This function mounts the main suggest list shown
	_listGen: function (cachestr) {
		if(!this.dom.box) return false;
		var	cache = this.ref.input.suggest.cache[cachestr],
			ul = '<ul></ul>',
			self = this,
			li,ulobj,a,wrap1=wrap2=match=false,
			tempevent = false,
			typed = this.ref.input.val(),
			length = 0,
			msg;
			
		this.dom.box.append(ul);
		ulobj=$('ul',this.dom.box);
		switch (country) {
			case 'ar':
				msg = 'Ver más resultados...';
				break;
			case 'br':
				msg = 'Ver mais resultados...';
				break;
			default:
				msg = 'See more results...';
				break;
		};
		for (var i in cache) if (length < this.limit){
			matched = this._highlightMatch(typed,cache[i].urlname);
			matched_simple = this._simpleMatch(typed,cache[i].urlname);
			if (matched) {
				li = $('<li><a href="/'+cache[i].urlpart+'/" class="icoHover"><i></i>'+matched+'</a><abbr title="'+matched_simple+'" class="icoHover"></abbr></li>').appendTo(ulobj);
				li[0].suggestinfo=cache[i];
				length++;
			};
		};		
                if (length > 0) {
                	$('<li class="more"><a href="/search.php?t=art&noredir=1&q='+typed+' "><b>'+msg+'</b></a></li>').appendTo(ulobj);
		};
		if (typeof(this.subinfo.draw) == 'function') {
			$('ul li',this.dom.box).bind('mouseover',function(){
				$('li',$(this).parent()).removeClass('selected');
				$(this).addClass('selected');
				if(!$(this).hasClass('more'))
					self.subinfo.draw(this);
				else
					self.subinfo.subclose();
			});					
		};
		$('ul li',this.dom.box).bind('mousedown',function(){
			location.href = $('a',this).attr('href');
		});
		
		if ($('ul li',this.dom.box).length < 1) {
			this.close();
			return false;
		};
		
		this.dom.box.show();
		
	},
	// Simplify text for match and to correspond to remote search files
	_strSimplify: function(str,f) {
		if (!str) return false;
		str=str.toLowerCase();
		var RE={a:/[àáãäâ]/g, e:/[èéëêæ]/g, i:/[ìíïî]/g, o:/[òóõöôø]/g,
			u:/[ùúüû]/g, c:/[ç]/g, n:/[ñ]/g, " ":/[- \\\/+,.:;`´'"?!¡¿&%]+/g };
		for (var re in RE) {
			str = str.replace(RE[re],re);	
		};
		str = str.replace(/ /g,'');
		if (f) str = this._trim(str.substr(0,f));
		return str.length > 0 ? str : false;
	},
	_simpleMatch:function(str,phrase) {
		var phraseSimpleStr;
		if (!phrase) return false;
		str = str.replace(new RegExp("[- \\*\/,.:;'\"?!¡¿]+","g"), '');
		str = this._strSimplify(str);
		phraseSimpleStr = phrase.replace(' ', ''); 
		phraseSimpleStr = this._strSimplify(phraseSimpleStr);
		if (phraseSimpleStr.substr(0,str.length) == str) {
			return phrase;
		}	
	},	
	// Match str, turning bold the matched parts 
	_highlightMatch: function (str,phrase) {
		if (!phrase) return false;
		var phraseSimpleStr, bolded;

		// Changes str to be an RegularExpression
		str = str.replace(/[- \\*\\\[\\\]\\\(\\\)\\/,.:;'"?!¡¿]+/g, '');
		str = this._strSimplify(str);
		if (str.length > 1) str = str.replace(/(.)/g, '$1[- \\/,.:;\'"?!¡¿]*');

		// Turn phrase simple as str and match them
		phraseSimpleStr = this._strSimplify(phrase);
		
		matched = phraseSimpleStr.match(RegExp(str));
		if (matched == null) return false;
		matched = matched.toString();
		matched = phrase.substr(phraseSimpleStr.indexOf(matched),matched.length);

		// Search the matched string in the original phrase state
		matched = phrase.match(RegExp(matched,"i"));

		// Change matched string to a bold format
		bolded = phrase.replace(RegExp(matched,"i"),"<b>"+matched+"</b>");

		return bolded;

	},
	// Função de compatibilidade
	unset: function() {
		if (this.ref.input) {
			this.ref.input.unbind('keyup');
			this.ref.pos = undefined;
		};
		//DOM.event.rmv(document,this._bindingEvent,this.keyBindings);
		this.close();
	}
};
function OAS_VARS(OAS_page, OAS_pos) {
	OAS_site = 'www.vagalume.com.br';
	OAS_sitepage = OAS_site + OAS_page;
	OAS_listpos = OAS_pos;
};

OAS_url = 'http://adserver.ig.com.br/RealMedia/ads/';
OAS_query = '';
OAS_target = '_blank';
OAS_version = 10;
OAS_rn = '001234567890';
OAS_rns = '1234567890';
OAS_rn = new String(Math.random());
OAS_rns = OAS_rn.substring(2, 11);

function OAS_NORMAL (pos) {
	document.write('<a href="' + OAS_url + 'click_nx.ads/' + OAS_sitepage + '/1' + OAS_rns + '@' + OAS_listpos + '!' + pos + '?' + OAS_query + '" target="'+ OAS_target + '">');
	document.write('<img src="' + OAS_url + 'adstream_nx.ads/' + OAS_sitepage + '/1' + OAS_rns + '@' + OAS_listpos + '!' + pos + '?' + OAS_query + '" border="0"></a>');
};

function OAS_START() {
	OAS_version = 11;
	if (navigator.userAgent.indexOf('Mozilla/3') != -1 || navigator.userAgent.indexOf('Mozilla/4.0 WebTV') != -1) {
		OAS_version = 10;
	};
	if (OAS_version >= 11) {
		document.write('<SCRIP' + 'T LANGUAGE=JavaScript1.1 SRC="' + OAS_url + 'adstream_mjx.ads/' + OAS_sitepage + '/1' + OAS_rns + '@' + OAS_listpos + '?' + OAS_query + '"><\/SCRIP' + 'T>');
	};
};

document.write('');
function OAS_AD(pos){
	try {
		if (OAS_version >= 11) {
			OAS_RICH(pos);
		} else {
			OAS_NORMAL(pos);
		};
	} catch (err) {
		OAS_NORMAL(pos);
	}
};
