var x,y,px,py,xa,ya,link
var arrastadoLeftInicial,arrastadoTopInicial
var movendo=false;
var idAtual;
var istmp=0;
function parar(e) //para com o drag'n'drop e salva a posição no servidor
{
	if(!e){
	link.style.filter='alpha(opacity=100)';
	}else{
	link.style.opacity=1;
	}
	link.style.zIndex=0;
	if (movendo==true){
		if (document.getElementById('dicaarrastar')){document.getElementById('dicaarrastar').style.display='none';}
		if (document.getElementById('dicasalvar')){document.getElementById('dicasalvar').style.display='';document.getElementById('dicaAdicionar2').style.display='';}
		enquadrar(link,document.getElementById('bordaPontilhada')) //enquadra o link na grade virtual, enviando no primeiro parametro o objeto a ser movido (neste caso, o proprio link), e no segundo a posição atual do link.
		document.getElementById('bordaPontilhada').style.display='none';
		carregar('/_atualizar.asp?acao=reposicionar&id='+link.id+'&xa='+xa+'&ya='+ya+'&x='+link.style.left.replace('px','')+'&y='+link.style.top.replace('px',''),'statusText');
	}
	movendo=false;
}
function mover(e) //movimenta o link (e=link) pela tela
{
	if(movendo==false)
	{
		if(!e)
		{
			px=link.offsetLeft-event.clientX;
			py=link.offsetTop-event.clientY;
			link.style.filter='alpha(opacity=70)';
		}
		else
		{
			px=link.offsetLeft-e.pageX;
			py=link.offsetTop-e.pageY;
			link.style.opacity=7/10;
		}
		link.style.zIndex=10001;
		xa=link.style.left.replace('px','');
		xa=xa.replace('pt','');
		ya=link.style.top.replace('px','');
		ya=ya.replace('pt','');
		arrastadoLeftInicial=link.style.left.replace('px','');
		arrastadoTopInicial=link.style.top.replace('px','');
		enquadrar(document.getElementById('bordaPontilhada'),link);
		document.getElementById('bordaPontilhada').style.display='';
		movendo=true;
	}
	return false;
}

function posicionar(e,elemento)
{
	if(!e) //se não é internet explorer
	{
		x=event.clientX;
		y=event.clientY;
	}else //se é internet explorer
	{
		x=e.pageX;
		y=e.pageY;
	}
	if(movendo==true) //se o objeto ainda está se movendo...
	{
		enquadrar(document.getElementById('bordaPontilhada'),link); //manda enquadrar a bordaPontilhada em função do link, para que o usuário veja onde ele ficará.
		link.style.left=x+px; //faz o link se mover
		link.style.top=y+py; //faz o link se mover
	}
}
function movimentar(botao,elemento) //ao passar o mouse sobre o link, embute-se a funçao "mover", "parar" e "posicionar" no botão.
{	//botao=icone sob o mouse sendo arrastado - elemento=div do link, contendo o botão
	botao.style.cursor='move';
	if(movendo==false) //movendo=false significa que o link ainda não sofreu onMouseDown
	{
		link=elemento;
		botao.onmousedown=mover; //inicia as ações de movimento
		botao.onmouseup=parar; //para o reposicionamento, e atualiza a posição do link no servidor
		document.onmousemove=posicionar; //reposiciona os outros links da tela
	}
}
function enquadrar(objeto,referencia) //divide a tela virtualmente em colunas e linhas, para forçar o alinhamento dos elementos
{ //objeto=objeto a ser enquadrado
  //referencia=a posição original do objeto, antes do enquadramento
	var w
	w=185; //w=largura da coluna
	var referenciaL,referenciaT,objetoID,objetoL,objetoT
	referenciaL=referencia.offsetLeft;
	referenciaT=referencia.offsetTop;
	//===========
	for(i=20;i<650;i+=w+5) //movendo pelas colunas. || i=60 -> primeira coluna começa a 60px da margem esquerda. || i<1600 -> não há coluna após 1600px (todo:mudar a largura máxima da tela) e 5=margem
	{
		if ((referenciaL-i)<w-15)
		{
			objetoL=i;
			break;
		}
	}
	//===========
	for(i=35;i<1600;i+=25) //movendo pelas linhas. || i=110 -> a primeira linha começa a partir de 110px do topo. || i<1600 -> não há linha abaixo de 1600px
	{
		if ((referenciaT-i)<15)
		{
			objetoT=i;
			break;
		}
	}
	deslocarOutros(objetoT,objetoL,objeto.id);
	objeto.style.left=objetoL;
	objeto.style.top=objetoT;

}
function deslocarOutros(arrastadoTop,arrastadoLeft,objetoID) //desloca os links na tela, em função do link sendo arrastado
{
	//link=posição inicial do link sendo movido
	//desloca todos os outros objetos enquanto se arrasta os links.
	var fixoTop, fixoLeft
	var x=document.getElementsByTagName("div"); //percorre todos os divs da página (x=array com os DIVs)
	for (var i=0;i<x.length;i++)
	{
		if (!isNaN(x[i].id) && x[i].id!=objetoID && x[i].id!=link.id) //se é um div que possui link (ou seja, se o seu ID=NÚMERO e ID<>OBJETO SENDO MOVIMENTADO
		{
			fixoTop=x[i].style.top.replace('px','');
			fixoLeft=x[i].style.left.replace('px','');
			//===se saiu da coluna move os objetos abaixo dele para cima
			if(fixoTop>=arrastadoTopInicial && fixoLeft!=arrastadoLeft && fixoLeft==arrastadoLeftInicial)
			{
				if (x[i].offsetTop>1){x[i].style.top=x[i].offsetTop-25};
			}
			//===se entrou na coluna move os objetos abaixo dele para baixo
			if(fixoTop>=arrastadoTop && fixoLeft==arrastadoLeft && fixoLeft!=arrastadoLeftInicial)
			{
				x[i].style.top=x[i].offsetTop+25;
			}
			//===se arrastou para baixo na mesma coluna.
			if(fixoTop<=arrastadoTop && fixoTop>=arrastadoTopInicial && arrastadoTopInicial!=arrastadoTop && fixoLeft==arrastadoLeft && fixoLeft==arrastadoLeftInicial)
			{
				if (x[i].offsetTop>1){x[i].style.top=x[i].offsetTop-25};
			}
			//===se arrastou para cima na mesma coluna.
			if(fixoTop>=arrastadoTop && fixoTop<=arrastadoTopInicial && arrastadoTopInicial!=arrastadoTop && fixoLeft==arrastadoLeft && fixoLeft==arrastadoLeftInicial)
			{
				x[i].style.top=x[i].offsetTop+25;
			}
		}
	}
	arrastadoLeftInicial=arrastadoLeft;
	arrastadoTopInicial=arrastadoTop;
	return true;
}

function salvaBit() //salva o novo link no banco
{
	var titulo=document.getElementById('titulo');
	var url=document.getElementById('url');
	var favicon=pegaFav(url.value);	
	var ifeed=document.getElementById('ifeed');
	if (ifeed.checked==true){
		xmla=1
	}else{
		xmla=0
	}
	//validações
	if (url.value=='' || url.value.length<=6 || url.value.indexOf('.')==-1 || url.value.indexOf('http://http://')>=0)
	{
		alert('Informe uma URL válida para seu link.');
		document.getElementById('url').focus();
		return;
	}
	if (titulo.value=='')
	{
		alert('Informe um nome para seu link.');
		document.getElementById('titulo').focus();
		return;
	}
	if (url.value.indexOf('://')==-1){url.value='http://'+url.value;}
	//envia os dados do novo link para o banco de dados. uma vez que o salvamento ocorreu, este link aparece na tela, através da função gerarLink()
	if (idAtual==0)
	{
		carregar('/_atualizar.asp?acao=salvar&xmla='+xmla+'&nome='+titulo.value+'&link='+url.value+'&favicon='+favicon+'&x=215&y=1','statusText');
	}
	else
	{
		carregar('/_atualizar.asp?acao=editar&xmla='+xmla+'&id='+idAtual+'&nome='+titulo.value+'&link='+url.value+'&favicon='+favicon+'&x=70&y=85','statusText');
	}
	document.getElementById('bitsNovoForm').style.display='none';
	document.getElementById('bitsNovo').style.display='none';	
}
function gerarLink(vid,ilink,ixml,xmla,vistmp) // é chamado pelo resultado do ajax (imagem salvo.jpg), para incluir o link na tela, uma vez que ele foi salvo no servidor
{
	var titulo=document.getElementById('titulo');
	var url=document.getElementById('url');
	var favicon=pegaFav(url.value);	
	vnovo='<div id=\"'+vid+'\" class=\"super\" style=\"top:1px;left:240px;\"><div><span style=\"float:left;\">';
	vnovo=vnovo+'<img class=\"fav\" onMouseOver=\"movimentar(this,document.getElementById(\''+vid+'\'));\" align=\"left\" src=\"'+favicon+'\">';
	if (ixml>0) {
		vnovo=vnovo+'<a title=\"Exibir perfil\" class=fav href=\"site.asp?id='+ixml+'\"><img id=\"perIMG'+vid+'\" border=0 src=./img/ico16.png></a>'
		vnovo=vnovo+'<a title=\"Exibir últimas novidades\" class=\"fav\" href=\"javascript:void(0)\" onClick=\"exibirFeed(\''+ilink+'\',\''+ixml+'\',1)\"><img border=0 src=./img/rsson.png></a>';
	}
	vnovo=vnovo+'</span><span id=editar style="float:left;display:none"><a href="javascript:void(0)" onClick="editarLink(\''+vid+'\')"><img border=0 src=./img/edit.png></a>'
	vnovo=vnovo+'<a href="javascript:void(0)" onClick="excluirLink(\''+vid+'\')"><img border=0 src=./img/rem.png></a></span>'
	vnovo=vnovo+'<span style="position:absolute;"><a target=\"_blank\" id=url'+vid+' href=\"'+url.value+'\"><span id=tit'+vid+' class="rotulo">'+titulo.value+'</span></a></span>';
	
	vnovo=vnovo+'</div></div>';
	var ns=document.createElement('span');
	var body=document.getElementById('bits');
	body.appendChild(ns);
	ns.innerHTML=vnovo;
	if (vistmp==1){istmp=vistmp;if (document.getElementById('dicaarrastar')){document.getElementById('dicaarrastar').style.display='';}}
	if (document.getElementById('dicaAdicionar')){document.getElementById('dicaAdicionar').style.display='none';}
	destacaLink();
}
var dl;
var dlc=0;
function destacaLink(){
	var dnl=document.getElementById('destacaNovoLink');
	if (dnl.style.display=='none'){
		dnl.style.display='';
	}else{
		dnl.style.display='none';
		dlc=dlc+1;
		if (dlc==4){dlc=0;return;}
	}
	dl=setTimeout('destacaLink()',200)
}
function editarLink(id) //abre o form de inclusao, porém em modo de edição
{
	idAtual=id;
	document.getElementById('bitsNovoForm').style.display=''; //exibe o form 'novo'
	document.getElementById('bitsNovo').style.display=''; //exibe o form 'novo'
	document.getElementById('titulo').value=document.getElementById('tit'+id).innerHTML; //atribui o valor TITULO do link para o form
	document.getElementById('url').value=document.getElementById('url'+id).href; //atribui o valor URL do link para o form
	if (document.getElementById('xmla'+id).innerHTML=='1'){
		document.getElementById('ifeed').checked=true;
	}else{
		document.getElementById('ifeed').checked=false;
	}
}
function excluirLink(id)
{
	if (confirm('Deseja mesmo excluir este link?')){
		carregar('/_atualizar.asp?acao=excluir&id='+id,'statusText');
	}
}
function removerLink(iUsuarioLink)
{
	var remLink=document.getElementById(iUsuarioLink)
	var x=document.getElementsByTagName("div"); //percorre todos os divs da página (x=array com os DIVs)
	for (var i=0;i<x.length;i++)
	{
		if (!isNaN(x[i].id) && x[i].id!=iUsuarioLink) //se é um div que possui link (ou seja, se o seu ID=NÚMERO e ID<>OBJETO SENDO MOVIMENTADO
		{
			//===como remLink deixará de existir, move a coluna toda para cima (se o DIV ATUAL (x) está na altura ou abaixo do link sendo movido E )
			if(parseInt(x[i].style.top.replace('px',''))>=parseInt(remLink.style.top.replace('px','')) && x[i].style.left.replace('px','')==remLink.style.left.replace('px',''))
			{
				x[i].style.top=x[i].offsetTop-25; //move a coluna para cima
			}
		}
	}
	remLink.parentNode.removeChild(remLink);
}
function atualizarLink(id) //é chamada pelo resultado do ajax (imagem salvo.jpg), atualizando os dados do link que foi alterado.
{	
	var titulo=document.getElementById('titulo');
	var url=document.getElementById('url');
	document.getElementById('tit'+id).innerHTML=titulo.value;
	document.getElementById('url'+id).href=url.value;
	document.getElementById('fav'+id).src=pegaFav(url.value);
}
function turnOff(iul){
	if (document.getElementById('rssIMG'+iul)){
		if (document.getElementById('rssIMG'+iul).src.match('rsson')){
			document.getElementById('rssIMG'+iul).src='img/rssoff.png';
			document.getElementById('tit'+iul).style.fontWeight='normal';
		}
	}
}
function exibirFeed(link,xml,iul,pg){
		feed.style.display='';
		feed.style.top=document.body.scrollTop+25+'px';
		var myDate = new Date();
		carregar('/_feed.asp?pg='+pg+'&link='+link+'&xml='+xml+'&iul='+iul+'&rnd='+myDate.getMinutes(),'feed');
}
function fecharFeed(){
		feed.style.display='none';
}

function revisaoTLD(){
	var u=document.getElementById('url');
	if (u.value.indexOf('http://http://')==0){
		u.value=u.value.replace('http://http://','http://');
	}
}

function dicaTLD(){
	var t=document.getElementById('titulo');
	var u=document.getElementById('url');
	if (t.value.length==0 && u.value.length>0){
		t.value=pegaTLD(u.value);
	}
}
function pegaTLD(url) {
	var indice;
	var str1;
	str1=url.replace('http://','');
	indice=str1.indexOf('/');
	if (indice>=0){
		return str1.substring(0,indice);
	}else{
		return str1;
	}
}

function pegaFav(url) //função que pega o favicon. será passado no futuro para o servidor, pois deve ser mais elaborado. esta função trabalha de modo simples, apenas adicionando 'favicon.ico' no final do TLD
{
	vindex=url.indexOf('/',9);
	if (vindex==-1)
	{
		url=url+'/';
		vindex=url.indexOf('/',9);
	}
	url=url.substr(0,vindex+1);
	return url+'favicon.ico';
}

function salvaPI() {
	var piurl=document.getElementById('piurl');
	var pipass1=document.getElementById('pipass1');
	var pipass2=document.getElementById('pipass2');
	var pimail1=document.getElementById('pimail1');
	var pimail2=document.getElementById('pimail2');
	var tos=document.getElementById('tos');
	//validações
	if (isValid(piurl.value,'abcdefghijklmnopqrstuvwxyz0123456789-_')==false || piurl.value.length<4)
	{
		alert('Informe uma URL válida. A URL deve conter no mínimo 4 caracters apenas com letras, números - e _');
		piurl.focus();
		return;
	}
	if (pipass1.value.length<6)
	{
		alert('Sua senha deve conter no mínimo 6 caracteres.');
		pipass1.focus();
		return;
	}
	if (pipass1.value!=pipass2.value)
	{
		alert('A primeira senha não confere com a segunda.');
		pipass1.focus();
		return;
	}
	if (pimail1.value.length<6)
	{
		alert('Digite um e-mail válido.');
		pimail1.focus();
		return;
	}
	if (pimail1.value!=pimail2.value)
	{
		alert('O primeiro e-mail não confere com o segundo.');
		pimail1.focus();
		return;
	}
	if (tos.checked==false)
	{
		alert('Você deve concordar com os termos de uso para prosseguir.');
		return;
	}
	//envia os dados do novo link para o banco de dados. uma vez que o salvamento ocorreu, este link aparece na tela, através da função gerarLink()
	carregar('/_usuario.asp?acao=usuario&piurl='+piurl.value+'&pipass1='+pipass1.value+'&pipass2='+pipass2.value+'&pimail1='+pimail1.value+'&pimail2='+pimail2.value+'&tos='+tos.checked,'pistatus');
}
function usuarioOk(usuario){
	if (usuario!=''){
	//redireciona para a nova URL
	window.location='http://'+usuario+'.letabit.com/?bemvindo=1'
	}else{
		document.getElementById('statusText').innerHTML='<div style="position:relative;background-color:#ffffcc;width:100%;text-align:center;">Seus dados foram atualizados com sucesso.</div>';
		document.getElementById('novaPI').style.display='none';
		document.getElementById('bitsNovo').style.display='none';		
	}
}
function exibeLogin(){
	if (document.getElementById('login').style.display=='none')
	{
		document.getElementById('login').style.display='';
	}else{
		document.getElementById('login').style.display='none';
	}
}
function exibeNovaPI()
{
	if (document.getElementById('novaPI').style.display=='none')
	{
		idAtual=0;
		document.getElementById('novaPI').style.display='';
		document.getElementById('bitsNovo').style.display='';
		document.getElementById('piurl').value='';
		document.getElementById('pipass1').value='';
		document.getElementById('pipass2').value='';
		document.getElementById('pimail1').value='';
		document.getElementById('pimail2').value='';
		document.getElementById('tos').checked=false;
		document.getElementById('piurl').focus();
	}else
	{
		document.getElementById('novaPI').style.display='none';
		document.getElementById('bitsNovo').style.display='none';
	}
}
function validaURL() {
	document.getElementById('avisoURL').innerHTML=isValid(document.getElementById('piurl').value,'abcdefghijklmnopqrstuvwxyz0123456789-_');
	var vurl=document.getElementById('piurl').value;
	var obj=document.getElementById('avisoURL');
	if (vurl.length<4) {obj.innerHTML='A URL deve conter no mínimo 4 caracteres  (letras, números, - ou _)';obj.style.color='gray';return;}
	if(isValid(vurl,'abcdefghijklmnopqrstuvwxyz0123456789-_')==false){obj.innerHTML='A URL só pode conter letras, números e os caracteres - ou _';obj.style.color='gray';return;}else{}
	obj.innerHTML='URL válida';
	obj.style.color='darkgreen';
}
function validaPass(){
	var obj=document.getElementById('pipass1');
	var obj2=document.getElementById('avisoPass');
	if (obj.value.length<6) {
		obj2.innerHTML='Sua senha deve conter no mínimo 6 caracteres.';obj2.style.color='gray';
	}else {obj2.innerHTML='Senha válida';obj2.style.color='darkgreen';}
}
function validaPass2(){
	var obj=document.getElementById('pipass1');
	var obj2=document.getElementById('pipass2');
	var obj3=document.getElementById('avisoPass');
	if (obj.value!=obj2.value) {
		obj3.innerHTML='A primeira senha não confere com a segunda.';obj3.style.color='gray';
	}else {obj3.innerHTML='Senha válida';obj3.style.color='darkgreen';}
}

function isValid(texto,permitidos) {
	if (texto == "") return true;
	for (i=0; i<texto.length; i++) {
		if (permitidos.indexOf(texto.charAt(i),0) == -1) return false;
	}
	return true;
}





function exibeNovo() //exibe form para incluir novo link
{
	if (document.getElementById('bitsNovoForm').style.display=='none')
	{
		idAtual=0;
		document.getElementById('bitsNovoForm').style.display='';
		document.getElementById('bitsNovo').style.display='';
		document.getElementById('titulo').value='';
		document.getElementById('url').value='http://';
		document.getElementById('url').focus();
		document.getElementById('ifeed').checked=true;
	}else
	{
		document.getElementById('bitsNovoForm').style.display='none';
		document.getElementById('bitsNovo').style.display='none';
	}
}

function exibeEdicao() // exibe os botões de edição e exclusão
{
	var exibir;
	if (document.getElementById('editar').style.display=='none')
	{
		exibir='';
		document.getElementById('bitsTituloBotaoEditar').innerHTML='Fechar edição';
	}
	else
	{
		exibir='none';
		document.getElementById('bitsTituloBotaoEditar').innerHTML='Editar';
	}
	var x=document.getElementsByTagName("span");
	for (var i=0;i<x.length;i++)
	{
		if (x[i].id=='editar')
		{
			x[i].style.display=exibir;
		}
	}
}

function addFav(vurl){
	title = "Minha página inicial - Let a Bit"; 
  // Blogger - Replace with <$BlogItemTitle$> 
  // MovableType - Replace with <$MTEntryTitle$>

 url = vurl;
  // Blogger - Replace with <$BlogItemPermalinkURL$> 
  // MovableType - Replace with <$MTEntryPermalink$>
  // WordPress - <?php bloginfo('url'); ?>

	if (window.sidebar) { // Mozilla Firefox Bookmark
		window.sidebar.addPanel(title, url,"");
	} else if( window.external ) { // IE Favorite
		window.external.AddFavorite( url, title); }
	else if(window.opera && window.print) { // Opera Hotlist
		return true; }
}
