/**
 * Javascripts Base, será carregado em todas as páginas indiferentemente do conteúdo
 */
 
var timeout = null;
function flash(msg, error){
	if (msg) {
		$('flashMensagem').innerHTML = msg;
		$('flash').show();
		posicionaFlash();
		flashTimeOut();
	}
	else 
		if ($('flash').style.display != 'none') {
			$('flash').hide();
			window.clearTimeout(timeout);
		}	
}

function flashTimeOut() {
	if (timeout != null)
		window.clearTimeout(timeout);
	timeout = window.setTimeout("flash()", 15000);
}

function posicionaFlash(){
	var width = $('flash').offsetWidth;
	var screen_width = document.body.clientWidth;
	var left = screen_width/2 - width/2;
	$('flash').style.left = left + 'px';
}

function evalJSON (json) {
	return eval("(" + json + ")");
}

function clearCDATA (string) {
	while (string.include('//<![CDATA[')) {
		string = string.replace('//<![CDATA[', '');
		string = string.replace('//]]>', '');
	}	
	return string;
}

function evalJS (string) {
	string = clearCDATA(string);
	string.evalScripts();
}

var loginShown = false;

function login () {
	toggleLinkLoginClass(true);
	var duration;
	
	if (loginShown) {
		loginShown = false;
		duration = 0.3;
		new Effect.BlindUp('caixa-login', {
			duration: duration,
			scaleX: true,
			scaleY: false,
			scaleContent: true
		});
	}
	else {
		loginShown = true;
		duration = 0.5;
		new Effect.BlindDown('caixa-login', {
			duration: duration,
			scaleX: true,
			scaleY: false,
			scaleContent: true
		});
	}
	
	window.setTimeout('toggleLinkLoginClass(false)', duration * 1000);
}

function toggleLinkLoginClass (desativar) {	
	$('link-login').toggleClassName('link-inativo');
	
	if (desativar)
		$('link-login-a').onclick = function() {};
	else
		$('link-login-a').onclick = function() {
			login();
			return false;
		};
}

function toggleLinkLogoutClass (hover) {
	if (hover)
		$('texto-logout-link').style.textDecoration = 'underline';
	else
		$('texto-logout-link').style.textDecoration = '';
}

function focusEmail (msg) {
	if ($('form-login-email').value == msg)
		$('form-login-email').value = '';
}

function focusSenha (msg) {
	if ($('form-login-senha').value == msg)
		$('form-login-senha').value = '';
}

function blurSenha(e) {
	if ((e.keyCode == 9) && !(e.ctrlKey) && !(e.shiftKey)) {
		$('saveCookie-checkbox').focus();
		return false;
	}
}

function focusBusca (msg) {
	if ($('form-busca-input').value == msg)
		$('form-busca-input').value = '';
}

function loginLoading () {
	$('form-login-botao-ok').toggle();
	$('form-login-carregando').toggle();
}

function loginComplete (request) {	
	var resp = evalJSON(request.responseText);

	if (resp.error) {
		loginLoading();
		flash(resp.error);
	}
	else {
		window.location.reload();
	}
}

function toggleBotaoMaisClass (botao) {
	botao.toggleClassName('botao-mais-over');
	botao.toggleClassName('botao-mais-active');
}

function toggleLinkClass (id, hover) {	
	if (hover)
		$(id).style.textDecoration = 'underline';
	else
		$(id).style.textDecoration = '';
}

function selectCheckbox(id) {
	var browser = navigator.appName;
	
	if (browser == "Microsoft Internet Explorer")
		$(id).click();
}

function nl2br (str) { 
    return str.replace(/\n/g, '<br />\n');
}

function adicionarRemoverProduto(request, id) {
	var resp = evalJSON(request.responseText);
	
	flash(resp.mensagem);	
	if (resp.retorno == '1') {		
		$('div-participar-produto-' + resp.produto_id).innerHTML = resp.html;
		evalJS(resp.html);
		if (resp.action == 'add') {
			$('link-avocar').show();
			$('link-avocar-com-aviso').hide();
		}
		else {
			if ($('links-avocar').visible()) {
				$('link-avocar').hide();
				$('link-avocar-com-aviso').show();
			}
			else {
				$('link-cancelar-avocar').hide();
				$('links-avocar').show();
				$('link-avocar').hide();
				$('link-avocar-com-aviso').show();
			}
		}
	}
}

function avocarAdmProduto(request) {	
	var resp = evalJSON(request.responseText);
	
	flash(resp.msg);	
	if (resp.ok) {
		$('links-avocar').toggle();
		$('link-cancelar-avocar').toggle();
	}
}

function adjustCharCounter(id, max) {
	if ($(id).getWidth() <= 0) {
		var width = parseInt($(id).style.width.sub('px', '')) + 6;
		$(id + '-counter').setStyle({width: width + 'px'});
	}
	else 
		$(id + '-counter').setStyle({width: $(id).getWidth() + 'px'});
	decreaseCharCounter(id, max);
}

function decreaseCharCounter(id, max) {
	var chars = $(id).getValue().length;
	
	if (chars > max) {
		$(id).value = $(id).getValue().truncate(max, '');
		$(id).scrollTop = 10000;
	}
	else 
		$(id + '-counter-value').innerHTML = max - chars;
}

function getElementsByName_iefix(tag, name) {
	var elem = document.getElementsByTagName(tag);
	var arr = new Array();
	for(i = 0, iarr = 0; i < elem.length; i++) {
		att = elem[i].getAttribute("name");
		if(att == name) {
			arr[iarr] = elem[i];
			iarr++;
		}
	}
	return arr;
}



function mostraAviso(mensagem) {
	if(navigator.appName == "Microsoft Internet Explorer")
		screenY = document.documentElement.scrollTop + 120;
	else
		screenY = window.pageYOffset + 120;
		
	apagaSelects();

	var width = 5 + document.body.clientWidth;
	var height = document.body.clientHeight;
	
	$('caixa-aviso-texto').innerHTML = mensagem;
	
	$('fundo-opaco').style.width = width + 'px';
	$('fundo-opaco').style.height = height + 'px';		

	$('caixa-aviso').style.top = screenY + 'px';
	$('caixa-aviso').style.left = width/2 - 200 + 'px';
	
	$('fundo-opaco').style.display = 'block';
	$('caixa-aviso').style.display = 'block';
}

		
function escondeAviso() {
	$('fundo-opaco').style.display = 'none';
	$('caixa-aviso').style.display = 'none';
	mostraSelects();
}
	
function apagaSelects(){

	if (!document.all)
		return;
 	for (var i = 0; i < document.all.length; i++) {
  		o = document.all(i);
  		if (o.type == 'select-multiple') {
	   		if (o.style) o.style.display = 'none';
	  	}
	  	if (o.type == 'select-one') {
	   		if (o.style) o.style.display = 'none';
	  	}
 	}
}
function mostraSelects(){
	if (!document.all) 
		return;
	for (var i = 0; i < document.all.length; i++) {
		o = document.all(i);
		if (o.type == 'select-one') {
			if (o.style) 
				o.style.display = '';
		}
		if (o.type == 'select-multiple') {
			if (o.style) 
				o.style.display = '';
		}
	}
}


/*
 * Funções de contador de caracteres do TinyMCE
 */
function adjustCharCounterTinyMCE(e) {
	if(e.type == 'keyup') {
		decreaseCharCounterTinyMCE(2000);
	}
	return true; // Continue handling
}

function startCharCounterTinyMCE() {
	decreaseCharCounterTinyMCE(2000);
	return true; // Continue handling
}
	
function clean(content) { 
    content = content.replace(/<(.+?)>/g, '');//remove html
    content = content.replace('&nbsp;', ' ', 'g');//replace &nbsp; with space
    content = content.replace(/&(.*);/g, '1');//convert entities to single character
    return content;
}

function countChars(content) {
    var total = 0;
    total = content.length;
    return total;
}
	
function decreaseCharCounterTinyMCE(max) {

	var chars = countChars(tinyMCE.activeEditor.getContent());
	
	if (chars > max) {
		$('counter-value').style.color = '#CE5C5C';
		$('counter-value').innerHTML = '(' + avisoCharCounter + ') ' + (max - chars) ;
	}
	else {
		$('counter-value').style.color = '#999999';
		$('counter-value').innerHTML = max - chars;
	}
}

function defineBg(url, padrao, attachment, repeat, position_vertical, position_horizontal, color) {
	if (repeat == 'norepeat')
		repeat = 'no-repeat';
	
	bg_url = '';	
	if (padrao == 0)
		bg_url = ' url(' + url + ') ';
	
	var bg = color + bg_url  + ' ' + attachment + ' ' + repeat + ' ' + position_vertical + ' ' + position_horizontal;

	$('bg').setStyle({
		'background': bg
	});
}

function setDivWidthAndHeight(id) {
	$(id).setStyle({
		'width': ($(id).getWidth() - 14) + 'px',
		'height': ($(id).getHeight() - 10) + 'px'
	});
}

function addItemToListHome(text) {
	$('search-busca').value = text.innerHTML.stripTags().strip();
}

function addItemToListCabecalho(text) {
	$('form-busca-input').value = text.innerHTML.stripTags().strip();
}

/*
 * getCookie(): given a cookie name, get its value. Returns null if the cookie can't be found.
 * From http://www.webreference.com/js/column8/functions.html
 *
 */
function getCookie(name) {
  var dc = document.cookie;
  var prefix = name + "=";
  var begin = dc.indexOf("; " + prefix);
  if (begin == -1) {
    begin = dc.indexOf(prefix);
    if (begin != 0) return null;
  } else
    begin += 2;
  var end = document.cookie.indexOf(";", begin);
  if (end == -1)
    end = dc.length;
  return unescape(dc.substring(begin + prefix.length, end));
}
 
/*
 * utmvCookieCheck(): given a value, read the __utmv cookie and see if
 * that value is already set. Return true if so, false otherwise.
 *
 */
function utmvCookieCheck(value) {
	var utmvCookie = getCookie("__utmv"); 
 
	if (utmvCookie == null)
		return false;
 
	// get rid of the Google's domain prefix ID, which appear on all
	// GA cookies
	utmvCookie = utmvCookie.replace(/^\d*\./, '');
 
	return (utmvCookie == value) ? true : false;
}


