var parametros = {accion: "", queHacer: "", evento: "", codigo: "", lugar_retiro: "", tarjeta: ""};

$.fn.lol = function () {
	var texto = $(this).val();
	$(this).unbind('click').click(function(){
		if(jQuery.trim($(this).val()) == texto) { 
			if ($(this).attr('name') == 'clave_visible') {
				$(this).parent().find('input[name=clave]').css({'display':''});
				$(this).parent().find('input[name=clave]').focus();
				$(this).css({'display':'none'});
			} else {
				$(this).val("");
			}
		}
	});
	$(this).unbind('click').focus(function(){
		if(jQuery.trim($(this).val()) == texto) { 
			if ($(this).attr('name') == 'clave_visible') {
				$(this).parent().find('input[name=clave]').css({'display':''});
				$(this).parent().find('input[name=clave]').focus();
				$(this).css({'display':'none'});
			} else {
				$(this).val("");
			}
		}
	});
	$(this).unbind('blur').blur(function() {
		if ($(this).attr('name') == 'clave') {
			if (jQuery.trim($(this).val()) == "") {
				$(this).parent().find('input[name=clave_visible]').css({'display':''});
				$(this).css({'display':'none'});
			}
		} else {
			if (jQuery.trim($(this).val()) == "") $(this).val(texto);
		}
	});
	
	return true;
}

$(document).ready(function(){
	$('.list_event').each(function() {
		var id = $(this).attr('id');
		id = id.split("_");

		$('.ratingstar_'+id[1]).rating({ 
			callback: function(value, link){ 
				var parametros = {accion: 'eventos',
								  queHacer: 'guardarRating',
								  id: id,
								  valor: value};
								  
				cargandov2(true);
				$.ajax({
					data: parametros,
					type: 'POST',
					url: 'includes/funciones_parser.php',
					success: function(response){
						cargandov2(false);
					}
				});
			},
			split: 2
		});
	});
	$('.ratingBox').css({'display':''});
	
	var evento_reservado = function() {
		$('.list_event .reserva .reserva_activa').each(function() { 
			var reserva_activa = $(this);
			
			//COMO RETIRO
			reserva_activa.find('.retiro').unbind('click').click(function(){
				var reserva_activa = $(this).parent().parent().parent();
				reserva_activa.find('.mensaje').html($('#boxReservaComoRetiro').html()).slideDown("normal");
				reserva_activa.find('.mensaje').append('<a href="javascript:void(0)">- cerrar informaci&oacute;n</a');
				reserva_activa.find('.mensaje a').unbind('click').click(function() {
					$(this).parent().parent().parent().find('.boxReserva').slideDown("normal");
					$(this).parent().slideUp("normal");
				});
				reserva_activa.parent().find('.boxReserva').slideUp("normal");
			});
			
			//CANCELAR RESERVA
			reserva_activa.find('.cancelar').unbind('click').click(function(){
				var reserva_activa = $(this).parent().parent().parent();
				reserva_activa.find('.mensaje').html($('#boxCancelarReserva').html()).slideDown("normal");
				
				reserva_activa.find('.mensaje .no').unbind('click').click(function() {
					$(this).parent().parent().parent().find('.boxReserva').slideDown("normal");
					$(this).parent().slideUp("normal");
				});
				reserva_activa.find('.mensaje .si').unbind('click').click(function() {
					var reserva_box = $(this).parent().parent().parent().parent();
					cargandov2(true);
					$.ajax({
						data: 'accion=reservar&queHacer=cancelar&evento='+reserva_box.attr('id').replace(/evento_/, ""),
						type: 'POST',
						url: 'includes/funciones_parser.php',
						success: function(response) {
							reserva_box.find('.boxReserva').slideDown("normal");
							reserva_box.find('.mensaje').slideUp("normal");
							reserva_box.find('.reserva_activa').slideUp('normal', function(){reserva_box.find('.reserva_activa').html('')});
							
							//
								reserva_box.find('.boxReserva h6').html(response.stock[response.stock.length - 1]);
								var lugares = '', stock = 0;
								for (var cont = 0; cont < response.stock.length - 1; cont++) {
									stock = parseInt(response.stock[cont].stock, 10);
									lugares += '<li class="'+(stock > 0 ? response.stock[cont].ID:'no')+'"><strong>'+response.stock[cont].nombre+'</strong> '+stock+' Entradas disponibles</li>';
								}
								reserva_box.find('.boxReserva ul').html(lugares);
								evento_reservado();
								reservaLink();
								loginBox_reservas();
							//
							
							cargandov2(false);
						}
					});
				});
				reserva_activa.parent().find('.boxReserva').slideUp("normal");
			});
		});
	};
	var linkLugarRetiro = function(){
        if (!DESACTIVAR_FRONT_RESERVA) {
            var reserva_box = $(this).parent().parent();
            var id_evento = reserva_box.parent().parent().attr('id').replace(/evento_/, "");
            var lugar_retiro = $(this).attr('class');
            
            reserva_box.find('li').css({'background-color':'#F2F2F2'});
            $(this).css({'background-color':'#E6E6E6'});
		
            reserva_box.find('form').unbind('submit').submit(function(){
                cargandov2(true);
                parametros.codigo = reserva_box.find('input[name=codigo]').val();
                parametros.tarjeta_fisico = reserva_box.find('input[name=tarjeta_fisico]').val();
                parametros.tarjeta_chip = reserva_box.find('input[name=tarjeta_chip]').val();
                
                parametros.email = reserva_box.find('input[name=email]').val();
                parametros.clave = reserva_box.find('input[name=clave]').val();
                
                $.ajax({
                    data: parametros,
                    type: 'POST',
                    url: 'includes/funciones_parser.php',
                    success: function(response) {
                        cargandov2(false);
                        if (response.estado) {
                            if (response.estado_modo_login) {
                                $('#evento_'+id_evento+' .reserva ul li[class='+lugar_retiro+']').click();
                                $('#boxLoginHeaderContainer').html($('#boxLoginHeader').html());
                                $('#boxLoginHeaderContainer #texto_nombre_usuario').html(response.nombre_cliente);
                            } else {
                                if (response.estado_modo_tarjeta) {
                                    if (response.estado_codigo == 1) { 
                                        reserva_box.find('.error').html($('#boxReservaTarjetaError').html()).slideDown("normal");
                                        reserva_box.find('.ayuda').slideDown("normal");
                                    } else $('#evento_'+id_evento+' .reserva ul li[class='+lugar_retiro+']').click();
                                } else {
                                    reserva_box.parent().find('.boxReserva h6').html(response.stock[response.stock.length - 1]);
                                    
                                    var lugares = '', stock = 0;
                                    for (var cont = 0; cont < response.stock.length - 1; cont++) {
                                        stock = parseInt(response.stock[cont].stock, 10);
                                        lugares += '<li class="'+(stock > 0 ? response.stock[cont].ID:'no')+'"><strong>'+response.stock[cont].nombre+'</strong> '+stock+' Entradas disponibles</li>';
                                    }
                                    reserva_box.parent().find('.boxReserva ul').html(lugares);
                                    
                                    $('#boxReservaCompletada .texto_reserva').html('su n&uacute;mero de reserva es <a href="javascript:void(0)" style="text-decoration:underline" title="Imprimir" onclick="javascript:window.open(\'print.reserva.php?'+response.nro_reserva+'\', \'printreserva\', \'width=570,height=300,resizable=yes\');">'+response.nro_reserva+'</a>.');
                                    $('#boxReservaCompletada .marco strong').html(response.estado_mensaje);
                                    reserva_box.parent().find('.reserva_activa').html($('#boxReservaCompletada').html()).slideDown("normal");
                                    reserva_box.find('form').slideUp("normal");
                                    evento_reservado();
                                    reservaLink();
                                }
                            }
                            loginBox_reservas();
                        } else {
                            reserva_box.find('.error').html(response.estado_mensaje).slideDown("normal");
                        }
                    }
                });
                return false;
            });
		
            cargandov2(true);
        
            $.ajax({
                data: {accion: "cliente",
                       queHacer: "datosUsuario"},
                type: 'POST',
                url: 'includes/funciones_parser.php',
                success: function(response){
                    if (response.identificado) {
                        if (response.cantidad_reservas_activas > 0 || response.reserva_adicional) {
                            if (response.nro_tarjeta.length > 0) {
                                reserva_box.find('form').html($('#boxCodigo').html());
                                reserva_box.find('form input[name=codigo]').lol();
                                
                                parametros.accion 		= "eventos";
                                parametros.queHacer 	= "reservar";
                                parametros.evento 		= id_evento;
                                parametros.lugar_retiro = lugar_retiro;
                                
                            } else {
                                reserva_box.find('form').html($('#boxTarjeta').html());
                                reserva_box.find('form input[name=tarjeta_chip]').lol();
                                reserva_box.find('form input[name=tarjeta_fisico]').lol();
                                
                                parametros.accion 	= "cliente";
                                parametros.queHacer = "setTarjetaBip";
                            }
                            reserva_box.find('.linkAyuda').unbind('click').click(function() {
                                reserva_box.find('.ayuda').toggle("normal");
                            });
                        } else {
                            if (response.penalizado) {
                                reserva_box.find('form').html($('#boxNoReservaPenalizado').html());
                            } else {
                                reserva_box.find('form').html($('#boxNoReserva').html());
                            }
                        }
                    } else {
                        reserva_box.find('form').html($('#boxLoginReserva').html());
                        reserva_box.find('form input[name=email]').lol();
                        reserva_box.find('form input[name=clave_visible]').lol();
                        reserva_box.find('form input[name=clave]').lol();
                        
                        parametros.accion = "login";
                    }	
                    reserva_box.find('form').slideDown('normal');
                    Shadowbox.init({ skipSetup: true }); Shadowbox.setup(); 
                    cargandov2(false);
                }
            });					
        }
	};
	var reservaLink = function() {
		$('.list_event .reserva ul li[class!=no]').css({'cursor':'pointer'}).unbind('click').click(linkLugarRetiro);
	}
	
	reservaLink();
	evento_reservado();		
});

