// Confirmacao de Exclusao de Produto
function confirmation(id) {
	 resposta = confirm ("Deseja excluir realmente ?")
    if (resposta)
       document.location.href = "/administrador/produtos/excluirProduto?id="+id;
}

function confEmail(id) {
	 resposta = confirm ("Deseja excluir realmente ?")
    if (resposta)
       document.location.href = "/administrador//newsletter/excluirEmail?id="+id;
}

// Confirmacao de Exclusao de Categoria
function confirmationCategoria(id) {
	 resposta = confirm ("Deseja excluir realmente ?")
    if (resposta)
       document.location.href = "/administrador/produtos/excluirCategoria?id="+id;
}

// Funcao de validacao do formulario Comprar
function ValidaFormulario () {	

// Nome
	if (document.form_comprar.from_name.value == ""){		
		alert ("Digite seu nome !");
		document.form_comprar.from_name.focus();
		return false;
	}
				
// Email

	if (document.form_comprar.from_email.value=="" 
		|| document.form_comprar.from_email.value.indexOf("@")== -1
		|| document.form_comprar.from_email.value.indexOf(".")==-1)
		{
			alert("O campo E-mail deve ser conter um endereco eletronico!");
			document.form_comprar.from_email.focus();
			return false;
	}

// Telefone

	if (document.form_comprar.telefone.value=="" ) { 
		alert("Digite o Telefone"); 
		document.form_comprar.telefone.focus(); 
		return false;
	}
	
	if (isNaN(document.form_comprar.telefone.value)){
		alert("O campo Telefone deve conter apenas n&uacute;meros!");
		document.form_comprar.telefone.focus();
		return false;
	}							

// Endereco
	
	if (document.form_comprar.endereco.value==""){
		alert("Digite o endere&ccedil;o");
		document.form_comprar.endereco.focus(); 
		return false;
	}

// Cep
	if (document.form_comprar.cep.value==""){
		alert ("Digite o cep");
		document.form_comprar.cep.focus();
		return false;
	}

	return true;
}

// Funcao de validacao do formulario Contato	

function ValidaFormularioContato() {	
	// Nome
	if (document.form_contato.nome.value == ""){		
		alert ("Digite seu nome !");
		document.form_contato.nome.focus();
		return false;
	}
				
	// Email
	if (document.form_contato.mail.value=="" 
		|| document.form_contato.mail.value.indexOf("@")== -1
		|| document.form_contato.mail.value.indexOf(".")==-1){
			alert("O campo E-mail deve ser conter um endereco eletronico!");
			document.form_contato.mail.focus();
			return false;
	}
	
	// Cidade
	if (document.form_contato.cidade.value=="" ) { 
		alert("Digite o Cidade"); 
		document.form_contato.cidade.focus(); 
		return false;
	}
// Mensagem
	if (document.form_contato.mensagem.value=="" ) { 
		alert("Digite sua mensagem"); 
		document.form_contato.mensagem.focus();		
		return false;
	}
	return true;
}

/*
**************************************
* Event Listener Function v1.4       *
* Autor: Carlos R. L. Rodrigues      *
**************************************
*/
addEvent = function(o, e, f, s){
	var r = o[r = "_" + (e = "on" + e)] = o[r] || (o[e] ? [[o[e], o]] : []), a, c, d;
	r[r.length] = [f, s || o], o[e] = function(e){
		try{
			(e = e || event).preventDefault || (e.preventDefault = function(){e.returnValue = false;});
			e.stopPropagation || (e.stopPropagation = function(){e.cancelBubble = true;});
			e.target || (e.target = e.srcElement || null);
			e.key = (e.which + 1 || e.keyCode + 1) - 1 || 0;
		}catch(f){}
		for(d = 1, f = r.length; f; r[--f] && (a = r[f][0], o = r[f][1], a.call ? c = a.call(o, e) : (o._ = a, c = o._(e), o._ = null), d &= c !== false));
		return e = null, !!d;
    }
};

removeEvent = function(o, e, f, s){
	for(var i = (e = o["_on" + e] || []).length; i;)
		if(e[--i] && e[i][0] == f && (s || o) == e[i][1])
			return delete e[i];
	return false;
};

/*
**************************************
* formatCurrency Function v1.1       *
* Autor: Carlos R. L. Rodrigues      *
**************************************
*/

//========================================================
// REQUIRES http://www.jsfromhell.com/geral/event-listener
//========================================================

function formatCurrency(o, n, dig, dec){
	o.c = !isNaN(n) ? Math.abs(n) : 2;
	o.dec = typeof dec != "string" ? "," : dec, o.dig = typeof dig != "string" ? "." : dig;
	addEvent(o, "keypress", function(e){
		if(e.key > 47 && e.key < 58){
			var o, s, l = (s = ((o = this).value.replace(/^0+/g, "") + String.fromCharCode(e.key)).replace(/\D/g, "")).length, n;
			if(o.maxLength + 1 && l >= o.maxLength) return false;
			l <= (n = o.c) && (s = new Array(n - l + 2).join("0") + s);
			for(var i = (l = (s = s.split("")).length) - n; (i -= 3) > 0; s[i - 1] += o.dig);
			n && n < l && (s[l - ++n] += o.dec);
			o.value = s.join("");
		}
		e.key > 30 && e.preventDefault();
	});
}

function loadComboCategoria(obj, id)
{
	obj.onchange = createComboCategoria;

	if ( id )
	{
		var dados = new Ajax();
		dados.url = '/administrador/categorias/getRecursive?id=' + id;
		dados.method = 'get';
		dados.responseType = 'html';
		dados.handler = function()
		{
			eval('objJson = ' + dados.response);
			obj.value = objJson[0]['Categoria']['id'];
			createComboCategoria(false, obj);
		}
		dados.Send();
	}
}

function createComboCategoria(e, obj)
{
	var returno = false;
	
	if (!obj) obj = this;
	conteudo = obj.parentNode;

	var dados = new Ajax();
	dados.url = '/administrador/categorias/get?id=' + obj.value;
	dados.method = 'get';
	dados.responseType = 'html';
	dados.handler = function()
	{
		var idDiv = eval(conteudo.id) + 1;
		if ( !document.getElementById(idDiv) )
		{
			var objDiv = document.createElement('SPAN');
			objDiv.id = idDiv;
		}
		else
		{
			var objDiv = document.getElementById(idDiv);
			for ( var j = objDiv.childNodes.length-1; j > -1; j-- )
				objDiv.removeChild(objDiv.childNodes[j]);
		}
		
		eval('objJson = ' + dados.response);
		if ( objJson.length > 0 )
		{
			var select = document.createElement('SELECT');
			select.onchange = createComboCategoria;
			select.setAttribute('name', 'Produto[categoria_id]');
			var option = document.createElement('OPTION');
			option.value = objJson[0]['Categoria']['categoria_id'];			
			select.appendChild(option);
			for ( var i = 0; i < objJson.length; i++ )
			{
				var option = document.createElement('OPTION');
				option.setAttribute('value', objJson[i]['Categoria']['id']);
				option.innerHTML = objJson[i]['Categoria']['nome'];
				select.appendChild(option);
			}
			
			objDiv.appendChild(select);
			conteudo.appendChild(objDiv);
		}
	}
	return dados.Send();
}

/*function alterarDestaque(id, obj)
{
	var dados = new Ajax();
	dados.url = '/administrador/home/alterarDestaque?id=' + id + '&status=' + ((obj.checked)?'adiciona':'remove');
	dados.method = 'get';
	dados.responseType = 'html';
	dados.handler = function()
	{
	}

	dados.Send();
	setTimeout("refresh()", 1000);
}*/

function refresh()
{
	history.go(0);
}

function loadTableEmail()
{
	var table = document.getElementById('emails');

	var trs = table.getElementsByTagName('TR');
	for ( var i = 0; i < trs.length; i++ )
	{
		var td = trs[i].getElementsByTagName('TD')[0];
		td.ondblclick = alterarEmail;
	}
}

function alterarEmail()
{
	alert(this.parentNode);
	var inputHidden = document.createElement('INPUT');
}

function alterarLogo(imgAtual)
{
	htmlContent = "<center><h1>Upload de imagem</h1><form action=\"/administrador/home/uploadImagem\" method=\"post\" enctype=\"multipart/form-data\">" +
			"<input type=\"hidden\" name=\"imagem_atual\" value=\""+ imgAtual +"\" />" +
			"<label>Imagem da home <small style=\"color:#f00;\">(992 x 220)</small>:</label>" +
			"<input type=\"file\" name=\"home\" /><br />" +
			"<br /><input type=\"submit\" value=\"EwindowModalnviar\" />&nbsp;<input type=\"button\" value=\"Fechar\" onClick=\"windowModal.close();\" />" +
			"</form></center>";
	
	windowModal.setShadowOffset(5);
	windowModal.setCssClassMessageBox(false);
	windowModal.setSize(380,120);
	windowModal.setShadowDivVisible(true);
	windowModal.setHtmlContent(htmlContent);
	windowModal.display();
}
function alterarImagem(imgAtual)
{
	htmlContent = "<center><h1>Upload de imagem</h1><form action=\"/administrador/oficina/uploadImagem\" method=\"post\" enctype=\"multipart/form-data\">" +
			"<input type=\"hidden\" name=\"imagem_atual\" value=\""+ imgAtual +"\" />" +
			"<label>Imagem da oficina:</label>" +
			"<input type=\"file\" name=\"oficina\" /><br />" +
			"<br /><input type=\"submit\" value=\"EwindowModalnviar\" />&nbsp;<input type=\"button\" value=\"Fechar\" onClick=\"windowModal.close();\" />" +
			"</form></center>";
	
	windowModal.setShadowOffset(5);
	windowModal.setCssClassMessageBox(false);
	windowModal.setSize(380,120);
	windowModal.setShadowDivVisible(true);
	windowModal.setHtmlContent(htmlContent);
	windowModal.display();
}
function alterarDestaque(indice)
{
	htmlContent = "<table width=\"100%\">" +
			"<tr>" +
			"<td>" +
			"<b>Produto:</b> <input type=\"text\" id=\"produto\" /> <input type=\"hidden\" id=\"pagina\" value=\"1\" />" +
			"<input type=\"button\" value=\"Buscar\" onClick=\"buscarProdutos(true);\" />" +
			"</td>" +
			"<td align=\"right\"><input type=\"button\" value=\"Fechar\" onClick=\"windowModal.close();\" /></td>" +
			"</tr>" +
			"</table>" +
			"<div id=\"produtos\"></div>" +
			"<form action=\"/administrador/home/alterarDestaque\" method=\"post\" id=\"form\">" +
			"<input type=\"hidden\" name=\"indice\" value=\"" + indice + "\" /><input type=\"hidden\" name=\"id\" />" +
			"</form>";
	windowModal.setShadowOffset(5);
	windowModal.setCssClassMessageBox(false);
	windowModal.setSize(600,400);
	windowModal.setShadowDivVisible(true);
	windowModal.setHtmlContent(htmlContent);
	windowModal.display();
}
function alterarPropaganda(indice)
{		
	htmlContent = "<center><h1>Upload de imagem</h1><form action=\"/administrador/home/uploadImagemProgaganda\" method=\"post\" enctype=\"multipart/form-data\">" +			
			"<input type=\"hidden\" name=\"id\"  value=\""+indice+"\" />" +
			"<label>Imagem da propaganda:</label>" +
			"<input type=\"file\" name=\"propaganda\"/><br />" +
			"<label>Link: http://</label>" +
			"<input type=\"text\" name=\"link"+indice+"\" size=\"50\"/><br />" +
			"<br /><input type=\"submit\" value=\"EwindowModalnviar\" />&nbsp;<input type=\"button\" value=\"Fechar\" onClick=\"windowModal.close();\" />" +
			"</form></center>";
				
	windowModal.setShadowOffset(5);
	windowModal.setCssClassMessageBox(false);
	windowModal.setSize(380,120);
	windowModal.setShadowDivVisible(true);
	windowModal.setHtmlContent(htmlContent);
	windowModal.display();
}

function adicionarProduto(posicao, tipo, template)
{
	htmlContent = "<table width=\"100%\">" +
	"<tr>" +
	"<td>Busca: <input type=\"text\" id=\"produto\" /> <input type=\"hidden\" id=\"pagina\" value=\"1\" /> <input type=\"button\" value=\"Buscar\" onClick=\"buscarProdutos(true, 'email');\" /></td>" +
	"<td align=\"right\"><input type=\"button\" value=\"Fechar\" onClick=\"windowModal.close();\" /></td>" +
	"</tr>" +
	"</table>" +
	"<div id=\"produtos\"></div>" +
	"<input type=\"hidden\" id=\"template\" value=\"" + template + "\" />" +
	"<input type=\"hidden\" id=\"posicao\" value=\"" + posicao + "\" />" +
	"<input type=\"hidden\" id=\"tipo\" value=\"" + tipo + "\" />";
	
	windowModal.setShadowOffset(5);
	windowModal.setCssClassMessageBox(false);
	windowModal.setSize(600,400);
	windowModal.setShadowDivVisible(true);
	windowModal.setHtmlContent(htmlContent);
	windowModal.display();
}

function carregaProduto(id)
{
	var posicao = document.getElementById('posicao').value;
	var tipo = document.getElementById('tipo').value;
	var template = document.getElementById('template').value;
	
	var dados = new Ajax();
	dados.url = '/administrador/produtos/carregaProdutoEmail?id=' + id + '&tipo=' + tipo + '&posicao=' + posicao + '&template=' + template;
	dados.method = 'get';
	dados.responseType = 'html';
	dados.handler = function()
	{
		document.getElementById(tipo+posicao).innerHTML = dados.response;
		windowModal.close();
	}
	dados.Send();
}

function buscarProdutos(botaoOK, tipo)
{
	var pagina = document.getElementById('pagina');
	if ( botaoOK )
		pagina.value = 1;
	
	var produto = document.getElementById('produto');
	
	var dados = new Ajax();
	dados.url = '/administrador/produtos/findAll?produto=' + produto.value + '&pagina=' + pagina.value + ( (tipo)?'&tipo=' + tipo:'' );
	dados.method = 'get';
	dados.responseType = 'html';
	dados.handler = function()
	{
		var produtos = document.getElementById('produtos');
		produtos.innerHTML = dados.response;
	}
	dados.Send();
}

function openPopup(url, width, height)
{
	width = (width)?width:400;
	height = (height)?height:200;
	
	var horizontal = (eval(screen.width) / 2) - (eval(width)/2);
	var vertical = (eval(screen.height) / 2) - (eval(height)/2);
	
	features = 'menubar=no,resizable=no,scrollbars=no,status=no,titlebar=no,toolbar=no,width='+width+',height='+height+',top='+vertical+',left='+horizontal;
	
	if ( url.indexOf('?') >= 0 )
		url+= '&';
	else
		url+= '?';
	
	url+= 'display=popup';
	
	window.open(url, 'popup', features);
}

function removeImagem(path)
{
	var img = new Image(0);
	img.src = '/administrador/produtos/deleteImage?path=' + path;

	er = /([0-9]+)\.jpg$/;
	var id = path.match(er)[1];
	document.getElementById('a' + id).style.display = 'none';
	document.getElementById('img' + id).style.display = 'none';
}

function carregaJS()
{
	if ( document.getElementById('emails') )
		loadTableEmail();

	if ( document.getElementById('mainMenu') )
		initMenu();

	if ( document.getElementById('dhtmlgoodies_menu') )
		initDhtmlGoodiesMenu();

	if ( document.getElementById('map') )
		loadMap();
		
	if ( document.getElementById('arrow_left') )
		initSlideShow();
		
	if ( document.getElementById('googleAnalytics') )
		__utmSetTrans();
	
	if ( document.getElementById('dhtmlgoodies_slidedown_menu') )	
		initSlideDownMenu();				
}


function validaFormProduto(form)
{
	var combos = form.getElementsByTagName('SELECT');
	if ( combos.length > 1 )
	{
		campo = combos[combos.length - 2];
		if ( campo.value.length ==  0 )
		{
			alert('Informe a categoria');
			campo.focus();
			return false;
		}
	}

	var campo = document.getElementById('produto_nome');
	if ( campo.value.length == 0 )
	{
		alert('Informe o nome.');
		campo.focus();
		return false;
	}

	var campo = document.getElementById('produto_preco');
	if ( campo.value.length == 0 )
	{
		alert('Informe o preço.');
		campo.focus();
		return false;
	}
	
	return true;
}

function validaFormAlterarSenha(form, id)
{
	var campo = form.atual;

	var dados = new Ajax();
	dados.url = '/administrador/usuario/senhaAtual?senha=' + campo.value + '&id=' + id;
	dados.method = 'get';
	dados.responseType = 'html';
	
	dados.handler = function()
	{
		if ( dados.response == 'OK' )
			alert();
	}
	dados.Send();
	
	return false;
}

function alterarSenha(id)
{
	htmlContent = '<form action="/administrador/usuario/alterarSenha" method="post" onSubmit="return validaFormAlterarSenha(this, ' + id + ')">' +
		'<table align="center">' +
		'<tr><td align="right"><b>Senha atual:</b></td><td><input type="password" name="atual" /></td></tr>' +
		'<tr><td align="right"><b>Nova senha:</b></td><td><input type="password" name="nova" /></td></tr>' +
		'<tr><td align="right"><b>Confirma:</b></td><td><input type="password" name="confirma" /></td></tr>' +
		'<tr><td colspan="2" align="center"><input type="submit" value="Alterar" /> <input type=\"button\" value=\"Fechar\" onClick=\"windowModal.close();\" /></td></tr>' +
		'</table>' +
		'</form>';

	windowModal.setShadowOffset(5);
	windowModal.setCssClassMessageBox(false);
	windowModal.setSize(220,90);
	windowModal.setShadowDivVisible(true);
	windowModal.setHtmlContent(htmlContent);
	windowModal.display();
}

windowModal = new DHTML_modalMessage();
window.onload = carregaJS;