
jQuery(document).ready(function($) {
  $('a[rel*=facebox]').facebox();
  
/*
  jQuery('a.minibutton').bind({
    mousedown: function() {
      jQuery(this).addClass('mousedown');
    },
    blur: function() {
      jQuery(this).removeClass('mousedown');
    },
    mouseup: function() {
      jQuery(this).removeClass('mousedown');
    }
  });*/
 
     $("ul.dropdown li").hover(function(){
    
        $(this).addClass("hover");
        $('ul:first',this).css('visibility', 'visible');
    
    }, function(){
    
        $(this).removeClass("hover");
        $('ul:first',this).css('visibility', 'hidden');
    
    });
    
    $("ul.dropdown li ul li:has(ul)").find("a:first").append(" &raquo; ");
  
});
 
function showHideContent(div)
{
	var obj = document.getElementById(div);
	if(obj.style.display=='block'){
		obj.style.display='none';
	}else{
		obj.style.display='block';
	}		
}

function goToChannel(channel)
{
	//alert(channel);
	location.href = SITEDIR +'/canal/'+channel;
}

function showContent(div)
{
	var obj = document.getElementById(div);
	obj.style.display='block'
}

function hideContent(div)
{
	var obj = document.getElementById(div);
	obj.style.display='none';
}

function jqueryShowHide(div)
{
	$('#'+div).toggle('slow');	
}

function jqueryHide(div)
{
	$('#'+div).fadeOut('slow');
}

function ajaxAction(action,args,callback)
{
	$.post(SITEDIR+"/actions/ajaxutil/"+action,args,callback);

}

function loadContent(content,container,args)
{
	$.post(SITEDIR+"/actions/getContent/"+content,args, function(data) {
		$('#'+container).html(data);
	});
	
}

function loadContentBox(content,args)
{
	$.post(SITEDIR+"/actions/getContent/"+content,args, function(data) {
		jQuery.facebox(data);
	});
	
}

function loadFAQ(cat)
{
	$.post(SITEDIR+"/actions/getContent/faq",{'cat': cat}, function(data) {
		jQuery.facebox(data);
	});
	
}

function checkLogin(login,container)
{
	ajaxAction("checkLogin",{'login': login}, function(data) {
		$('#'+container).html(data);
	});
}

function checkEmail(email,container)
{
	ajaxAction("checkEmail",{'email': email}, function(data) {
		$('#'+container).html(data);
	});
}

function ajaxLogin(container,loadtemplate)
{
	var login = $('#inp_login').val();
	var senha = $('#inp_senha').val();
	
	ajaxAction("checkEmail",{'login': login,'senha':senha,'template':loadtemplate}, function(data) {
		if(data)
		{
			$('#'+container).html(data);
		}
		else
		{
			alert("Erro de Autenticação. Verifique se os dados estão corretos.");
		}
	});
}


function followTW()
{
	ajaxAction("twFollow",args, function(data) {
		jQuery.facebox(data);
	});
}

function gostei(post_type,post_id)
{
	ajaxAction("gostei",{'type': post_type,'id': post_id}, function(data) {
		jQuery.facebox(data);
	});
}

function favorite(type,post_id)
{
	ajaxAction("favorite",{'type': type,'id': post_id}, function(data) {
		jQuery.facebox(data);
	});
}

function verifyvideo(video_url)
{
	ajaxAction("verifyvideo",{'video': video_url}, function(data) {
		document.getElementById('msg_verify').innerHTML = data;
	});
}

function follow(user_id)
{
	ajaxAction("follow",{'user': user_id}, function(data) {
		jQuery.facebox(data);
	});
}

function unfollow(user_id)
{
	ajaxAction("unfollow",{'user': user_id}, function(data) {
		jQuery.facebox(data);
	});
}

function deleteComment(com_id,post_owner)
{
	ajaxAction("apagacoment",{'id': com_id,'post_owner':post_owner }, function(data) {	
		jQuery.facebox(data);
		$('#comm'+com_id).fadeOut('slow');
	});
}

function deleteResposta(resp_id,post_owner)
{
	ajaxAction("apagaresposta",{'id': resp_id,'post_owner':post_owner }, function(data) {	
		jQuery.facebox(data);
		$('#resp'+resp_id).fadeOut('slow');
	});
}

function showSubcatSel(canal,select)
{
	var canal_id = $(canal).val();
	var options;
	
	ajaxAction("getSubcats",{'canal':canal_id}, function(data) {
		var oselect = $('#'+select);
		
		oselect.find('option')
			.remove()
			.end()
			.append('<option value="0">Selecione a categoria</option>')
			.val('0')
		;
		
		/*$.each(data, function(key,val) {
				
				  $('<option/>').attr('value', val.id)
                  .html(val.nome)
                  .appendTo(oselect);
		});*/
		oselect.html(data);
	});
}

function showCidadeSel(estado,select)
{
	var est_id = $(estado).val();
	var options;
	
	ajaxAction("getCidades",{'estado':est_id}, function(data) {
		var oselect = $('#'+select);
		
		oselect.find('option')
			.remove()
			.end()
			.append('<option value="0">Selecione a cidade</option>')
			.val('0')
		;
		
		/*$.each(data, function(key,val) {
				
				  $('<option/>').attr('value', val.id)
                  .html(val.nome)
                  .appendTo(oselect);
		});*/
		oselect.html(data);
	});
}

function publicaPost()
{
	if(confirm('Deseja publicar o post agora? Ele será submetido para a moderação do site.'))
	{
		$('#rascunho').val('0');
		$('#formcreate').submit();
	}
	
}

function showPasso(step_id,step_nmbr)
{
	var player = document.getElementById('playerSteps');
	player.innerHTML = '<img src="'+SITEDIR+'/imagens/loading.gif">';
	
	ajaxAction("showPasso",{'id': step_id,'number':step_nmbr }, function(data) {	
		player.innerHTML = data;
	});
}

function walk(direction)
{
	
	var firstV = document.getElementById('divPassoFirstVis').value;
	var lastV = document.getElementById('divPassoLastVis').value;
	var lastP = document.getElementById('divPassoLast').value;
	
	if(direction == 'next')
	{
		var w_to = parseInt(lastV)+1;

		if(w_to <= lastP)
		{
			var phide = 'divPasso'+firstV;
			var pshow = 'divPasso'+w_to;
			
			lastV = w_to;
			firstV = parseInt(firstV)+1;
		}
	}
	else
	{
		var w_to = parseInt(firstV)-1;
		if(w_to >= 1)
		{
			var phide = 'divPasso'+lastV;
			var pshow = 'divPasso'+w_to;
			
			lastV = parseInt(lastV)-1;
			firstV = w_to;
		}
	}
	
	if(phide)
	{
		/*walk*/

		document.getElementById(phide).style.display='none';
		document.getElementById(pshow).style.display='block';
		
		
		document.getElementById('divPassoLastVis').value = lastV;
		document.getElementById('divPassoFirstVis').value = firstV;
	}

}

function deletePost(post_type,post_id)
{
	if(confirm('Tem certeza que deseja excluir este post?'))
	{
		ajaxAction("apagapost",{'id': post_id,'type':post_type }, function(data) {	
			if(data == 0)
				alert('Você não tem permissão para exluir este post.');
			else
			{			
				alert('Post excluído.');
				window.location.href = SITEDIR+'/home/posts';
			}
		});
	}
}

function showTooltip(div)
{
	var obj = document.getElementById(div);
	if(obj.style.display=='block'){
		obj.style.display='none';
	}else{
		obj.style.display='block';
	}	
}

function checklogin(login,retwr)
{
	
	var req = new getHTTPObject();

	req.open('POST', '/actions/admin/checkNickname', false);
	req.setRequestHeader('Content-type','application/x-www-form-urlencoded;charset=UTF-8;');	

	var string = 'nick='+login+'&XMLHttpRequest=test';
	req.send(string);
	if(req.status == 200)
	{	 
	  document.getElementById(retwr).innerHTML = req.responseText;
	}

}



function checkemail(email,retwr)
{
	var req = new getHTTPObject();

	req.open('POST', '/actions/admin/checkEmail', false);
	req.setRequestHeader('Content-type','application/x-www-form-urlencoded;charset=UTF-8;');	

	var string = 'email='+email+'&XMLHttpRequest=test';
	req.send(string);
	if(req.status == 200)
	{	 
	  document.getElementById(retwr).innerHTML = req.responseText;
	}
}

/* admin */

function putDestaque(tipo,post)
{
	$.post(SITEDIR+"/actions/admin/putDestaque",{tipo:tipo,id:post},function(data) {
			$('#postStatus_'+tipo+'_'+post).html('<img src="/imagens/icones/status_'+data+'.png" />');
	});
}

function putDestaqueEspecial(especial)
{
	$.post(SITEDIR+"/actions/admin/putDestaqueEspecial",{id:especial},function(data) {
			$('#especialStatus_'+especial).html('<img src="/imagens/icones/status_'+data+'.png" />');
	});
}

function putDestaqueRot(tipo,post)
{
	$.post(SITEDIR+"/actions/admin/putDestaqueRot",{tipo:tipo,id:post},function(data) {
			$('#postDRot_'+tipo+'_'+post).html('<img src="/imagens/icones/status_'+data+'.png" />');
	});
}

function putDestaqueCan(tipo,post)
{
	$.post(SITEDIR+"/actions/admin/putDestaqueCan",{tipo:tipo,id:post},function(data) {
			$('#postDCan_'+tipo+'_'+post).html('<img src="/imagens/icones/status_'+data+'.png" />');
	});
}


function destMudaStatus(destaque)
{
	$.post(SITEDIR+"/actions/admin/destMudaStatus",{id:destaque},function(data) {
			$('#destStatus_'+post).html('<img src="/imagens/icones/status_'+data+'.png" />');
	});
}

function postAprova(tipo,post)
{
	if(confirm('Tem certeza que deseja aprovar este post? Os pontos serão creditados na conta do usuário.'))
	{
		$.post(SITEDIR+"/actions/admin/postPublicar",{tipo:tipo,id:post},function(data) {
			$('#td_'+tipo+'_'+post).attr('style', 'background-color:'+data);
		});
	}
}

function postReprova(tipo,post)
{
	if(confirm('Tem certeza que deseja reprovar este post?'))
	{
		$.post(SITEDIR+"/actions/admin/postReprovar",{tipo:tipo,id:post},function(data) {	
			$('#td_'+tipo+'_'+post).attr('style', 'background-color:'+data);
		});
	}
}

function postMudaStatus(tipo,post)
{
	alert('tipo:'+tipo+' post: '+post);
	var status = $('#status_'+tipo+'_'+post).val();
	
	if(status == 1)
		postAprova(tipo,post);
	else if(status == 2)
		postReprova(tipo,post);
	else
		$.post(SITEDIR+"/actions/admin/postMudaStatus",{tipo:tipo,id:post,status:status},function(data) {	
			$('#td_'+tipo+'_'+post).attr('style', 'background-color:'+data);
		});
}


function postApaga(tipo,post)
{
	if(confirm('Tem certeza que deseja excluir permanentemente este post?'))
	{
		$.post(SITEDIR+"/actions/admin/apagaPost",{tipo:tipo,id:post},function(data) {
		
			$('#tr_post_'+post).toggle();
		});
	}
}

function twDisconnect()
{
	if(confirm('Tem certeza que deseja desconectar sua conta do Twitter?'))
	{
		location.href(SITEDIR+'/home/settings/connections/twdisconnect');
	}
}

function deleteNotificacao(not_id)
{
	ajaxAction("apaganotificacao",{'id': not_id }, function(data) {	
		if(data == 1)
			$('#notif'+not_id).fadeOut('slow');
		else
			alert("Ocorreu um erro desconhecido.");
	});
}

function myFileBrowser (field_name, url, type, win) {

    // alert("Field_Name: " + field_name + "nURL: " + url + "nType: " + type + "nWin: " + win); // debug/testing

    /* If you work with sessions in PHP and your client doesn't accept cookies you might need to carry
       the session name and session ID in the request string (can look like this: "?PHPSESSID=88p0n70s9dsknra96qhuk6etm5").
       These lines of code extract the necessary parameters and add them back to the filebrowser URL again. */

    var cmsURL = "/filebrowser";    // script URL - use an absolute path!
    if (cmsURL.indexOf("?") < 0) {
        //add the type as the only query parameter
        cmsURL = cmsURL + "?type=" + type;
    }
    else {
        //add the type as an additional query parameter
        // (PHP session ID is now included if there is one at all)
        cmsURL = cmsURL + "&type=" + type;
    }

    tinyMCE.activeEditor.windowManager.open({
        file : cmsURL,
        title : 'My File Browser',
        width : 600,  // Your dimensions may differ - toy around with them!
        height : 400,
        resizable : "yes",
        inline : "yes",  // This parameter only has an effect if you use the inlinepopups plugin!
        close_previous : "no"
    }, {
        window : win,
        input : field_name
    });
    return false;
}


function loadComentarios(tipo,post,pagina)
{
	$('#comentarios-wrapper').html('<p class="textcenter"><img src="/imagens/loading.gif" /></p>');
	
	$.post(SITEDIR+"/actions/ajaxutil/loadComments",{tipo:tipo,id:post,page:pagina},function(data) {
			$('#comentarios-wrapper').html(data);
	});
}

function replyComment(id,autor)
{
	$('#replyTo').val(id);
	if(autor)
		$('#replyToMessage').html('Postar resposta ao comentário de <strong>'+autor+'</strong>.');
	else
		$('#replyToMessage').html('');
}

function postComentario()
{
	var tipo = $('#postType').val();
	var id = $('#postId').val();
	var texto = $('#comment').val();
	var replyTo = $('#replyTo').val();
	
	var autor="";
	var autor_url="";
	var autor_email="";

	var r_challenge = $('[name=recaptcha_challenge_field]').val();
	var r_response = $('[name=recaptcha_response_field]').val();
	
	if(!$('#loggedUser').val())
	{
		autor = $('#autor').val();
		autor_url = $('#autor_url').val();
		autor_email = $('#autor_email').val();
	}
	
	$.post(SITEDIR+"/actions/ajaxutil/postComment",{tipo:tipo,id:id,texto:texto,autor:autor,autor_url:autor_url,autor_email:autor_email,in_reply_to:replyTo,recaptcha_challenge_field:r_challenge,recaptcha_response_field: r_response},function(data) {
		
		var res = data.split(':');
		
		if(res[0] == 1)
		{
			$('#comment').val('');
			$('#comentarios-form-message').html('<p class="boxOk">'+res[1]+'</p>');
			
			loadComentarios(tipo,id,'last');
			reloadCommentForm();
		}
		else
		{
			$('#comentarios-form-message').html('<p class="boxErro">'+res[1]+'</p>');
		}
	});
}

function reloadCommentForm()
{
	$.post(SITEDIR+"/actions/getContent/commentForm",function(data) {
		$('#comentarios-form-wrapper').html(data);
	});
	
}

function finalizaPremio()
{
	if(confirm('Deseja finalizar o prêmio agora? O usuário em verde será o vencedor e os pontos do mês serão zerados para todos os usuários.'))
	{
		$('#formfinalizapremio').submit();
	}
	
}

