$(document).ready(function( ) {

	// ----------------------------------------
	// colorbox
	$("a[rel='cbox']").colorbox( );

	// ----------------------------------------
	// enquete
	var enqueteContentBackup = '';
	var enqueteMainContainer = 'div #enqueteContainer';

	$( 'form#enqueteForm' ).submit( function( ) {
		return false;
	});

	$( 'form#enqueteForm .btvotar' ).click(function( ) {

		var form	  = $(this).parent( );
		var enquete_  = form.children( '#id_enquete' ).val( );
		var resposta_ = $( 'form#enqueteForm input:radio[name=resposta]:checked' ).val( );

		if ( !resposta_ || !enquete_ )
		{
			alert( 'Escolha uma opção!' );
			return false;
		}

		var param = { idEnquete: enquete_, idEnqueteResposta: resposta_ };

		$.myPost( '/ajax_enquete.php', param, function( response ) {

			enqueteContentBackup = $( enqueteMainContainer ).html( );

			$( enqueteMainContainer ).html( '<img src="' + tb_pathToImage + '" />' );

			if ( response == 'ERRO' )
			{
				$( enqueteMainContainer ).html( '<p>Seu voto não foi confirmado, tente novamente mais tarde!</p>' );
			}
			else
			{
				$( enqueteMainContainer ).html( '' );
				var respostas = response.respostas;
				for ( i in respostas )
				{
					var resposta = respostas[i];
					var respostaText = '<p>' + resposta.resposta + ' (' + resposta.contador + ')</p>';
					$( enqueteMainContainer ).append( respostaText );
				}
				$( enqueteMainContainer ).append( '<p><b>Seu voto foi confirmado!</b></p>' );
			}
			$( enqueteMainContainer ).fadeOut( ).fadeIn( ).fadeOut( ).fadeIn( );
		});

		return false;
	});


	// ----------------------------------------
	// autocomplete
	$( 'form#searchAutocompleteForm' ).submit(function( ) {
		return false;
	});

	function format( mail )
	{
		return mail.titulo;
	}

	$( '#searchAutocomplete' ).autocomplete( '/ajax_search.php', {
		multiple: true,
		dataType: 'json',
		parse: function(data) {
			return $.map(data, function(row) {
				return {
					data: row,
					value: row.titulo,
					result: row.titulo
				};
			});
		},
		formatItem: function( item ) {
			return format( item );
		}
	}).result(function( e, item ) {
		top.location.replace( item.link );
	});


	// ----------------------------------------
	// indique

	$( 'a.icoindique' ).cluetip({
		cluetipClass: 'jtip',
		activation: 'click',
		arrows: true,
		dropShadow: false,
		hoverIntent: false,
		sticky: true,
		mouseOutClose: false,
		local: true,
		closePosition: 'title',
		closeText: '<img src="' + window.MAINDOMAIN + '/js/jquery/cluetip/images/cross.png" alt="Fechar" />'
	});

	$( 'form#indique' ).submit(function( ) {
		return false;
	});

	$( 'form#indique .submit' ).click(function( ) {
		var form   = $(this).parent( );
		var name_  = form.children('#name').val( );
		var email_ = form.children('#email').val( );
		var friendName_  = form.children('#friendName').val( );
		var friendEmail_ = form.children('#friendEmail').val( );

		if ( !name_ || !email_ || !friendName_ || !friendEmail_ )
		{
			alert( 'Todos os campos são obrigatórios!' );
			return false;
		}

		var param = { name: name_, email: email_,
					  friendName: friendName_, friendEmail: friendEmail_,
					  link: self.location.href };

		$.myPost( '/indique.php', param, function( response ) {
			if ( response == 'OK' )
			{
				alert( 'Sua mensagem foi enviada!' );
				$( 'div#cluetip-close' ).click( );
			}
			else
			{
				alert( 'Sua mensagem não foi enviada, tente novamente!' );
			}
		});

		return false;
	});


	// ----------------------------------------
	// contato

	$( 'form#contato' ).submit(function( ) {
		return false;
	});

	$( 'form#contato .submit' ).click(function( ) {
		var form		= $(this).parent( );
		var nome_		= form.children('label#lNome').children('#nome');
		var telefone_	= form.children('label#lTelefone').children('#telefone');
		var email_		= form.children('label#lEmail').children('#email');
		var mensagem_	= form.children('label#lMensagem').children('#mensagem');
		var destino_	= form.children('label#lDestino').children('#destino');

		if ( !nome_.val( ) || !email_.val( ) || !mensagem_.val( ) )
		{
			alert( 'Todos os campos são obrigatórios!' );
			return false;
		}

		var param = { nome: nome_.val( ), telefone: telefone_.val( ),
					  email: email_.val( ), mensagem: mensagem_.val( ),
					  destino: destino_.val( ) };

		$.myPost( '/envia_contato.php', param, function( response ) {
			if ( response == 'OK' )
			{
				alert( 'Sua mensagem foi enviada!' );
				nome_.val( '' );
				telefone_.val( '' );
				email_.val( '' );
				mensagem_.val( '' );
			}
			else
			{
				alert( 'Sua mensagem não foi enviada, tente novamente!' );
			}
		});

		return false;
	});


	// ----------------------------------------
	// banners

	$( '#bannerSlider' ).cycle({
		delay: 3000,
		speed: 500
	});


	// ----------------------------------------
	// acesso restrito

	$( 'a.arearestrita' ).cluetip({
		positionBy: 'bottomTop',
		cluetipClass: 'jtip',
		activation: 'click',
		arrows: true,
		dropShadow: false,
		hoverIntent: false,
		sticky: true,
		mouseOutClose: false,
		local: true,
		closePosition: 'title',
		closeText: '<img src="' + window.MAINDOMAIN + '/js/jquery/cluetip/images/cross.png" alt="Fechar" />'
	});
	
	$( 'form#acessaoRestrito' ).submit(function( ) {
		return false;
	});

	$( 'form#acessaoRestrito .submit' ).click(function( ) {
		var form   = $(this).parent( );
		var login_ = form.children('#login').val( );
		var senha_ = form.children('#senha').val( );

		if ( !login_ || !senha_ )
		{
			alert( 'Todos os campos são obrigatórios!' );
			return false;
		}

		var param = { login: login_, senha: $.md5( senha_ ) };

		$.myPost( '/acessar.php', param, function( response ) {
			if ( response == 'OK' )
			{
				top.location.replace( window.MAINDOMAIN + '/adm/publicacao.php' );
			}
			else if ( response == 'leitura' )
			{
				top.location.replace( window.MAINDOMAIN + '/restritas' );
			}
			else
			{
				alert( 'Login e/ou senha inválidos!' );
			}
		});

		return false;
	});


	// ----------------------------------------
	// imprimir

	$( 'a.icoprint' ).click(function( ) { 
		var title = $( 'h2.title_pg' ).html( );
		var content = $( 'div.conteudo-int div#mainContent' ).html( );
		var url = self.location.href;
		var wnd = window.open( '', '_blank', 'status=1, toolbar=1' );
		wnd.document.write( '<html><head><style>span.p_center{display: none;}</style></head><body><h1>' + title + '</h1>' + content + '<hr>' + url  + '</body></html>');
		wnd.print( );
	});


	// ----------------------------------------
	// redes sociais

	var currentUrl = null;

	function openShareLink( url, network )
	{
		var networkUrl;
		var title = escape( $( 'h2.title_pg' ).html( ) ? $( 'h2.title_pg' ).html( ) : window.RADIONOME );
		var url = escape( url );

		switch ( network )
		{
			case 'facebook': 
				networkUrl = 'http://www.facebook.com/sharer.php?u=' + url;
			break;
	
			case 'twitter':
				networkUrl = 'http://twitter.com/home?status=' + title + ' ' + url;
			break;
	
			case 'google':
				networkUrl = 'http://www.google.com/bookmarks/mark?op=edit&output=popup&bkmk='+ url +'&title=' + title;
			break;
	
			case 'myspace':
				networkUrl = 'http://www.myspace.com/index.cfm?fuseaction=postto&t=' + title + '&c=&u=' + url + '&l=5';
			break;
	
			case 'digg':
				networkUrl = 'http://digg.com/submit?phase=2&url=' + url;
			break;
	
			case 'delicious':
				networkUrl = 'http://del.icio.us/post?url=' + url;
			break;
	
			case 'orkut':
				networkUrl = 'http://promote.orkut.com/preview?nt=orkut.com&tt=' + title + '&du=' + url + '&tn=';
			break;
	
			default: return false;
		}
	
		window.open ( networkUrl, 'socialNetworkWindow', 'status=1, toolbar=1' );
	}


	$( 'a.socialNetwork' ).click(function( ) {

		var network = $(this).attr('title').toLowerCase( );

		if ( window.currentUrl )
			openShareLink( window.currentUrl, network );
		else
			openShareLink( self.location.href, network );

		return false;
	});


	var param = { link: self.location.href };

	$.myPost( '/shorturl.php', param, function( response ) {
		if ( response )
		{
			window.currentUrl = response;

			// http://www.mcardoso.net/socialize-com-o-novo-botao-like-curtir-do-facebook/
			//
			var url_ = 'http://www.facebook.com/plugins/like.php?href=' + window.currentUrl + '&layout=standard&show_faces=true&width=300&action=like&font=lucida+grande&colorscheme=dark';
			$( 'iframe#facebookLikeIframe' ).attr( 'src', url_ );
		}
	});


	// ----------------------------------------
	// player

	$( 'a.openPlayer' ).click(function( ) {

		var idRadio = $(this).attr( 'rel' );
		window.open ( window.MAINDOMAIN + '/player.php?id=' + idRadio, 'scalabriniPlayer', 'status=0, toolbar=0, location=0, menubar=0, directories=0, resizable=0, scrollbars=0, width=520, height=350' );
		return false;
	});


	// ----------------------------------------
	// programacao

	$( 'a.openProgramacao' ).click(function( ) {

		var idRadio = $(this).attr( 'rel' );
		window.open ( window.MAINDOMAIN + '/programacao.php?id=' + idRadio, 'scalabriniProgramacao', 'status=0, toolbar=0, location=0, menubar=0, directories=0, resizable=0, scrollbars=0, width=600, height=420' );
		return false;
	});

});

