var _HTTP_PATH_ = "http://" + document.domain + "/";

function dump(arr,level) {
	var dumped_text = "";
	if(!level) level = 0;
	
	//The padding given at the beginning of the line.
	var level_padding = "";
	for(var j=0;j<level+1;j++) level_padding += "    ";
	
	if(typeof(arr) == 'object') { //Array/Hashes/Objects 
		for(var item in arr) {
			var value = arr[item];
			
			if(typeof(value) == 'object') { //If it is an array,
				dumped_text += level_padding + "'" + item + "' ...\n";
				dumped_text += dump(value,level+1);
			} else {
				dumped_text += level_padding + "'" + item + "' => \"" + value + "\"\n";
			}
		}
	} else { //Stings/Chars/Numbers etc.
		dumped_text = "===>"+arr+"<===("+typeof(arr)+")";
	}
	return dumped_text;
}

function validalink(obj){
    if(obj.value.substring(0,7)!="http://"){ 
        xx = obj.value;
        //obj.value = "http://"+xx;
    }
}

function MM_swapImgRestore(tmp) { //v3.0
    if (!tmp)
	var i,x,a=document.MM_sr;
    for(i=0;a&&i<a.length&&(x=a[i])&&x.oSrc;i++) x.src=x.oSrc;
}

function MM_preloadImages() { //v3.0
    var d=document;
    if(d.images){
	if(!d.MM_p) d.MM_p=new Array();
	var i,j=d.MM_p.length,a=MM_preloadImages.arguments;
	for(i=0; i<a.length; i++)
	    if (a[i].indexOf("#")!=0){
		d.MM_p[j]=new Image;
		d.MM_p[j++].src=a[i];
	    }
    }
}

function MM_showHideLayers() { //v6.0
    var i,p,v,obj,args=MM_showHideLayers.arguments;
    for (i=0; i<(args.length-2); i+=3) if ((obj=MM_findObj(args[i]))!=null) {
	v=args[i+2];
	if (obj.style) {
	    obj=obj.style;
	    v=(v=='show')?'visible':(v=='hide')?'hidden':v;
	}
	obj.visibility=v;
    }
}

function MM_findObj(n, d) { //v4.01
    var p,i,x;
    if(!d) d=document;
    if((p=n.indexOf("?"))>0&&parent.frames.length) {
	d=parent.frames[n.substring(p+1)].document;
	n=n.substring(0,p);
    }
    if(!(x=d[n])&&d.all) x=d.all[n];
    for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
    for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document);
    if(!x && d.getElementById) x=d.getElementById(n);
    return x;
}

function MM_swapImage() { //v3.0
    var i,j=0,x,a=MM_swapImage.arguments;
    document.MM_sr=new Array;
    for(i=0;i<(a.length-2);i+=3)
	if ((x=MM_findObj(a[i]))!=null){
	    document.MM_sr[j++]=x;
	    if(!x.oSrc) x.oSrc=x.src;
	    x.src=a[i+2];
	}
}

function init()
{
    switch (document.domain)
    {
	case 'www.magicwebdesign.com.br':
	    _HTTP_PATH_ += "dev/bagozzi/public/";
	    break;
	case '192.168.0.200':
	    _HTTP_PATH_ += "dev/bagozzi.edu.br/public/";
	    break;
	default:
	    _HTTP_PATH_ += "";
	    break;
    }
}

function abre_popup(foto, titulo)
{
    window.open(_HTTP_PATH_+'fotos.html?'+foto, titulo, 'width=100, height=100, status=no');
}

function desativaRegistro(obj, id, tipo, aux)
{
    if (tipo == 'operadores')
    {
	if (!confirm('Deseja mesmo '+obj.innerHTML.toLowerCase()+' esse operador?'))
	{
	    return false;
	}
    }

    if (aux != undefined)
    {
	id += '/tipo/'+aux;
    }

    var kw = {
	url:	_HTTP_PATH_+"admin/"+tipo+"/desativar/id/"+id,
	load:	function(data)
	{
	    dados = dojo.fromJson(data);
	    if (dados == 1)
	    {
		obj.parentNode.parentNode.parentNode.className += ' tab_inativo';
		obj.innerHTML = 'Ativar';
	    }
	    else if (dados == 2)
	    {
		var classe = obj.parentNode.parentNode.parentNode.className;
		classe = classe.toString().split(" ");
		obj.parentNode.parentNode.parentNode.className += classe[0];
		obj.innerHTML = 'Desativar';
	    }
	},
	error: function(data)
	{
	    console.debug("An error occurred: ", data);
	},
	timeout: 2000
    };

    dojo.xhrGet(kw);
}

function excluiRegistro(obj, id, tipo, aux, objlinha)
{
    if (!confirm('Deseja mesmo excluir este registro?')){
        return false;
    }
    xid = id;
    if (aux != undefined)
    {
	id += '/tipo/'+aux;
    }

    var kw = {
	url:	_HTTP_PATH_+"admin/"+tipo+"/excluir/id/"+id,
	load:	function(data)
	{
	    dados = dojo.fromJson(data);
	},
	error: function(data)
	{
	    console.debug("An error occurred: ", data);
	},
	timeout: 2000
    };

    dojo.xhrGet(kw);
    if(objlinha){
        objlinha.style.display='none';
    }
}

function modal (id, tipo)
{
    var kw = {
	url: _HTTP_PATH_+"admin/"+tipo+"/backups/id/"+id,
	load: function (data)
	{
	    dados = dojo.fromJson(data);
	    var conteudo = '';
	    var contador = 0;

	    dados.each(
		function(dado)
		{
		    switch (tipo)
		    {
			case 'galerias':
			    var id		= dado['galer_id'];
			    var data	= dado['galer_data'];
			    var titulo	= dado['galer_titulo'];
			    break;

			case 'noticias':
			    var id		= dado['notic_id'];
			    var data	= dado['notic_data'];
			    var titulo	= dado['notic_titulo'];
			    break;

			case 'conteudos':
			    var id		= dado['conte_id'];
			    var data	= dado['conte_data'];
			    var titulo	= dado['conte_titulo'];
			    break;
		    }

		    conteudo += "<div style='width:100px;float:left;margin:4px;text-align:center;'>";
		    conteudo += data;
		    conteudo += "</div>";

		    conteudo += "<div style='width:300px;float:left;margin:4px;'>";
		    conteudo += titulo;
		    conteudo += "</div>";

		    conteudo += "<div style='width:100px;;float:left;margin:4px;text-align:center;'>";

		    conteudo += "<a href='#' onclick='recuperarBackup("+id+", \""+tipo+"\");return false;'>";
		    conteudo += "<img src='imagens/ico-incluir-conteudo.gif' border='0' alt='Recuperar backup' title='Recuperar backup' style='margin-right:5px;' />";
		    conteudo += "</a>";

		    conteudo += "<a href='#' onclick='window.open(\""+_HTTP_PATH_+"admin/"+tipo+"/visualizar/"+id+"/backup\", \"JANELA\", \"width=550,height=450,toolbar=no,status=no,menubar=no,scrollbars=yes,resizable=no\");return false;'>";
		    conteudo += "<img src='imagens/icone_06.gif' border='0' alt='Visualizar' title='Visualizar' style='margin-bottom:3px;' />";
		    conteudo += "</a>";

		    conteudo += "</div>";

		    contador++;
		}
		);

	    $('total_backups').update(contador);
	    $('conteudoBackup').update(conteudo);
	},
	error: function(data)
	{
	    console.debug("An error occurred: ", data);
	},
	timeout: 2000
    };

    dojo.xhrGet(kw);
    Modal.show('divBackup',{
	color:'#6c6d6e',
	opacity:0.5
    });
}

function recuperarBackup (id, tipo)
{
    var kw = {
	url: _HTTP_PATH_+"admin/"+tipo+"/recuperarbackup/id/"+id,
	load: function (data)
	{
	    dados = dojo.fromJson(data);
	    if (dados == 1)
	    {
		alert('Backup recuperado com sucesso!');
		location.reload();
	    }
	    else if (dados == 2)
	    {
		alert('Backup recuperado com sucesso. Aguarde a aprovação!');
		location.reload();
	    }
	    else
	    {
		alert('Ocorreu um erro inexperado, tente novamente');
		return false;
	    }
	},
	error: function(data)
	{
	    console.debug("An error occurred: ", data);
	},
	timeout: 2000
    };

    dojo.xhrGet(kw);
    Modal.show('divBackup',{
	color:'#6c6d6e',
	opacity:0.5
    });
}

function ordenacao(id, acao, obj)
{
    var kw = {
	url: _HTTP_PATH_+"admin/galerias/ordenacao/id/"+id+"/acao/"+acao,
	load: function (data)
	{
	    dados = dojo.fromJson(data);
	    if (dados == 1)
	    {
		var tabela = dojo.byId('listagem');
		var linha_principal = obj.parentNode.parentNode.parentNode;
		var linha = (acao == 'sobe') ?
		linha_principal.rowIndex-1 :
		linha_principal.rowIndex+1;
		var linha_secundaria = tabela.rows[linha];

		swapNodes(linha_principal, linha_secundaria);
		var classe = 'tab_linha2';
		for (var i=1; i < tabela.rows.length; i++)
		{
		    classe = (classe == 'tab_linha2') ? 'tab_linha1' : 'tab_linha2';
		    dojo.removeClass(tabela.rows[i], 'tab_linha1');
		    dojo.removeClass(tabela.rows[i], 'tab_linha2');
		    dojo.removeClass(tabela.rows[i], 'tab_linha_over');
		    dojo.addClass(tabela.rows[i], classe);

		    tabela.rows[i].onmouseover = function()
		    {
			dojo.removeClass(this, classe);
			dojo.addClass(this, 'tab_linha_over');
		    }
		    tabela.rows[i].onmouseout = function()
		    {
			dojo.removeClass(this, 'tab_linha_over');
			dojo.addClass(this, classe);
		    }
		}
	    }
	},
	error: function(data)
	{
	    console.debug("An error occurred: ", data);
	},
	timeout: 2000
    };

    dojo.xhrGet(kw);
}

function ordenacaoMenus(id, acao, obj, tipo, menu, site, status)
{
//    if(jQuery(".tab_linha2")!= null){
//        jQuery(".tab_linha2").remove(); 
//    }
    
    
    var tabela = dojo.byId('tabela_conteudo');
    var linha_principal = obj.parentNode.parentNode.parentNode;
    var linha = (acao == 'sobe') ?
    linha_principal.rowIndex-1 :
    linha_principal.rowIndex+1;

    var linha_secundaria = tabela.rows[linha];

    var comparacao1 = linha_principal.id.split('_');
    var comparacao2 = linha_secundaria.id.split('_');

    if (comparacao1[0] == comparacao2[0])
    {
	var kw = {
	    url: _HTTP_PATH_+"admin/menus/ordenacao/id/"+id+"/acao/"+acao+"/tipo/"+tipo+"/menu/"+menu+"/site/"+site+"/status/"+status,
	    load: function (data)
	    {
		dados = dojo.fromJson(data);
		if (dados == 1)
		{
		    swapNodes(linha_principal, linha_secundaria);
		}
	    },
	    error: function(data)
	    {
		console.debug("An error occurred: ", data);
	    },
	    timeout: 2000
	};

	dojo.xhrGet(kw);
    }
}

function swapNodes(item1,item2)
{
    var itemtmp	= item1.cloneNode(1);
    var parent	= item1.parentNode;

    item2 = parent.replaceChild(itemtmp,item2);

    parent.replaceChild(item2,item1);
    parent.replaceChild(item1,itemtmp);
    itemtmp = null;

}

function validateForm (formid)
{
    var form = dijit.byId(formid);
    if (!form.validate())
    {
	alert("Verifique os campos marcados antes de continuar.");
	return false;
    }

    return true;
}

function validaSenhas (senha1, senha2)
{
    if(dijit.byId(senha1).value != dijit.byId(senha2).value)
    {
	alert("As senhas não conferem. Digite-as novamente");
	dijit.byId(senha1).setDisplayedValue('');
	dijit.byId(senha2).setDisplayedValue('');
	dijit.byId(senha1).focus();
	return false;
    }

    return true;
}

function excluirImagem (imagem, galeria, node, temp)
{
    temp = temp == '' ? null : temp;

    if (confirm ('Deseja mesmo excluir essa imagem?'))
    {
	var kw = {
	    url: _HTTP_PATH_+"admin/galerias/excluirimagem/imagem/"+imagem+"/galeria/"+galeria+"/tmp/"+temp,
	    load: function (data)
	    {
		dados = dojo.fromJson(data);
		if (dados == 1)
		{
		    node.style.display = 'none';
		}
	    },
	    error: function(data)
	    {
		console.debug("An error occurred: ", data);
	    },
	    timeout: 2000
	};

	dojo.xhrGet(kw);
    }
}

function carregarSubniveis (id, tipo, site, elemento)
{
    var tabela	= dojo.byId('tabela_conteudo');
    var index	= elemento.parentNode.rowIndex;
    var status	= jQuery('#status').val();

    if (tipo == 'menu')
    {
	var dojo_id		= 'smenu'+id+'_';
	var dados_pref	= 'smenu';
    }
    else if (tipo == 'submenu')
    {
	var dojo_id		= 'ssmen'+id+'_';
	var dados_pref	= 'ssmen';
    }

    if (dojo.byId(dojo_id+'0'))
    {
	var x			= 0;
	var condicao1	= true;

	jQuery.get(_HTTP_PATH_+"admin/menus/carregarsubniveis/id/"+id+"/tipo/"+tipo+"/acao/remove");

	if (tipo == 'menu')
	{
	    while (condicao1)
	    {
		if (tabela.rows[index+1].id.substring(0,5) != 'ssmen' &&
		    tabela.rows[index+1].id.substring(0,5) != 'smenu')
		    {
		    condicao = false;
		    break;
		}

		tabela.deleteRow(tabela.rows[index+1].rowIndex);
		x++;
	    }
	}
	else
	{
	    if (tipo == 'submenu')
	    {
		while (condicao1)
		{
		    if (tabela.rows[index+1].id.substring(0,5) != 'ssmen')
		    {
			condicao = false;
			break;
		    }

		    tabela.deleteRow(tabela.rows[index+1].rowIndex);
		    x++;
		}
	    }
	}
    }
    else
    {
	var url = _HTTP_PATH_+"admin/menus/carregarsubniveis/id/"+id+"/tipo/"+tipo+"/site/"+site+"/status/"+status;
	jQuery.getJSON(url, function(dados)
	{
	    for (var i=0; i<dados['items'].length; i++)
	    {
		if (tipo == 'menu')
		{
		    var span1 = '<span class="bot_link_cadastrar">'+
		    '<a href="'+_HTTP_PATH_+'admin/menus/formulario/setasub'+tipo+'/'+dados['items'][i]['id']+'" class="link1">'+
		    'Subsubmenu'+
		    '</a>'+
		    '</span>';
		}
									
		var span2 = '<span class="bot_link_altera">'+
		'<a href="'+_HTTP_PATH_+'admin/menus/formulario/sub'+tipo+'/'+dados['items'][i]['id']+'" class="link1">'+
		'Alterar'+
		'</a>'+
		'</span>';

		var span3 = '<span class="bot_link_exclui">'+
		'<a href="javascript: void(0)" onclick="desativaRegistro(this, \''+dados['items'][i]['id']+'\', \'menus\', \'sub'+tipo+'\');" class="link1">'+
		(dados['items'][i]['ativo'] == true ? 'Desativar' : 'Ativar') +
		'</a>'+
		'</span>';

		var span4 = '<span class="bot_link_conteudo">'+
		'<a href="'+_HTTP_PATH_+'admin/menus/visualizar/sub'+tipo+'/'+dados['items'][i]['id']+'" class="link1">'+
		'Ver'+
		'</a>'+
		'</span>';

		var span5 = '<span class="bot_link_cadastrar1">'+
		'<a href="'+_HTTP_PATH_+'admin/conteudos/formulario/sub'+tipo+'/'+dados['items'][i]['id']+'" class="link1">'+
		'Conteúdo'+
		'</a>'+
		'</span>';

		var span6 = '<span class="bot_link_sobe">'+
		'<a href="javascript:void(0);" onclick="ordenacaoMenus('+dados['items'][i]['id']+', \'sobe\', this, \'sub'+tipo+'\','+dados['items'][i]['menus_id']+','+dados['items'][i]['sites_id']+','+dados['status']+')" class="link1">'+
		'Sobe'+
		'</a>'+
		'</span>';

		var span7 = '<span class="bot_link_desce">'+
		'<a href="javascript:void(0);" onclick="ordenacaoMenus('+dados['items'][i]['id']+', \'desce\', this, \'sub'+tipo+'\','+dados['items'][i]['menus_id']+','+dados['items'][i]['sites_id']+','+dados['status']+')" class="link1">'+
		'Desce'+
		'</a>'+
		'</span>';
            
                var span8 = '<span class="bot_link_exclui">'+
		'<a href="javascript: void(0)" onclick="excluiRegistro(this, \''+dados['items'][i]['id']+'\', \'menus\', \'sub'+tipo+'\', document.getElementById(\''+dojo_id+i+'\'));" class="link1">'+
		'Excluir' +
		'</a>'+
		'</span>';

		var prefixo		= dados['items'][i]['ssmen'] > 0 ? '(+) ' : '';
		var celula1		= document.createElement("td");
		var nodotexto1	= document.createTextNode(prefixo+dados['items'][i]['name']);
		var celula2		= document.createElement("td");
		var id_linha	= dojo_id+i;

		var input = '';

		celula1.className = "tab_texto tab_borda";
		celula2.className = "tab_texto tab_borda";

		celula1.id = dados['items'][i]['id'];

		if (tipo == 'menu')
		{
		    jQuery(celula1).bind("click", {
			"id":celula1.id
		    }, function (evt)

		    {
			    carregarSubniveis(evt.data.id,'submenu',jQuery('#sites').val(),document.getElementById(+evt.data.id));
			});
		    celula1.className += " td_submenu";
		}
		else
		{
		    celula1.className += " td_subsubmenu";
		}

		jQuery(celula1).bind("mouseover", {
		    "id": celula1.id
		}, function (evt)

		{
			jQuery("#"+evt.data.id).css("cursor", "pointer");
		    });

		celula1.appendChild(nodotexto1);

		if (tipo == 'menu')
		{
		    jQuery(celula2).append(span1);
		}

		jQuery(celula2).append(span2);
		jQuery(celula2).append(span3);
		jQuery(celula2).append(span4);
		jQuery(celula2).append(span5);
		jQuery(celula2).append(span6);
		jQuery(celula2).append(span7);
                jQuery(celula2).append(span8);
		celula2.setAttribute('align', 'center');

		tabela.insertRow(index+1);
		tabela.rows[index+1].appendChild(celula1);
		tabela.rows[index+1].appendChild(celula2);
		tabela.rows[index+1].id = id_linha;

		var classe = tabela.rows[index+1].className = tipo == 'menu' ? 'tab_submenu' : 'tab_linha2';

		if (dados['items'][i]['ativo'] == false)
		{
		    tabela.rows[index+1].className += ' tab_inativo'
		}

		jQuery(tabela.rows[index+1]).bind("mouseover", {
		    "id": id_linha
		}, function (evt) {
		    var $class = jQuery("#"+evt.data.id).attr("class").replace(classe, 'tab_linha_over');
		    jQuery("#"+evt.data.id).attr("class", $class);
		    jQuery("#"+evt.data.id).css("cursor", "pointer");
		});

		jQuery(tabela.rows[index+1]).bind("mouseout", {
		    "id": id_linha
		}, function (evt) {
		    var $class = jQuery("#"+evt.data.id).attr("class").replace('tab_linha_over', classe);
		    jQuery("#"+evt.data.id).attr("class", $class);
		    jQuery("#"+evt.data.id).css("cursor", "pointer");
		});

		index++;
	    }
	}
	);
    }
}

function tamanhoBanner (id)
{
    var kw = {
	url:	_HTTP_PATH_+"admin/banners/tamanhobanner/id/"+id,
	load:	function(data)
	{
	    dados = dojo.fromJson(data);
	    dojo.byId('tamanho').innerHTML = 'Tamanho da imagem deve ser de: '+dados;
	},
	error:	function(data)
	{
	    console.debug("An error occurred: ", data);
	},
	timeout: 2000
    };

    dojo.xhrGet(kw);
}

function marcaCheckbox(id)
{
    obj = document.getElementById(id);
    obj.checked = obj.checked == true ? false : true;

    marcaNiveisAbaixo(id);
}

function marcaNiveisAbaixo(id)
{
    var tipo = id.split('enu');
    var cont = 1;

    if (tipo.length == 2)
    {
	while (document.getElementById(id+'_submenu'+cont) != null)
	{
	    var cont2 = 1;

	    document.getElementById(id+'_submenu'+cont).checked = document.getElementById(id).checked;
	    while (document.getElementById(id+'_submenu'+cont+'_subsubmenu'+cont2) != null)
	    {
		document.getElementById(id+'_submenu'+cont+'_subsubmenu'+cont2).checked = document.getElementById(id).checked;
		cont2++;
	    }
	    cont++;
	}
    }
    else if (tipo.length == 3)
    {
	while (document.getElementById(id+'_subsubmenu'+cont) != null)
	{
	    document.getElementById(id+'_subsubmenu'+cont).checked = document.getElementById(id).checked;
	    cont++;
	}

	if (document.getElementById(id).checked == true)
	{
	    var id_menu = id.split('_');
	    document.getElementById(id_menu[0]).checked = true;
	}
    }
    else if (tipo.length == 4)
    {
	if (document.getElementById(id).checked == true)
	{
	    var id_menu = id.split('_');
	    document.getElementById(id_menu[0]).checked = true;
	    document.getElementById(id_menu[0]+'_'+id_menu[1]).checked = true;
	}
    }
}

function BuscaModelos (valor)
{
    document.getElementById('img_modelo').src = _HTTP_PATH_+'imagens/modelos/'+valor+'.jpg';
}

function addBloco (id, idConte, tipo)
{
    var site;

    if (tipo == 'noticias')
    {
	if (dojo.byId('sites_id-1').checked)
	{
	    site  = dojo.byId('sites_id-1').value;
	}
	if (dojo.byId('sites_id-2').checked)
	{
	    site += '-'+dojo.byId('sites_id-2').value;
	}
	if (dojo.byId('sites_id-3').checked)
	{
	    site += '-'+dojo.byId('sites_id-3').value;
	}
    }
    else
    {
	var site	= dijit.byId('sites_id').value;
    }

    var parametro	= '';
    if (idConte)
    {
	parametro = "/idConte/"+idConte;
    }

    if (id > 0)
    {
	var kw = {
	    url: _HTTP_PATH_+"admin/conteudos/adicionarbloco/id/"+id+"/site/"+site+parametro,
	    load: function (data)
	    {
		if (data)
		{
		    var tmp			= data.split("fieldset id='bc");
		    tmp				= tmp[1].split("'");
		    var id_span		= tmp[0];
		    var span		= document.createElement('li');
		    span.innerHTML	= data;
                    //id_span = (id_span+1);
		    span.id			= 'recordsArray_'+id_span;

		    document.getElementById('ui-sortable').appendChild(span);
								
		    if (id == 19)
		    {
			carregaEditor(id_span, id);
		    }
								
		/*if (idConte)
								{
									document.getElementById('filtro_blocos_modal').innerHTML = '';
									document.getElementById('filtro_blocos_modal').appendChild(span);
									Modal.show('div_modal',{color:'#6c6d6e',opacity:0.5});
								}
								else
								{
									document.getElementById('filtro_blocos').appendChild(span);
								}*/
		}
	    },
	    error: function(data)
	    {
		console.debug("An error occurred: ", data);
	    },
	    timeout: 2000
	};

	dojo.xhrGet(kw);
        
    }
jQuery(".uu").sortable({ 
opacity: 0.6, 
cursor: 'move',
revert: true,
forcePlaceholderSize: true,
scrollSensitivity: 40, 
start: function(e, ui) {
    jQuery(this).sortable( "refresh" );
    jQuery(".uu li input").each(function (i) {
        //alert(this.id);
        var str = this.id;
        str = str.substr(0,(str.length-1));
        //populahidden_listagem(str,str+"1"); 
        //alert('chamou.');
    }); 	 
},
stop: function(e,ui) {
    jQuery(this).sortable( "refresh" );
    jQuery(".uu li input").each(function (i) {
        //alert(this.id);
        var str = this.id;
        str = str.substr(0,(str.length-1));
        //populahidden_listagem(str,document.getElementById(str+"1")); 
        //alert('chamou.');
    });            

}		
});

jQuery(".uufaq").sortable({ 
opacity: 0.6, 
cursor: 'move',
revert: true,
forcePlaceholderSize: true,
scrollSensitivity: 40, 
start: function(e, ui) {
    $(this).sortable( "refresh" );
    jQuery(".uufaq li input").each(function (i) {
        var str = this.id;
        str = str.substr(0,(str.length-1));
        populahiddenfaq(str,str+"1"); 
    }); 	 
},
stop: function(e,ui) {
    $(this).sortable( "refresh" );
    jQuery(".uufaq li input").each(function (i) {
        var str = this.id;
        str = str.substr(0,(str.length-1));
        populahiddenfaq(str,document.getElementById(str+"1")); 
    });            

}
});
}

function delBloco (id, cbloc_id)
{
    /*if (cbloc_id)
	{
		if (id > 0)
		{
			var kw = {
					url: _HTTP_PATH_+"admin/conteudos/removerbloco/id/"+cbloc_id,
					load: function (data)
							{
								if (data)
								{
									document.getElementById("span"+id).parentNode.removeChild(document.getElementById("span"+id));
								}
							},
					error: function(data)
					  		{
					   			console.debug("An error occurred: ", data);
							},
					timeout: 2000
			};

			dojo.xhrGet(kw);
		}
	}
	else
	{
		document.getElementById("span"+id).parentNode.removeChild(document.getElementById("span"+id));
	}*/

    document.getElementById("recordsArray_"+id).parentNode.removeChild(document.getElementById("recordsArray_"+id));
}

function populahidden(campos, hidden){ 
    
    hidden.value = "";
    for(i=2; i<150; i++){
        campo = document.getElementById(campos+i);
        if(campo!=null){
            hidden.value+= campo.value+"§";
        }
    }
jQuery(".uu").sortable({ 
opacity: 0.6, 
cursor: 'move',
revert: true,
forcePlaceholderSize: true,
scrollSensitivity: 40, 
start: function(e, ui) {
    jQuery(this).sortable( "refresh" );
    jQuery(".uu li input").each(function (i) {
        //alert(this.id);
        var str = this.id;
        str = str.substr(0,(str.length-1));
        populahidden_listagem(str,str+"1"); 
        //alert('chamou.');
    }); 	 
},
stop: function(e,ui) {
    jQuery(this).sortable( "refresh" );
    jQuery(".uu li input").each(function (i) {
        //alert(this.id);
        var str = this.id;
        str = str.substr(0,(str.length-1));
        populahidden_listagem(str,document.getElementById(str+"1")); 
        //alert('chamou.');
    });            

}		
});
}

function populahidden_listagem(campos, hidden){
        xtmp = campos.split("texto");
        campos = xtmp[0]+"texto";
        //alert("campos="+campos);
        hidden = document.getElementById(campos+"1");
        
    hidden.value = "";
        jQuery("."+campos).each(function (i) {
            if(this.value!=null){
                //alert("+add "+this.value);
                hidden.value+= this.value+"§";
            }
        });
}

function populahiddenfaq(campos, hidden){
        xtmp = campos.split("texto");
        campos = xtmp[0]+"texto";



hidden1=document.getElementById(campos+1);
hidden2=document.getElementById(campos+2);
hidden1.value = "";
hidden2.value = "";
//alert('limpahidden');
var contador = 3;
//alert(campos);
jQuery("."+campos).each(function (i) {
    //alert(contador+" - "+this.value);
    if(contador%2==1){
        hidden1.value+= this.value+"§";
    }else{
        hidden2.value+= this.value+"§";
    }
    contador++;
});

jQuery(".uufaq").sortable({ 
opacity: 0.6, 
cursor: 'move',
revert: true,
forcePlaceholderSize: true,
scrollSensitivity: 40, 
start: function(e, ui) {
    $(this).sortable( "refresh" );
    jQuery(".uufaq li input").each(function (i) {
        var str = this.id;
        str = str.substr(0,(str.length-1));
        populahiddenfaq(str,str+"1"); 
    }); 	 
},
stop: function(e,ui) {
    $(this).sortable( "refresh" );
    jQuery(".uufaq li input").each(function (i) {
        var str = this.id;
        str = str.substr(0,(str.length-1));
        populahiddenfaq(str,document.getElementById(str+"1")); 
    });            

}
});

}

function carregaSelectbox (tipo, valor, idpai)
{
    var idfilho = tipo == 'noticias' ? 'ncate' : 'gcate';

    var kw = {
	url: _HTTP_PATH_+"admin/"+tipo+"categorias/categoriasite/id/"+valor,
	load: function (data)
	{
	    dados = dojo.fromJson(data);
	    if (dados)
	    {
		if (document.getElementById(idfilho+"_id"))
		{
		    document.getElementById(idpai).removeChild(document.getElementById(idfilho+"_id"));
		}

		var select				= document.createElement('select');
		select.id				= idfilho+"_id";
		select.style.marginTop	= "10px";
		select.style.width		= "400px";

		for (var i in dados)
		{
		    var tam = select.options.length;
		    select.options[tam] = new Option(dados[i][idfilho+'_nome'],dados[i][idfilho+'_id']);
		}

		document.getElementById(idpai).appendChild(select);
	    }
	},
	error: function(data)
	{
	    console.debug("An error occurred: ", data);
	},
	timeout: 2000
    };

    dojo.xhrGet(kw);
}

function getContentFromIframe(iFrameName)
{
    var myIFrame = document.getElementById(iFrameName);
    return myIFrame.contentWindow.document.body.innerHTML;
}
function trocaBlocos (id, acao, idConte)
{
    /**
     *	@var id: id do span/bloco
     *	@var acao: sobe/desce
     *	@var idConte: ???
     */
    var blocos	= document.getElementById(id).parentNode;

    for (var i in blocos.childNodes) {
	if (blocos.childNodes[i].id == id) {
	    pos = i;
	    break;
	}
    }

    pos = parseInt(pos);

    if (acao == 'sobe' && pos > 0)
    {
	pos1 = pos;
	pos2 = pos-1;
	tmp1 = blocos.childNodes[pos].cloneNode(true);
	tmp2 = blocos.childNodes[pos-1].cloneNode(true);

	iFrameID1 = jQuery(blocos.childNodes[pos1]).find('iframe') ? jQuery(blocos.childNodes[pos1]).find('iframe').attr('id') : null;
	iFrameID2 = jQuery(blocos.childNodes[pos2]).find('iframe') ? jQuery(blocos.childNodes[pos2]).find('iframe').attr('id') : null;
	iFrameConteudo1 = iFrameID1 ? getContentFromIframe(iFrameID1) : null;
	iFrameConteudo2 = iFrameID2 ? getContentFromIframe(iFrameID2) : null;

	blocos.replaceChild(tmp1, blocos.childNodes[pos-1]);
	blocos.replaceChild(tmp2, blocos.childNodes[pos]);
    }
    else if (acao == 'desce' && pos+1 < blocos.childNodes.length)
    {
	pos1 = pos;
	pos2 = pos+1;
	tmp1 = blocos.childNodes[pos].cloneNode(true);
	tmp2 = blocos.childNodes[pos+1].cloneNode(true);

	iFrameID1 = jQuery(blocos.childNodes[pos1]).find('iframe') ? jQuery(blocos.childNodes[pos1]).find('iframe').attr('id') : null;
	iFrameID2 = jQuery(blocos.childNodes[pos2]).find('iframe') ? jQuery(blocos.childNodes[pos2]).find('iframe').attr('id') : null;
	iFrameConteudo1 = iFrameID1 ? getContentFromIframe(iFrameID1) : null;
	iFrameConteudo2 = iFrameID2 ? getContentFromIframe(iFrameID2) : null;

	blocos.replaceChild(tmp1, blocos.childNodes[pos+1]);
	blocos.replaceChild(tmp2, blocos.childNodes[pos]);
    }

	var controle1 = blocos.childNodes[pos1].id.replace('span','');
	var controle2 = blocos.childNodes[pos2].id.replace('span','');

	if(iFrameConteudo1) {
	    txtAreaID1 = iFrameID1.replace('_ifr', '');
	    jQuery('#'+iFrameID1.replace('_ifr', '_parent')).remove();
            jQuery("#"+txtAreaID1)
	    .attr('style','width: 420px;')
//	    .html(iFrameConteudo1);
	    carregaEditor(controle2, 19);
	}
	if(iFrameConteudo2) {
	    txtAreaID2 = iFrameID2.replace('_ifr', '');
	    jQuery('#'+iFrameID2.replace('_ifr', '_parent')).remove();
            jQuery("#"+txtAreaID2)
	    .attr('style','width: 420px;')
//	    .html(iFrameConteudo2);

	    carregaEditor(controle1, 19);
	}

//	blocos.childNodes[pos1].id = 'span'+controle2;
//	blocos.childNodes[pos2].id = 'span'+controle1;

/*
    if (idConte != '') {
	var kw = {
	    url: _HTTP_PATH_+"admin/conteudos/alterarordem/id/"+idConte+"/acao/"+acao,
	    load: function (data)
	    {
		return true;
	    },
	    error: function(data)
	    {
		console.debug("An error occurred: ", data);
	    },
	    timeout: 2000
	};

	dojo.xhrGet(kw);
    }
*/
}

function moveBlocos (input, id, acao)
{
    if(acao=="sobe"){
        for(i = (id-1); i<150; i--){
            //alert('for');
            id2 = (i);
            x = document.getElementById(input+id2);
            if(x!=null){
                //alert(id2);
                break;
            }else{
                //alert('input+id2 is null!');
            }
            //alert(id2);
        }
        var vinput2 = document.getElementById(input+id2);
    }
    if(acao=="desce"){
        //id2 = (parseFloat(id)+1);
        for(i = (id+1); i<150; i++){
            //alert('for');
            id2 = (i);
            x = document.getElementById(input+id2);
            if(x!=null){
                //alert(id2);
                break;
            }else{
                //alert('input+id2 is null!');
            }
            //alert(id2);
        }
        var vinput2 = document.getElementById(input+id2);
    }
    if((vinput2)&&(id2!=1)){
        var input2 = document.getElementById(input+id).value ;
        var input1 = document.getElementById(input+id2).value ;
        document.getElementById(input+id).value = input1;
        document.getElementById(input+id2).value = input2;
    }
}

function movefaq (input, id, acao)
{
    if(acao=="sobe"){
        //id2 = (parseFloat(id)-2);
        for(i = (id-1); i<150; i--){
            //alert('for');
            id2 = (i-1);
            x = document.getElementById(input+id2);
            if(x!=null){
                //alert(id2);
                break;
            }else{
                //alert('input+id2 is null!');
            }
            //alert(id2);
        }
        id3 = (parseFloat(id)-1);
        id4 = (parseFloat(id2)-1);
        
//        id2 = (parseFloat(id)-2);
//        id3 = (parseFloat(id)-1);
//        id4 = (parseFloat(id)-3);
        
        var vinput2 = document.getElementById(input+id2);
        var vinput4 = document.getElementById(input+id4);
    }
    if(acao=="desce"){
        i=0;
        for(i = (id+1); i<150; i++){
            //alert('for');
            id2 = (i+1);
            x = document.getElementById(input+id2);
            if(id2%2==0){
                if(x!=null){
                    //alert(id2);
                    break;
                }else{
                    //alert('input+id2 is null!');
                }
            }
            //alert(id2);
        }
        //id2 = (parseFloat(id)+2);
        id3 = (parseFloat(id)-1);
        id4 = (parseFloat(id2)-1);
        //alert(id2);
        //alert(id4);
//        id2 = (parseFloat(id)+2);
//        id3 = (parseFloat(id)-1);
//        id4 = (parseFloat(id)+1);
        
        
        
        var vinput2 = document.getElementById(input+id2);
        var vinput4 = document.getElementById(input+id4);
    }
    if((vinput2)&&(id2!=1)&&(id2!=2)){
        var input2 = document.getElementById(input+id).value ;
        var input1 = document.getElementById(input+id2).value ;
        
        var input4 = document.getElementById(input+(parseFloat(id)-1)).value ;
        var input3 = document.getElementById(input+id4).value ;
        
        document.getElementById(input+id).value = input1;
        document.getElementById(input+id2).value = input2;
        document.getElementById(input+id3).value = input3;
        document.getElementById(input+id4).value = input4;
    }
}

function buscaMenus (smenu_id, menus_id, sites_id)
{
    var caminho	= '';
    var tipo_id	= '';

    if (sites_id)
    {
	caminho += 'sites_id/'+sites_id+'/';
	tipo_id  = 'menus_id';
    }

    if (menus_id)
    {
	caminho += 'menus_id/'+menus_id+'/';
	tipo_id  = 'smenu_id';
    }

    if (smenu_id)
    {
	caminho += 'smenu_id/'+smenu_id+'/';
	tipo_id  = 'ssmen_id';
    }

    if (caminho)
    {
	var url = _HTTP_PATH_+"admin/menus/retornamenus/"+caminho;

	dijit.byId(tipo_id).textbox.value = '';
	menusStore = new dojo.data.ItemFileReadStore({
	    "url":url
	});
	menusStore.fetch({
	    onComplete: function(items, request){
		dijit.byId(tipo_id).store = menusStore;
		dijit.byId(tipo_id).textbox.value = items[0].name;
	    }
	});
    }
}

function carregaMenus(valor, tipo, mensagem, contador)
{
    var caminho	= '';
    var tipo_id	= '';
    var msg		= mensagem ? '/mensagem/true' : '';
    contador	= contador != undefined ?
    '_'+contador :
    '';

    if (tipo == 'sites')
    {
	caminho += 'sites_id/'+valor+msg;
	tipo_id  = 'menus_id_arq'+contador;
    }

    if (tipo == 'menus')
    {
	caminho += 'menus_id/'+valor+'/sites_id/'+jQuery('#sites_id_arq'+contador).val()+msg;
	tipo_id  = 'smenu_id_arq'+contador;
    }

    if (tipo == 'smenu')
    {
	caminho += 'smenu_id/'+valor+'/sites_id/'+jQuery('#sites_id_arq'+contador).val()+msg;
	tipo_id  = 'ssmen_id_arq'+contador;
    }

    var url = _HTTP_PATH_+"admin/menus/retornamenus/"+caminho;

    jQuery.getJSON(
	url,
	function(data)
	{
	    var select = document.getElementById(tipo_id);
	    if (select) {
		jQuery(select).empty();
		jQuery.each(data['items'], function(i, val) {
		    jQuery(select).append('<option value="' + data['items'][i]['id'] + '">' + data['items'][i]['name'] + '</option>')
		});
				
		document.getElementById(tipo_id).focus();
	    }
	}
	);
}

function carregaArquivos (id, contador, bloco)
{
    var kw = {
	url: _HTTP_PATH_+"admin/blocosarquivos/carregaarquivos/id/"+id,
	load: function (data)
	{
	    if (data)
	    {
		dados = dojo.fromJson(data);
		if (dados != '')
		{
		    var divPai = document.getElementById('arquivos_carregados');
		    for (var i in dados)
		    {
			var checkbox		= document.createElement('input');
			checkbox.type		= 'checkbox';
			checkbox.id			= 'bloco_conteudo_'+contador+'_'+bloco+'_'+(parseInt(i)+1);
			checkbox.name		= 'bloco_conteudo['+contador+']['+bloco+'][arquivos][]';
			checkbox.value		= dados[i]['barqu_id'];

			var label			= document.createElement('label');
			label.htmlFor		= 'bloco_conteudo_'+contador+'_'+bloco+'_'+(parseInt(i)+1);
			label.appendChild(checkbox);
			label.innerHTML		+= dados[i]['barqu_filename'];

			var br				= document.createElement('br');

			divPai.appendChild(label);
			divPai.appendChild(br);
		    }
		}
		else
		{
		    alert('Nenhum arquivo cadastrado no sistema!');
		}
	    }
	},
	error: function(data)
	{
	    console.debug("An error occurred: ", data);
	},
	timeout: 2000
    };

    dojo.xhrGet(kw);
}

function salvarConteudo (id, bloco, texto, tipo, elements)
{
    var valor = '';
    var compl = '';

    if (tipo == 'texto')
    {
	valor = document.getElementById('blocos_conteudo_'+id+'_'+bloco+'_texto'+texto).value;
    }
    else if (tipo == 'texto_editor')
    {
	var ed = tinyMCE.get(elements);
	valor = ed.getContent();
	tipo = "texto";
    }
    else if (tipo == 'noticia')
    {
	valor = document.getElementById('blocos_conteudo_'+id+'_'+bloco+'_noticia').value;
	compl = '_notic';
    }
    else if (tipo == 'noticia_categoria')
    {
	valor = document.getElementById('blocos_conteudo_'+id+'_'+bloco+'_categoria').value;
	compl = '_ncate';
    }
    else if (tipo == 'galeria')
    {
	valor = document.getElementById('blocos_conteudo_'+id+'_'+bloco+'_galeria').value;
	compl = '_galer';
    }
    else if (tipo == 'galeria_categoria')
    {
	valor = document.getElementById('blocos_conteudo_'+id+'_'+bloco+'_categoria').value;
	compl = '_gcate';
    }

    jQuery.post(_HTTP_PATH_+"admin/conteudos/salvarconteudo/", {
	'id':id,
	'valor':valor,
	'tipo':tipo
    },
    function(data)
    {
	if (data == 1)
	{
	    document.getElementById('div'+id+compl).style.display = 'none';
	}
	else
	{
	    alert(data);
	}
    }
    );
}

function removeArquivo (id, obj)
{
    obj.parentNode.parentNode.removeChild(obj.parentNode);
}

function carregaSelect(id, cont, bloco, tipo) 
{
    //    jQuery.each
	
    var select	= document.getElementById('blocos_conteudo_'+cont+'_'+bloco+'_'+tipo);
    for (var j in select.options)
    {
	select.remove(j);
    }

    var opt		= document.createElement('option');
    opt.text	= ' - Todas - ';
    opt.value	= '0';

    try
    {
	select.add(opt, null);
    }
    catch(ex)
    {
	select.add(opt);
    }

    if (id > 0)
    {
	var kw = {
	    url: _HTTP_PATH_+"admin/"+tipo+"s/carregar"+tipo+"s/id/"+id,
	    load: function (data)
	    {
		var prefixo	= tipo.slice(0,5);
		var dados	= dojo.fromJson(data);

		if (dados != '')
		{
		    for (var i in dados)
		    {
			if (dados[i][prefixo+'_titulo'])
			{
			    var opt		= document.createElement('option');
			    opt.text	= dados[i][prefixo+'_titulo'];
			    opt.value	= dados[i][prefixo+'_id'];

			    try
			    {
				select.add(opt, null);
			    }
			    catch(ex)
			    {
				select.add(opt);
			    }
			}
		    }
		}
	    },
	    error: function(data)
	    {
		console.debug("An error occurred: ", data);
	    },
	    timeout: 2000
	};

	dojo.xhrGet(kw);
    }
}

function definirPadrao (id)
{
    var kw = {
	url: _HTTP_PATH_+"admin/conteudos/definirpadrao/id/"+id,
	load: function (data)
	{
	    dados = dojo.fromJson(data);
	    if (dados)
	    {
		window.location.reload();
	    }
	    else
	    {
		alert('Erro ao definir conteúdo como padrão, tente novamente!');
	    }
	},
	error: function(data)
	{
	    console.debug("An error occurred: ", data);
	},
	timeout: 2000
    };

    dojo.xhrGet(kw);
}

function carregarBlocosPadrao ()
{
    var menu		= dijit.byId('menus_id').value;
    var submenu		= dijit.byId('smenu_id').value;
    var subsubmenu	= dijit.byId('ssmen_id').value;

    if (menu > 0)
    {
	var kw = {
	    url: _HTTP_PATH_+"admin/conteudos/carregarblocospadrao/menus/"+menu+"/smenu/"+submenu+"/ssmen/"+subsubmenu,
	    load: function (data)
	    {
		dados = dojo.fromJson(data);
		if (dados)
		{
		    document.getElementById('filtro_blocos').innerHTML = dados;
		}
	    },
	    error: function(data){
		console.debug("An error occurred: ", data);
	    },
	    timeout: 2000
	};

	dojo.xhrGet(kw);
    }
    else
    {
	alert('Deve ser selecionado ao menos o Menu');
    }
}

function mostraBlocos (id, idConte, tipo)
{
    jQuery.post(
	_HTTP_PATH_+"admin/conteudos/carregarblocos/",
	{
	    'id':id,
	    'idConte':idConte
	},
	function(data)
	{
	    var dados		= dojo.fromJson(data);
	    var blocos		= document.getElementById('blocos2');
	    var parametro	= idConte ? ', '+idConte : ', null';

	    if (dados)
	    {
		blocos.innerHTML = '';
		for (var i in dados)
		{
		    if (dados[i]['id'])
		    {
			if (tipo != undefined)
			{
			    blocos.innerHTML += '<a href="javascript:void(0);" onclick="addBloco('+dados[i]['id']+parametro+',\''+tipo+'\')"><img src="'+_HTTP_PATH_+'imagens/blocos/exemplos/'+dados[i]['id']+'.jpg" border="0" alt="'+dados[i]['nome']+'" title="'+dados[i]['nome']+'" class="blocos2" /></a>';
			}
			else
			{
			    blocos.innerHTML += '<a href="javascript:void(0);" onclick="addBloco('+dados[i]['id']+parametro+')"><img src="'+_HTTP_PATH_+'imagens/blocos/exemplos/'+dados[i]['id']+'.jpg" border="0" alt="'+dados[i]['nome']+'" title="'+dados[i]['nome']+'" class="blocos2" /></a>';
			}
		    }
		}
	    }
	}
	);
}

function excluiConteudo (id)
{
    if (confirm('Tem certeza que deseja excluir esse conteúdo?\nEssa açãoo também excluirá todos os backups desse conteúdo'))
    {
	window.location.href = _HTTP_PATH_+'admin/conteudos/excluir/conte_id/'+id;
    }
}

function carregaConteudo (contador)
{
    var sites	= jQuery('#sites_id_arq_'+contador);
    var menus	= jQuery('#menus_id_arq_'+contador);
    var smenu	= jQuery('#smenu_id_arq_'+contador);
    var ssmen	= jQuery('#ssmen_id_arq_'+contador);
    var caminho	= _HTTP_PATH_+'admin/conteudos/carregaconteudos/';
	
    if (sites.val() > 0)
    {
	if (menus.val() > 0 && smenu.val() > 0 && ssmen.val() > 0)
	{
	    caminho +=   'sites_id/' + sites.val() +
	    '/menus_id/' + menus.val() +
	    '/smenu_id/' + smenu.val() +
	    '/ssmen_id/' + ssmen.val();
	}
	else if (menus.val() > 0 && smenu.val() > 0)
	{
	    caminho +=   'sites_id/' + sites.val() +
	    '/menus_id/' + menus.val() +
	    '/smenu_id/' + smenu.val();
	}
	else if (menus.val() > 0)
	{
	    caminho +=   'sites_id/' + sites.val() +
	    '/menus_id/' + menus.val();
	}
	else if (menus.val() == 0 && smenu.val() == 0 && ssmen.val() == 0)
	{
	    caminho +=   'sites_id/' + sites.val();
	}
		
	jQuery.getJSON (caminho, function (data){
	    var select = jQuery('#conte_id_arq_'+contador);
			
	    jQuery(select).empty();
	    jQuery.each(data, function(i, val){
		jQuery(select).append('<option value="'+val['id']+'">'+val['nome']+'</option>');
	    });
	});
    }
}

function insereLink (id, contador, contador_view)
{
    if (jQuery('#conte_id_arq_'+id).val() > 0)
    {
	var site = jQuery('#sites_id_arq_'+id).val();
	var cont = jQuery('#conte_id_arq_'+id).val();
	var url  = _HTTP_PATH_+'admin/conteudos/retornalink/conte_id/'+cont+'/sites_id/'+site;
jQuery.get(url, function(data){
    
jQuery("."+'blocos_conteudo_'+id+'_'+contador+'_texto').each(function (i) {
if(this.value==""){
    var str = this.id;
    document.getElementById(str.replace("blocos_conteudo", "div")).parentNode.removeChild(document.getElementById(str.replace("blocos_conteudo", "div"))); 
}
});
            add_link_listagem(id, contador, contador_view, data);
	});
    }
}

var cont_file = 2;
function add_files (contador, id, cfile)
{
    if (cfile >= cont_file)
    {
	cont_file = cfile;
    }
if(cont_file>19){
    alert("Limite de arquivos atingido.");
}else{
    var conteudo = "<div>";
    conteudo += "	<div class='label_conteudo'>Arquivo "+cont_file+"</div>";
    conteudo += "	<input type='file' style='width:300px;' name='blocos_conteudo_"+contador+"_"+id+"_arquivo"+cont_file+"' />";
    conteudo += "	</div>";

    jQuery('#arquivos_carregados'+contador).append(conteudo);
    cont_file++;
}
}

function remove_field(field){
    document.getElementById(field).parentNode.removeChild(document.getElementById(field)); 
}

function remove_link(field){
    document.getElementById(field).parentNode.removeChild(document.getElementById(field)); 
}

function remove_faq(field){
    document.getElementById(field).parentNode.removeChild(document.getElementById(field)); 
}

function add_field (contador, id, cfile)
{
   
    if (cfile >= cont_file)
    {
	cont_file = parseFloat(cfile)+1;
    }
    var data = "";
    data += "<a style=\"margin-left:7px\" class=\"link2 bot_link_exclui\" href='javascript:void(0);' onclick='remove_field(\"div_"+contador+"_"+id+"_texto"+cont_file+"\"); \n\
populahidden(\n\
\"blocos_conteudo_"+contador+"_"+id+"_texto\",\n\
document.getElementById(\"blocos_conteudo_"+contador+"_"+id+"_texto1\")\n\
); \n\
'>&nbsp;</a>	\n\
<input class='naopostar' type='text' value='' \n\
onchange='\n\
populahidden(\n\
\"blocos_conteudo_"+contador+"_"+id+"_texto\",\n\
document.getElementById(\"blocos_conteudo_"+contador+"_"+id+"_texto1\")\n\
)' \n\
style='width:420px;' id='blocos_conteudo_"+contador+"_"+id+"_texto"+cont_file+"' name='blocos_conteudo["+contador+"]["+id+"][texto"+cont_file+"]' />";
    data += "<a class='link2 bot_link_sobe' onclick='moveBlocos(\"blocos_conteudo_"+contador+"_"+id+"_texto\","+cont_file+",\"sobe\");\n\
populahidden(\n\
\"blocos_conteudo_"+contador+"_"+id+"_texto\",\n\
document.getElementById(\"blocos_conteudo_"+contador+"_"+id+"_texto1\")\n\
);' \n\
href='javascript:void(0)' style='margin-left: 10px;'>&nbsp;</a><a style='margin-left: 4px;' class='link2 bot_link_desce' \n\
onclick='moveBlocos(\"blocos_conteudo_"+contador+"_"+id+"_texto\","+cont_file+",\"desce\"); \n\
populahidden(\n\
\"blocos_conteudo_"+contador+"_"+id+"_texto\",\n\
document.getElementById(\"blocos_conteudo_"+contador+"_"+id+"_texto1\")\n\
);' \n\
href='javascript:void(0)'>&nbsp;</a>";
    
    var field                   = document.createElement('div');
    field.id                    = "div_"+contador+"_"+id+"_texto"+cont_file;
    field.style.marginBottom  = "2px";
    field.innerHTML             = data;

    document.getElementById("bc"+contador).appendChild(field);
    //jQuery('#recordsArray_'+contador).append(conteudo);
    cont_file++;

}

function add_field_listagem (contador, id, cfile)
{
   
    if (cfile >= cont_file)
    {
	cont_file = parseFloat(cfile)+1;
    }
    var data = "";
    data += "<a style=\"margin-left:7px\" class=\"link2 bot_link_exclui\" href='javascript:void(0);' onclick='remove_field(\"div_"+contador+"_"+id+"_texto"+cont_file+"\"); populahidden_listagem(\"blocos_conteudo_"+contador+"_"+id+"_texto\",document.getElementById(\"blocos_conteudo_"+contador+"_"+id+"_texto1\"));'>&nbsp;</a>	\n\
<input class=\"blocos_conteudo_"+contador+"_"+id+"_texto\" type='text' value='' \n\
onchange='populahidden_listagem(\"blocos_conteudo_"+contador+"_"+id+"_texto\",document.getElementById(\"blocos_conteudo_"+contador+"_"+id+"_texto1\"))' \n\
style='width:420px;' id='blocos_conteudo_"+contador+"_"+id+"_texto"+cont_file+"' name='blocos_conteudo["+contador+"]["+id+"][texto"+cont_file+"]' />";
    data += '<img border="0" style="margin-left:5px;" src="imagens/bt_mao.png" style="margin-left:5px;"/>';
    
    var field                   = document.createElement('li');
    field.id                    = "div_"+contador+"_"+id+"_texto"+cont_file;
    field.style.marginBottom  = "2px";
    field.innerHTML             = data;

    document.getElementById("uu"+contador).appendChild(field);
    //jQuery('#recordsArray_'+contador).append(conteudo);
    cont_file++;

jQuery(".uu").sortable({ 
opacity: 0.6, 
cursor: 'move',
revert: true,
forcePlaceholderSize: true,
scrollSensitivity: 40, 
start: function(e, ui) {
    jQuery(this).sortable( "refresh" );
    jQuery(".uu li input").each(function (i) {
        //alert(this.id);
        var str = this.id;
        str = str.substr(0,(str.length-1));
        populahidden_listagem(str,str+"1"); 
        //alert('chamou.');
    }); 	 
},
stop: function(e,ui) {
    jQuery(this).sortable( "refresh" );
    jQuery(".uu li input").each(function (i) {
        //alert(this.id);
        var str = this.id;
        str = str.substr(0,(str.length-1));
        populahidden_listagem(str,document.getElementById(str+"1")); 
        //alert('chamou.');
    });            

}		
});

}



function add_link    (contador, id, cfile, rdata)
{
    if (cfile >= cont_file)
    {
	cont_file = parseFloat(cfile)+1;
    }
    var data = "";
    data += "<div style='margin-top:5px;'><a style=\"margin-left:7px\" class=\"link2 bot_link_exclui\" href='javascript:void(0);' onclick='remove_field(\"div_"+contador+"_"+id+"_texto"+cont_file+"\"); \n\
populahidden(\n\
\"blocos_conteudo_"+contador+"_"+id+"_texto\",\n\
document.getElementById(\"blocos_conteudo_"+contador+"_"+id+"_texto1\")\n\
); \n\
'>&nbsp;</a>	\n\
Link: <input class='naopostar' type='text' value='"+rdata+"' \n\
onchange='\n\
validalink(this);  \n\
populahidden(\n\
\"blocos_conteudo_"+contador+"_"+id+"_texto\",\n\
document.getElementById(\"blocos_conteudo_"+contador+"_"+id+"_texto1\")\n\
)' \n\
style='width:420px;' id='blocos_conteudo_"+contador+"_"+id+"_texto"+cont_file+"' name='blocos_conteudo["+contador+"]["+id+"][texto"+cont_file+"]' />";
    
    data += "<a class='link2 bot_link_sobe' onclick='moveBlocos(\"blocos_conteudo_"+contador+"_"+id+"_texto\","+cont_file+",\"sobe\");\n\
populahidden(\n\
\"blocos_conteudo_"+contador+"_"+id+"_texto\",\n\
document.getElementById(\"blocos_conteudo_"+contador+"_"+id+"_texto1\")\n\
);' \n\
href='javascript:void(0)' style='margin-left: 10px;'>&nbsp;</a><a style='margin-left: 4px;' class='link2 bot_link_desce' \n\
onclick='moveBlocos(\"blocos_conteudo_"+contador+"_"+id+"_texto\","+cont_file+",\"desce\"); \n\
populahidden(\n\
\"blocos_conteudo_"+contador+"_"+id+"_texto\",\n\
document.getElementById(\"blocos_conteudo_"+contador+"_"+id+"_texto1\")\n\
);' \n\
href='javascript:void(0)'>&nbsp;</a></div>";
    
    var field                   = document.createElement('div');
    field.id                    = "div_"+contador+"_"+id+"_texto"+cont_file;
    field.style.marginBottom  = "2px";
    field.innerHTML             = data;

    document.getElementById("bc"+contador).appendChild(field);
    //jQuery('#recordsArray_'+contador).append(conteudo);
    cont_file++;

}

function add_link_listagem    (contador, id, cfile, rdata)
{
    if (cfile >= cont_file)
    {
	cont_file = parseFloat(cfile)+1;
    }
    var data = "";
    data += "<div style='margin-top:5px;'><a style=\"margin-left:7px\" class=\"link2 bot_link_exclui\" href='javascript:void(0);' onclick='remove_field(\"div_"+contador+"_"+id+"_texto"+cont_file+"\"); \n\
populahidden(\n\
\"blocos_conteudo_"+contador+"_"+id+"_texto\",\n\
document.getElementById(\"blocos_conteudo_"+contador+"_"+id+"_texto1\")\n\
); \n\
'>&nbsp;</a>	\n\
Link: <input class=\"blocos_conteudo_"+contador+"_"+id+"_texto\" type='text' value='"+rdata+"' \n\
onchange='\n\
validalink(this);  \n\
populahidden_listagem(\n\
\"blocos_conteudo_"+contador+"_"+id+"_texto\",\n\
document.getElementById(\"blocos_conteudo_"+contador+"_"+id+"_texto1\")\n\
)' \n\
style='width:420px;' id='blocos_conteudo_"+contador+"_"+id+"_texto"+cont_file+"' name='blocos_conteudo["+contador+"]["+id+"][texto"+cont_file+"]' />";
    
    data += '<img border="0" style="margin-left:5px;" src="imagens/bt_mao.png" style="margin-left:5px;"/></div>';
    
    var field                   = document.createElement('li');
    field.id                    = "div_"+contador+"_"+id+"_texto"+cont_file;
    field.style.marginBottom    = "2px";
    field.innerHTML             = data;

    document.getElementById("uu"+contador).appendChild(field);
    //jQuery('#recordsArray_'+contador).append(conteudo);
    cont_file++;
    
jQuery(".uu").sortable({ 
opacity: 0.6, 
cursor: 'move',
revert: true,
forcePlaceholderSize: true,
scrollSensitivity: 40, 
start: function(e, ui) {
    jQuery(this).sortable( "refresh" );
    jQuery(".uu li input").each(function (i) {
        //alert(this.id);
        var str = this.id;
        str = str.substr(0,(str.length-1));
        populahidden_listagem(str,str+"1"); 
        //alert('chamou.');
    }); 	 
},
stop: function(e,ui) {
    jQuery(this).sortable( "refresh" );
    jQuery(".uu li input").each(function (i) {
        //alert(this.id);
        var str = this.id;
        str = str.substr(0,(str.length-1));
        populahidden_listagem(str,document.getElementById(str+"1")); 
        //alert('chamou.');
    });            

}		
});

populahidden_listagem(
    "blocos_conteudo_"+contador+"_"+id+"_texto",
    document.getElementById("blocos_conteudo_"+contador+"_"+id+"_texto1")
); 
}


function add_faq (contador, id, cfile)
{
   
    if (cfile >= cont_file)
    {
	cont_file = parseFloat(cfile);
    }
    var data = "";
    data += "<div id=\"div_"+contador+"_"+id+"_texto"+cont_file+"\"> \n\
<a style=\"margin-left:7px\" class=\"link2 bot_link_exclui\" href='javascript:void(0);' onclick='remove_field(\"div_"+contador+"_"+id+"_texto"+cont_file+"\"); \n\
populahiddenfaq(\n\
\"blocos_conteudo_"+contador+"_"+id+"_texto\",\n\
document.getElementById(\"blocos_conteudo_"+contador+"_"+id+"_texto1\")\n\ "
+ "); " 
+" '>&nbsp;</a>\n\
<div>\n\ "
+ "<div class='label_conteudo'>Pergunta</div>\n\
<input onchange='populahiddenfaq(\n\
\"blocos_conteudo_"+contador+"_"+id+"_texto\",\n\
document.getElementById(\"blocos_conteudo_"+contador+"_"+id+"_texto1\")\n\ "
+ ");'  type='text' name='blocos_conteudo["+contador+"]["+id+"][texto"+cont_file+"]'"
+"id='blocos_conteudo_"+contador+"_"+id+"_texto"+cont_file+"' class='blocos_conteudo_"+contador+"_"+id+"_texto'  style='width:420px;' value='' />"
+"</div>";

cont_file+=1;

data +="<div><div class=\"label_conteudo\">Resposta<br/>" ;

    data += '<img border="0" style="margin-left:7px;" src="imagens/bt_mao.png"/>\n\
\n\
</div> \n\
</div>';
    
data += "<textarea class='blocos_conteudo_"+contador+"_"+id+"_texto' name='blocos_conteudo["+contador+"]["+id+"][texto"+cont_file+"]' id='blocos_conteudo_"+contador+"_"+id+"_texto"+cont_file+"'\n\
 style='width:420px;' rows='5' onchange='populahiddenfaq(\n\
\"blocos_conteudo_"+contador+"_"+id+"_texto\",\n\
document.getElementById(\"blocos_conteudo_"+contador+"_"+id+"_texto1\")\n\ "
+ ");'  ></textarea></div>";
    
    var field                   = document.createElement('li');
    field.id                    = "div_"+contador+"_"+id+"_texto"+cont_file;
    field.style.marginBottom  = "2px";
    field.innerHTML             = data;

    document.getElementById("uu"+contador).appendChild(field);
    //jQuery('#recordsArray_'+contador).append(conteudo);
    cont_file++;
    
jQuery(".uu").sortable({ 
opacity: 0.6, 
cursor: 'move',
revert: true,
forcePlaceholderSize: true,
scrollSensitivity: 40, 
start: function(e, ui) {
    jQuery(this).sortable( "refresh" );
    jQuery(".uu li input").each(function (i) {
        //alert(this.id);
        var str = this.id;
        str = str.substr(0,(str.length-1));
        populahiddenfaq(str,str+"1"); 
        //alert('chamou.');
    }); 	 
},
stop: function(e,ui) {
    jQuery(this).sortable( "refresh" );
    jQuery(".uu li input").each(function (i) {
        //alert(this.id);
        var str = this.id;
        str = str.substr(0,(str.length-1));
        populahiddenfaq(str,document.getElementById(str+"1")); 
        //alert('chamou.');
    });            

}		
});

}

function negarRegistro (tipo, id, obj)
{
    if (confirm('Tem certeza que deseja negar esse conteúdo?'))
    {
	jQuery.post(
	    _HTTP_PATH_+"admin/"+tipo+"/negar/",
	    {
		'id':id
	    },
	    function (data)
	    {
		if (data == true)
		{
		    window.location.reload();
		}
	    }
	    );
    }

    return false;
}

var selecionado = 0;
function marcaBotao (id, acao)
{
    if (acao == 'click')
    {
	for (var i=1; i<8; i++)
	{
	    if (document.getElementById('bt_icone' + i))
	    {
		id == i ?
		document.getElementById('bt_icone' + i).src = _HTTP_PATH_ + 'imagens/blocos/exemplos/icone_' + i + '_over.jpg' :
		document.getElementById('bt_icone' + i).src = _HTTP_PATH_ + 'imagens/blocos/exemplos/icone_' + i + '.jpg';
	    }
	}

	selecionado = id;
    }
    else if (acao == 'over')
    {
	document.getElementById('bt_icone'+id).src = _HTTP_PATH_+'imagens/blocos/exemplos/icone_'+id+'_over.jpg';
    }
    else if (acao == 'out' && selecionado != id)
    {
	document.getElementById('bt_icone'+id).src = _HTTP_PATH_+'imagens/blocos/exemplos/icone_'+id+'.jpg'
    }
}

function carregaEditor (controle, id)
{
    tinyMCE.init({
	mode: "exact",
	elements: "blocos_conteudo_"+controle+"_"+id+"_texto1",
	theme: "advanced",
	language: "pt",
	width: "95%",
	height: "200",

	plugins: "safari, paste, table",

	theme_advanced_buttons1: "pastetext,pasteword,|,undo,redo,|,link,unlink,|,code,cleanup,removeformat",
	theme_advanced_buttons2: "bold,italic,underline,|,tablecontrols",
	theme_advanced_buttons3: "",
	theme_advanced_buttons4: "",
	theme_advanced_toolbar_location: "top",
	theme_advanced_toolbar_align: "left",
	theme_advanced_statusbar_location: "bottom",
	theme_advanced_resizing: true,
	theme_advanced_resize_horizontal: false,
	table_styles: "Header 1=header1;Header 2=header2;Header 3=header3",
	invalid_elements: "@[class]"        
    });
}

function BuscaSitesNoticias ()
{    
    var categorias	= "";
	
    jQuery(".class_categorias").each
    (
	function ()
	{
	    if (this.checked == true)
	    {
		categorias += 'categorias[]='+this.value+'&';
	    }
	}
	);
	
    jQuery.getJSON
    (
	_HTTP_PATH_+"admin/noticiascategorias/associacao/",
	categorias,
	function (data)
	{
	    jQuery(".class_sites").each
	    (
		function ()
		{
		    jQuery(this).css('display', 'none');
		    jQuery(this).parent().css('display', 'none');
		    this.disabled = true;
		    var objeto = this;
					
		    jQuery.each
		    (
			data,
			function(i, val)
			{
			    if (jQuery(objeto).attr('id') == 'sites_id-'+val['sites_id'])
			    {
				jQuery(objeto).css('display', '');
				jQuery(objeto).parent().css('display', '');
				objeto.disabled = false;
			    }
			}
			);
		}
		)
	}
	);
};

function BuscaSitesGalerias ()
{    
    var categorias	= "";
	
    jQuery(".class_categorias").each
    (
	function ()
	{
	    if (this.checked == true)
	    {
		categorias += 'categorias[]='+this.value+'&';
	    }
	}
	);
	
    jQuery.getJSON
    (
	_HTTP_PATH_+"admin/galeriascategorias/associacao/",
	categorias,
	function (data)
	{
	    jQuery(".class_sites").each
	    (
		function ()
		{
		    jQuery(this).css('display', 'none');
		    jQuery(this).parent().css('display', 'none');
		    this.disabled = true;
		    var objeto = this;
					
		    jQuery.each
		    (
			data,
			function(i, val)
			{
			    if (jQuery(objeto).attr('id') == 'sites_id-'+val['sites_id'])
			    {
				jQuery(objeto).css('display', '');
				jQuery(objeto).parent().css('display', '');
				objeto.disabled = false;
			    }
			}
			);
		}
		)
	}
	);
};

init();
