//~~~~~ BASE.JS

//~~~ [I]
var base_js = {
	init: function() 
	{
		autocomplete_series.start();
		calculate_time_elapsed_for_comments.start();
		user_feedback.start();
		new_new_comment.start();
		go_to_access.start();
		Sy_scroll.start();
		slider.start();
		collaborate.start();
		delete_comments_and_reviews.start();
		change_spoiler.start();
		most_viewed.start();
		validate_contact_info.start();
		validate_advertise.start();
		user_not_logged.start();
		comment_votes.start();
	}
};
//~~~ colaborar
var collaborate = {
	start: function() 
	{
		var collaborate_button = $('.collaborate');
		
		if( collaborate_button.length > 0 ) 
		{	
			var go_to_perfil_collab = $('#go_to_perfil_collab');
			
			go_to_perfil_collab.on( 'click', function( evt ) 
			{
					var _this = $(this);
					var user = _this.attr( 'data-user' );
					var type = _this.attr( 'data-type' );
					
					if( user == "no_user_:D" )
					{
						collaboration_dialog.dialog( 'close' );
						$('#loginreg').trigger( 'click' );
						return false;
					}
					else
					{
						if( type == 'serie' )
						{
							location.pathname = "/usuario/colaboracion_serie";
							return false;
						}
						
						if( type == 'movie' )
						{
							location.pathname = "/usuario/colaboracion_pelicula";
							return false;
						}
					}
						
				}
			);
			
			var collaboration_dialog = $('#collaboration-dialog');
			
			collaborate_button.on( 'click', function( evt ) 
			{
				evt.preventDefault();
							
				_this = $(this);
				
				var type 		= _this.attr( 'data-type' ); //serie o pelicula
				
				if( $('.user-menu').length > 0 )
				{
					if( type == 'serie' )
					{
						location.pathname = "/usuario/colaboracion_serie";
						return;
					}
					
					if( type == 'movie' )
					{
						location.pathname = "/usuario/colaboracion_pelicula";
						return;
					}
					
				}
				
				var vform		= null;
				var prefix 		= "collaboration_" +type + "_";
				var form 		= eval( "document." +prefix +"form" );
				var title 		= _this.attr( 'data-value' );
				var type_title	= '';
				
				if( type == 'serie' )
				{
					type_title = 'serie.';
					
					if( _this.attr( "data-season" ) )
						form[ prefix +"season"].value = _this.attr( "data-season" );
					if( _this.attr( "data-episode" ) )
						form[ prefix +"episode"].value = _this.attr( "data-episode" );
				} 
				else
				{
					if( type == 'movie' )
					{
						type_title = 'película';
					}
				}
				
				
				collaboration_dialog.dialog(
				{
					modal: true,
		   			title: 'Colaboración anónima de ' +type_title,
		   			resizable: false,
		   			width: 500,
					beforeClose: function() 
					{
						form.reset();
						if( vform )
						{
							vform.validate().resetForm();
						}
					},
					open: function() 
					{
						form[ prefix +"name"].value = title;
					},
					buttons: 
					{
						Cancelar: function() 
						{
									collaboration_dialog.dialog( 'close' );
						},
						Enviar: function() 
						{	
							var language 	= form[ prefix +"language"].value;
							var subtitles 	= form[ prefix +"subtitles"].value;
							var email 		= form[ prefix +"mail"].value;
							var link 		= form[ prefix +"link"].value;
							var info 		= form[ prefix +"comment_info"].value;
							
							var collaboration = null;
							
							if( type == 'movie' )
							{
								vform = $('#collaboration_movie_form');
								vform.validate({
									rules: 
									{
										collaboration_movie_language: 
										{
											required: function( element ) 
											{
												return element.selectedIndex < 1 || element.selectedIndex > 12;
											}
										},
										collaboration_movie_subtitles: 
										{
											required: function( element ) 
											{
												return element.selectedIndex < 1 || element.selectedIndex > 10;
											}
										},
										collaboration_movie_source:
										{
											required: function( element )
											{
												return element.selectedIndex < 1 || element.selectedIndex > 13;
											}
										},
										collaboration_movie_name: true,
										collaboration_movie_mail: 
										{
											required: true,
											email: true
										},
										collaboration_movie_link: 
										{
											required: function( element )
											{
												return $(element).val != "";
											}
										}
									},
									messages: 
									{
										collaboration_movie_language: 'Debes seleccionar un idioma de la lista.',
										collaboration_movie_subtitles: 'Subtítulos inválidos.',
										collaboration_movie_source: 'Selecciona el origen del vídeo de la lista.',
										collaboration_movie_name: 'Nombre de película obligatorio.',
										collaboration_movie_mail: 'Introduce un email válido.',
										collaboration_movie_link: 'Es obligatorio introducir un enlace.'
									},
									errorElement: 'div',
									errorClass: 'error_msg'
								});

								if( !vform.validate().form() )
									return;
								
								var source		= form[ prefix +"source"].value;
								
								collaboration = {
									type: 		type,
									language: 	language,
									subtitles: 	subtitles,
									source: 	source,
									title: 		title,
									email: 		email,
									link: 		link,
									info: 		info,
									href: 		location.href
								};
							}
							else
							{
								if( type == 'serie' )
								{
									vform = $('#collaboration_serie_form');
									vform.validate({
										rules: 
										{
											collaboration_serie_language: 
											{
												required: function( element ) 
												{
													return element.selectedIndex < 1 || element.selectedIndex > 12;
												}
											},
											collaboration_serie_subtitles: 
											{
												required: function( element ) 
												{
													return element.selectedIndex < 1 || element.selectedIndex > 10;
												}
											},
											collaboration_serie_name: true,
											collaboration_serie_season: 
											{
												required: true,
												digits: true,
												min: 0
											},
											collaboration_serie_episode:
											{
												required: true,
												digits: true,
												min: 0
											},
											collaboration_serie_mail: 
											{
												required: true,
												email: true
											},
											collaboration_serie_link: 
											{
												required: function( element )
												{
													return $(element).val != "";
												}
											}
										},
										messages: 
										{
											collaboration_serie_language: 'Debes seleccionar un idioma de la lista.',
											collaboration_serie_subtitles: 'Subtítulos inválidos.',
											collaboration_serie_name: 'Nombre de película obligatorio.',
											collaboration_serie_season: 'La temporada debe ser un número no negativo.',
											collaboration_serie_episode: 'El capítulo debe ser un número no negativo.',
											collaboration_serie_mail: 'Introduce un email válido.',
											collaboration_serie_link: 'Es obligatorio introducir un enlace.'
										},
										errorElement: 'div',
										errorClass: 'error_msg'
									});

									if( !vform.validate().form() )
										return;
											
									collaboration = {
										type: 		type,
										language: 	language,
										subtitles: 	subtitles,
										title: 		title,
										season: 	form[ prefix +"season"].value,
										episode: 	form[ prefix +"episode"].value,
										email: 		email,
										link: 		link,
										info: 		info,
										href: 		location.href
									};
								}
							}
							
							$.ajax(
							{
								type: 'POST',
								url: '/json/send_collaboration',
								data: 
								{
									collaboration: collaboration
								},
								dataType: 'json',
								success: function( data ) 
								{
									if( data && data.estado ) 
									{
										$.gritter.add({
											title: 'Notificación',
											text:  'Gracias por colaborar con nosotros.'
										});
										
										collaboration_dialog.dialog('close');
									}
									else 
									{
										if( !data.estado )
											$.gritter.add({
												title: 'Error',
												text:  data.error
											});
									}
								},
								error: function( data ) 
								{
									$.gritter.add({
										title: 'Error',
										text:  'Ocurrió algún error enviando la información.'
									});
									
									collaboration_dialog.dialog('close');
								}
							}); //ajax
						}
					}
				});
			});
		}
	}
};


//~~~ slider
var slider = {
	start: function() 
	{
		var slideshow = $('#slideshow');
		
		if( slideshow.length > 0 ) 
		{
	    	$('.slides').cycle(
			{	
	        	speed:  'slow',
	        	timeout: 10000,
	        	pause:	true,
	        	pauseOnPagerHover: true,
	        	pager:  '#navslider',
	        	pagerAnchorBuilder: function(idx, slide) 
				{
	           		return '<li><a href="#"><img src="' + slide.children[0].src + '" width="116" height="60" /><span>' + slide.children[0].alt + '</span></a></li>';
       			}
   			});
		}
	}
};

//~~~ Abre login o da el foco a nombre en login
var go_to_access = {
	start: function() 
	{
		var gta = $('#go_to_access');
		if( gta.length > 0 )
			gta.on( 'click', function() 
			{
				$('#loginreg').trigger('click');
			});
	}
};

//~~~ input escribe el nombre y ve a tu serie
var autocomplete_series = {
	
	accentMap: 
	{
				"á": "a", "à": "a", "ä": "a", "â": "a",
				"Á": "A", "À": "A", "Ä": "A", "Â": "A",

				"é": "e", "è": "e", "ë": "e", "ê": "e",
				"É": "E", "È": "E", "Ë": "E", "Ê": "E", 

				"í": "i", "ì": "i", "ï": "i", "î": "i", 
				"Í": "I", "Ì": "I", "Ï": "I", "Î": "I", 

				"ó": "o", "ò": "o", "ö": "o", "ô": "o", "ø": "o", 
				"Ó": "O", "Ò": "O", "Ö": "O", "Ô": "O", "Ø": "O", 

				"ú": "u", "ù": "u", "ü": "u", "û": "u", 
				"Ú": "U", "Ù": "U", "Ü": "U", "Û": "U", 

				"ç": "s", "Ç": "S",

				"ñ": "n", "Ñ": "N"
	},
	normalize: function( term ) 
	{
		var ret = "";
		for ( var i = 0; i < term.length; i++ ) 
		{
			ret += autocomplete_series.accentMap[ term.charAt(i) ] || term.charAt(i);
		}
		return ret;
	},
	
	start: function() 
	{
		if( typeof( acs ) != 'undefined' )
		{
			$('#serie').autocomplete(
			{ 
				source: function( request, response ) 
				{
					var matcher = new RegExp( $.ui.autocomplete.escapeRegex( request.term ), "i" );
					
					response( $.grep( acs, function( value ) 
					{
						value = value.label || value.value || value;
						return matcher.test( value ) || matcher.test( autocomplete_series.normalize( value ) );
					}));
				},
				select: function( event, ui ) 
				{
					window.location = $('#lista-series dd a[title^="' +ui.item.label +'"]').attr('href');
				}
			});
		}
	}
};

//~~~ calcular tiempo que ha pasado desde que se hizo la crítica a una serie, película o noticia
var calculate_time_elapsed_for_comments = {
	
	start: function() 
	{
		$("time.timeago").timeago();
		$('.reviews').show();
	}
};

//~~~ diálogo para enviar feedbacks
var user_feedback = {
	start: function() 
	{
		newmessagebeta = $('#newmessagebeta__');
		if( newmessagebeta.length > 0 )
			newmessagebeta.on( 'click', function( evt ) 
			{
				evt.preventDefault();
				
				var feedback_form = $('.feedback');
				var feedback_dialog = $('#betamail');
				var feddback_message = $('#feedback_message');
			
				feedback_dialog.dialog(
				{
	       			modal: true,
	       			title: 'Ayúdanos a mejorar',
	       			resizable: false,
	       			width: 590,
					beforeClose: function() 
					{
									feedback_form.each(function() { this.reset() } );  //reset form
									feddback_message.html('');
					},
					buttons: 
					{
						Cancelar: function() 
						{
							feedback_dialog.dialog('close');
						},
						Enviar: function() 
						{
							$.ajax({
								type: 'POST',
								url: '/json/send_feedback',
								data: 
								{
									feedback_text: feedback_form.find( '#mensaje' ).val(),
									feedback_url:  window.location.href,
									feedback_resolution: screen.width +"x" +screen.height
								},
								dataType: 'json',
								success: function( data ) 
								{
									if( data.estado == true ) 
									{
										feedback_dialog.dialog('close');
										$.gritter.add({
											title: 'Notificación',
											text:  'Gracias por darnos tu opinión.'
										});
									}
									else
										if( data.fail_check )
											feddback_message.html('Error de validación, comprueba que todos los campos tengan contenido');
										else
											console.log( 'Error al guardar feedback' );
								}
							});
						}
					}
	       		});
	    	}); // click & $ > 0
	} // start
};

//~~~ Comentar una noticia
var new_new_comment = {
	start: function() 
	{
		comment_form = $('#new_new_comment');
		if( comment_form.length > 0 )
			comment_form.on( 'submit', function( evt ) 
			{
				evt.preventDefault();
				var id = comment_form.attr('data-id');
				
				$.ajax(
				{
					type: 'POST',
					url: '/json/make_a_review_on_new',
					data: 
					{
						id: id,
						comment_text: comment_form.find('textarea').val()
					},
					dataType: 'json',
					success: function( data ) 
					{
						if( data.estado == true ) 
						{
							$('#new_message').html('');

							$.gritter.add({
								title: 'Notificación',
								text:  'Gracias por darnos tu opinión.'
							});

							comment_form.each(function() { this.reset() } );

							var comments = $('#comments');

							//Actualizar criticas
							var color = comments.children(':first').attr('class');
							color == 'gris' ? color = 'blanco' : color = 'gris';

							var html_comment = 	'<li class="' +color +'">';
							html_comment += 			'<a href="/usuario/perfil/' +data.user_login +'">';
							html_comment += 				'<img alt="' +data.user_login +'" title="' +data.user_login +'" width="50" height="50" src="/avatares/m/' +data.user_login[0].toLowerCase() +'/' +data.user_login.toLowerCase() +'.jpg">';
							html_comment += 			'</a>';
							html_comment +=			'<div class="middle-list-content">';
							html_comment +=				'<p class="spec"><a title="' +data.user_login +'" href="/usuario/perfil/' +data.user_login +'">' +data.user_login +'</a> hace menos de un minuto.</p>';
							html_comment +=  			'<p>' +data.comment_text +'</p>';
							html_comment += 			'<span class="sprite delete_new_comment" data-id="' +data.id +'">[Borrar comentario]</span>';
							html_comment +=			'</div>';
							html_comment +=		'</li>';
							
							var comments_children = comments.children();
							if( comments_children.length == 1 && comments_children.hasClass( 'helper' ) ) 
							{
								comments_children.remove();
							}
								
							comments.prepend( html_comment );
							
							delete_comments_and_reviews.start();
						}
						else
							if( data.fail_check )
								$('#new_message').html('Error de validación, comprueba que todos los campos tengan contenido');
							else
								if( data.error.user_error )
									$.gritter.add({
										title: 'Alerta',
										text:  'Debes estar logueado.'
									});
								else
									console.log( 'Error al guardar comentario' );
					}
				});
			});
	}
};

//~~~ scroll de series tipo movil
var Sy_scroll = {
	start: function()
	{
		var shows_list = $('.shows_list dl:visible');
		if( shows_list.length > 0 )
		{
			shows_list.not('.changed').each( function()
			{
				var sy_list_html = $(this).html();
				var h1 = $(this).prev();
				
				$(this).remove();
				
				var sy_scroll_wrapper = $('<div></div>').addClass('sy_scroll_wrapper');
				
				h1.after( sy_scroll_wrapper );
				sy_scroll_wrapper.append( $('<dl></dl>').addClass('shows_list')	);
				
				$('.shows_list', sy_scroll_wrapper).html( sy_list_html );
				var sy_list = $('.shows_list', sy_scroll_wrapper);
				var marker = $('<div></div>').addClass('sy_scroll_marker').appendTo(sy_scroll_wrapper).text('0-9').css(
							 {
								width: $('dt', sy_list).width()
							 });
				
				sy_list.bind('scroll', function( e )
				{
					Sy_scroll.update_marker(marker, sy_list, sy_list.offset());
				}).scroll();
				
				Sy_scroll.append_selector();
			});
		}
	},
	
	append_selector: function() 
	{
	},
	update_marker: function( marker, sy_list, list_offset )
	{
		var last_dt;
		$.each( $('dt', sy_list ), function( i, el )
		{
			var current_offset = $(el).offset();
			if( current_offset.top <= list_offset.top )
			{
				last_dt = $(el);
			}
		});
		marker.text(last_dt.text());
	},
	
	total_width: 0
};

function decrement_votes( type )
{
	var number_of_reviews = $('#number-of-reviews');
	var number_of_reviews_value = parseInt( number_of_reviews.attr( 'data-value' ) );
	--number_of_reviews_value;
	
	number_of_reviews.attr( 'data-value', number_of_reviews_value );

	if( number_of_reviews_value == 0 )
		$('#reviews').append( '<li class="helper">No hay críticas, sé el primero en escribir una</li>' );
	
	if( type == 'serie' )
	{
		number_of_reviews.html( '(' +number_of_reviews_value +' críticas en esta serie)' );
		return;
	}
	
	if( type == 'episode' )
	{
		number_of_reviews.html( '(' +number_of_reviews_value +' críticas en este capítulo)' );
		return;
	}
	
	if( type == 'pelicula' )
	{
		number_of_reviews.html( '(' +number_of_reviews_value +' críticas en esta película)' );
		return;
	}
				
}

//~~~ 
var delete_comments_and_reviews = {
	start: function() 
	{
		var confirmation_dialog_message = $('#confirmation_delete_message');
		var confirmation_dialog_review = $('#confirmation_delete_review');
		
		var review_type = '';
		
		var delete_comments = $('.delete_new_comment');
		if( delete_comments.length > 0 )
		{
			delete_comments.on( 'click', function( evt ) 
			{
				evt.preventDefault();
				
				_this = $(this);
				
				confirmation_dialog_message.dialog(
				{
					modal: true,
					title: 'Confirmar eliminar comentario',
					resizable: false,
					width: 300,
					buttons: 
					{
						Cancelar: function() 
						{
							confirmation_dialog_message.dialog('close');
						},
						Aceptar: function() 
						{
							confirmation_dialog_message.dialog('close');
							
							$.ajax({
								type: 'POST',
								url: '/json/delete_new_comment',
								data: { id: _this.attr( 'data-id' ) },
								dataType: 'json',
								success: function( data ) 
								{
									if( data.estado == true ) 
									{
										_this.closest( 'li' ).remove();
										$.gritter.add({
											title: 'Notificación',
											text:  'Comentario eliminado.'
										});
										
									}
								}
							});	
						}
					}
				}); // dialog
				
			});
		}
		
		var delete_movie_review = $('.delete_movie_review');
		if( delete_movie_review.length > 0 )
		{
			delete_movie_review.on( 'click', function( evt ) 
			{
				evt.preventDefault();
				
				_this = $(this);
				
				confirmation_dialog_review.dialog(
				{
					modal: true,
					title: 'Confirmar eliminar crítica',
					resizable: false,
					width: 300,
					buttons: 
					{
						Cancelar: function() 
						{
							confirmation_dialog_review.dialog('close');
						},
						Aceptar: function() 
						{
							confirmation_dialog_review.dialog('close');
							
							$.ajax(
							{
								type: 'POST',
								url: '/json/delete_movie_review',
								data: { id: _this.attr( 'data-id' ) },
								dataType: 'json',
								success: function( data ) 
								{
									if( data.estado == true ) 
									{
										_this.closest( 'li' ).remove();
								
										$.gritter.add({
											title: 'Notificación',
											text:  'Crítica eliminada.'
										});
										decrement_votes( 'pelicula' );
									}
								}
							});
							
						}
					}
				}); // dialog
				
			});
		}
		
		var delete_serie_review = $('.delete_serie_review');
		if( delete_serie_review.length > 0 )
		{
			delete_serie_review.on( 'click', function( evt ) 
			{
				evt.preventDefault();
				
				_this = $(this);
					
				confirmation_dialog_review.dialog(
				{
					modal: true,
					title: 'Confirmar eliminar crítica',
					resizable: false,
					width: 300,
					buttons: {
						Cancelar: function() 
						{
							confirmation_dialog_review.dialog('close');
						},
						Aceptar: function() 
						{
							confirmation_dialog_review.dialog('close');
							
							$.ajax(
							{
								type: 'POST',
								url: '/json/delete_serie_review',
								data: { id: _this.attr( 'data-id' ) },
								dataType: 'json',
								success: function( data ) 
								{
									if( data.estado == true ) 
									{
										_this.closest( 'li' ).remove();
										
										$.gritter.add({
											title: 'Notificación',
											text:  'Crítica eliminada.'
										});
										decrement_votes( 'serie' );
									}
								}
							});
							
						}
					}
				}); // dialog
				
			});
			
		}
			
		var delete_episode_review = $('.delete_episode_review');
		if( delete_episode_review.length > 0 )
		{	
			delete_episode_review.on( 'click', function( evt )
			{
				_this = $(this);
				
				confirmation_dialog_review.dialog(
				{
					modal: true,
					title: 'Confirmar marcar temporada',
					resizable: false,
					width: 300,
					buttons: 
					{
						Cancelar: function() 
						{
							confirmation_dialog_review.dialog('close');
						},
						Aceptar: function() 
						{
							confirmation_dialog_review.dialog('close');
							
							$.ajax(
							{
								type: 'POST',
								url: '/json/delete_episode_review',
								data: { id: _this.attr( 'data-id' ) },
								dataType: 'json',
								success: function( data ) 
								{
									if( data.estado == true ) 
									{
										_this.closest( 'li' ).remove();
									
										$.gritter.add({
											title: 'Notificación',
											text:  'Crítica eliminada.'
										});
										decrement_votes( 'episode' );
									}
								}
							});
							
						}
					}
				}); //dialog
				
			});
		}
	}
};

//~~~ 
var change_spoiler = {
	start: function() 
	{
		var button_movie = $('.change_spoiler_movie_review');
		if( button_movie.length > 0 )
			button_movie.on( 'click', function( evt ) 
			{
				evt.preventDefault();
				
				_this = $(this);
				
				$.ajax(
				{
					type: 'POST',
					url: '/json/change_spoiler_movie_review',
					data: { id: _this.attr( 'data-id' ) },
					dataType: 'json',
					success: function( data ) 
					{
						if( data.estado == true ) 
						{
							if( data.is_spoiler )
								$('.sm'+_this.attr( 'data-id' ) ).show();
							else
								$('.sm'+_this.attr( 'data-id' ) ).hide();
						}
					}
				});
				
			});
			
		var button_serie = $('.change_spoiler_serie_review');
		if( button_serie.length > 0 )
			button_serie.on( 'click', function( evt ) 
			{
				evt.preventDefault();
				
				_this = $(this);
				
				$.ajax(
				{
					type: 'POST',
					url: '/json/change_spoiler_serie_review',
					data: { id: _this.attr( 'data-id' ) },
					dataType: 'json',
					success: function( data ) 
					{
						if( data.estado == true ) 
						{
							if( data.is_spoiler )
								$('.ss'+_this.attr( 'data-id' ) ).show();
							else
								$('.ss'+_this.attr( 'data-id' ) ).hide();
						}
					}
				});
				
			});
		
		var button_episode = $('.change_spoiler_episode_review');
		if( button_episode.length > 0 )
			button_episode.on( 'click', function( evt ) 
			{
				evt.preventDefault();
				
				_this = $(this);
				
				$.ajax(
				{
					type: 'POST',
					url: '/json/change_spoiler_episode_review',
					data: { id: _this.attr( 'data-id' ) },
					dataType: 'json',
					success: function( data ) 
					{
						if( data.estado == true ) 
						{
							if( data.is_spoiler )
								$('.se'+_this.attr( 'data-id' ) ).show();
							else
								$('.se'+_this.attr( 'data-id' ) ).hide();
						}
					}
				});
				
			});
	}
};

//~~~ tabs para películas más vistas
var most_viewed = {
	start: function() 
	{
		var most_viewed = $('#most_viewed');
		if( most_viewed.length > 0 )
		{
			most_viewed.tabs();
		}
	}
};

//~~~ validador formulario contacta
var validate_contact_info = {
	start: function()
	{
		var frm_contact_info = $('#signup_form_contact');
		if( frm_contact_info.length > 0 )
		{
			frm_contact_info.validate(
			{
				rules: 
				{
					nombre: 
					{
						required: function( element )
						{
							return $(element).val() == "";
						}
					},
					email: 
					{
						required: true,
						email: true
					}	
				},
				messages:
				{
					nombre: 'El nombre es obligatorio.',
					email: 'La dirección de correo electrónico no es válida.'
				},
				errorElement: 'div',
				errorClass: 'error_msg'
			});
			
			frm_contact_info.on( 'submit', function() 
			{
				return frm_contact_info.validate().form();
			});
		}
	}
};

//~~~ Avisos para funciones sólo válidas para usuarios logueados
var user_not_logged = {
	start: function() 
	{
		var unl = $('.user_not_logged');
		if( unl.length > 0 )
			unl.on( 'click', function( evt ) 
			{
				evt.preventDefault();
				
				$.gritter.add({
					title: 'Alerta',
					text:  'Debes estar logueado para usar esta función.'
				});

			});
	}
};

//~~~ validador formulario anúnciate
var validate_advertise = {
	start: function()
	{
		var advertise_form = $('#advertise_form');
		if( advertise_form.length > 0 )
		{
			advertise_form.validate(
			{
				rules: 
				{
					nombre: 
					{
						required: function( element )
						{
							return $(element).val() == "";
						}
					},
					email: 
					{
						required: true,
						email: true
					},
					message:
					{
						required: function( element )
						{
							return $(element).val() == "";
						}
					}
				},
				messages:
				{
					nombre: 'El nombre es obligatorio.',
					email: 'La dirección de correo electrónico no es válida.',
					message: 'La consulta es obligatoria'
				},
				errorElement: 'div',
				errorClass: 'error_msg'
			});
			
			advertise_form.on( 'submit', function() 
			{
				return advertise_form.validate().form();
			});
		}
	}
};

var comment_votes = {
	start: function() 
	{
		var vote_review = $('.vote_review_positive, .vote_review_negative');
		
		if( $('.user_not_logged').length == 0 && vote_review.length > 0 )
		{
			vote_review.on( 'click', function() 
			{				
				_this = $(this);
				
				$.ajax(
				{
					type: 'POST',
					url: '/json/vote_review_' +_this.attr( 'data-value' ),
					data: 
					{ 
						id: _this.attr( 'data-id' ),
						type: _this.attr( 'data-type' )
					},
					dataType: 'json',
					success: function( data ) 
					{
						if( data.estado == true ) 
						{
							if( data.is_not_new )
							{
								_this.closest( 'li' ).attr( 'data-value', data.value );
								
								$.gritter.add({
									title: 'Notificación',
									text: 'Tu voto ha sido renovado'
								});
							}
							else
							{
								$.gritter.add({
									title: 'Notificación',
									text: 'Gracias por tu voto'
								});
							}
						}
						else
						{
							$.gritter.add({
								title: 'Error',
								text: 'Ocurrió algún error'
							});
						}
					},
					error: function()
					{
						$.gritter.add({
							title: 'Error',
							text: 'Ocurrió algún error'
						});
					}
				});
				
			});
			
		}
		
	}
};
