 $(document).ready(function(){
 	
	var comentando = false;
					
	//Aplicamos el hack para las transparencias en IE
	$('body').supersleight({shim: 'http://'+location.host+'/img/pixel.gif'});
	$('body').supersleight();
	
	//Método que comprueba que la estructura central tenga la altura mínima
	comprobarEstructura();
	
	$("a[rel^='prettyPhoto']").prettyPhoto({theme:'dark_rounded'});
	
	$('#buscarButton').bind('click', 
		function(e){
			e.preventDefault();
			document.location = 'http://'+location.host+'/buscador/0/'+$('#buscar').val();
		}
	);
	
	$('#buscar').bind('keypress',
    function(e){
			if (e.which == 13) {
				document.location = 'http://'+location.host+'/buscador/0/'+$('#buscar').val();
			}
	    }
	);
	
	$('#comEnviar').bind('click',
		function (e){
			e.preventDefault();
			if (!comentando) {
				var comNick = $('#comNick').val();
				var comWeb = $('#comWeb').val();
				var comEmail = $('#comEmail').val();
				var comValoracion = $('#comValoracio').val();
				var comText = $('#texto').val();
				var comId = $('#registro').val();
				var comTipo = $('#comTipo').val();
				var ok = true;
				if (ok == true && comNick == '') {
					alert('No se puede dejar el campo Nombre en blanco');
					ok = false;
				}
				if (ok == true && comEmail == '') {
					alert('No se puede dejar el campo Email en blanco');
					ok = false;
				}
				else {
					if (ok == true && !(/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(comEmail))) {
						alert('La dirección e-mail introducida no es válida');
						ok = false;
					}
				}
				if (ok == true && comText == '') {
					alert('No se puede dejar el campo Texto en blanco');
					ok = false;
				}
				if (ok == true) {
				
					$('#comEnviar').html("Enviant..");
					
					comentando = true;
					
					$.ajax({
						url: "http://" + location.host + "/ajax.php",
						cache: false,
						dataType: 'xml',
						data: {
							action: 'comentario',
							nick: comNick,
							email: comEmail,
							web: comWeb,
							texto: comText,
							puntos: comValoracion,
							tipo: comTipo,
							id: comId
						},
						type: 'POST',
						success: function(data, textStatus){
							var result = $("results result:eq(0)", data).text();
							if (result == "true") {
								alert('Gracias por su comentario. En breve, será publicado');
							}
							else {
								alert("No se ha registrado su comentario por algún tipo de problema técnico o porque ha intentado enviar más de un comentario en menos de un minuto. Perdone las molestias.");
							}							
							comentando = false;
							$('#comEnviar').html("Enviar");
						}
					});
				}
			}else{
				alert("Se está enviado su comentario. Espere por favor...");
			}
		}
	);
	
	
	//Abre la publicidad en una ventana nueva o cambia la url de la página 
	$("a[rel='nofollow']").bind('click',
	    function(e){
	        e.preventDefault();
	        var url = $(this).attr('href');
	        if (url.indexOf(location.host) > 0){
	            document.location = url;
	        }else{
	            window.open(url);
	        }
	    }
	);
	
	$('#mesAnt').click(function(e){
		
		if (month == 1){
			if ((year - 1) >= 2009){
				month = 12
				year = year - 1;
			}
		}else{
			month = month - 1;
		}
		
		loadCalendar();
		
	});
	
	$('#mesSig').click(function(e){
		
		if (month == 12){
			month = 1
			year = year + 1;
		}else{
			month = month + 1;
		}
		
		loadCalendar();
		
	});
	
	$(".visorFotos ul li a.enlFoto").bind('click',
		function(e){
		    e.preventDefault();
		    $('.fotosTheatrerViewer').html('<a rel="prettyPhoto" href="'+$(this).attr('href')+'"><img alt="'+$(this).attr('title')+'" src="http://'+location.host+'/imgUp/'+$(this).attr('rel')+'"/></a>');
			$("a[rel^='prettyPhoto']").prettyPhoto({theme:'dark_rounded'});
			position = $(this).text();
		}
	);
	
	$("#fotSig").bind('click',
		function(e){
			e.preventDefault();
			actualPosition = parseInt(position);
			if ((actualPosition +1) > numFotosGallery){
				position = 1;
			}else{
				position = actualPosition + 1;
			}
			showFotoInTheatre(position);
		}
	);
	
	$("#fotAnt").bind('click',
		function(e){
			e.preventDefault();
			actualPosition = parseInt(position);
			if ((actualPosition - 1) <= 0){
				position = numFotosGallery;
			}else{
				position = actualPosition - 1;
			}
			showFotoInTheatre(position);
		}
	);
	
	$('#otrosEstrenosSelect').bind('change',
		function(e){
			if (e.target.value != '') {
				document.location = e.target.value;
			}
		}
	);
	
	var numFotosGallery = $(".visorFotos ul li a.enlFoto").length;
	var position = 1;
	
	$('#leerTodaCritica').bind('click', 
		function(e){
			e.preventDefault();
			$('.leerToda').hide('normal');
			$('#restoCritica').slideDown('normal');
		}
	);
	
	$('#mes').bind('change',
		function(e){
			e.preventDefault();
			loadArchivo();
		}
	);
	
	$('#any').bind('change',
		function(e){
			e.preventDefault();
			loadArchivo();
		}
	);
	
	$('.web').bind('click',
    	function(e){
	        e.preventDefault();
	        window.open($(this).attr('href'));
	    }
	);
	
	$('.fotoCabecera').bind('click',
	    function(e){
	        e.preventDefault();
	        document.location = $('.ampliar a').attr('href');
	    }
	);
	
	if ($('#resultadoArchivo').length == 1){
		
		$('.ord').bind('click',
			function(e){
				e.preventDefault();
				orden = $(this).attr('rel');
				loadArchivo();
			}
		);
		
		
		loadArchivo();
	}
	
	$('#enviarContacta').bind('click',
		function(e){
			e.preventDefault();
			var ok = true;
			if (ok ==true && $('#nombre').val() == ""){
				alert("El campo Nombre es obligatorio");
				ok = false;
			}
			if (ok ==true && $('#email').val() == ""){
				alert("El campo Email es obligatorio");
				ok = false;
			}
			if (ok ==true && $('#texto').val() == ""){
				alert("El campp Comentario es obligatorio");
				ok = false;
			}
			if (ok == true){
				
				$('.respuesta').html("Enviando..");
				$('.respuesta').show();
				$('#campos').hide();
				
				$.ajax({
				  url		: "http://"+location.host+"/ajax.php",
				  cache		: false,
				  dataType	: 'xml',
				  data		: {
				  				action		: 'contacta',
								nombre		: $('#nombre').val(),
								email		: $('#email').val(),
								comentario	: $('#texto').val()
				  			  },
				  type		: 'POST',
				  success	: function(data, textStatus){
				  				var result = $("results result:eq(0)",data).text();
								if (result == "true"){
									$('.respuesta').html('Gracias por contactar. En breve, recibirá nuestra respuesta');
								}else{
									$('#campos').show();
									$('.respuesta').html('No ha sido posible enviar el formulario. Pruebe más tarde. Perdone las molestias.');
								}
				  			  }
				});
			}
		}
	);
	
	$('a[rel="linkExt"]').bind('click',
	    function(e){
	        e.preventDefault();
	        window.open($(this).attr('href'));
	    }
	);
	
	$('#enviarAnunciate').bind('click',
		function(e){
			e.preventDefault();
			var ok = true;
			if (ok ==true && $('#nombre').val() == ""){
				alert("El campo Nombre es obligatorio");
				ok = false;
			}
			if (ok ==true && $('#email').val() == ""){
				alert("El campo Email es obligatorio");
				ok = false;
			}
			if (ok ==true && $('#empresa').val() == ""){
				alert("El campo Empresa es obligatorio");
				ok = false;
			}
			if (ok ==true && $('#telefono').val() == ""){
				alert("El campo Telefono es obligatorio");
				ok = false;
			}
			if (ok == true){
				
				$('.respuesta').html("Enviando..");
				$('.respuesta').show();
				$('#campos').hide();
				
				$.ajax({
				  url		: "http://"+location.host+"/ajax.php",
				  cache		: false,
				  dataType	: 'xml',
				  data		: {
				  				action		: 'anunciate',
								nombre		: $('#nombre').val(),
								email		: $('#email').val(),
								empresa		: $('#empresa').val(),
								telefono	: $('#telefono').val()
				  			  },
				  type		: 'POST',
				  success	: function(data, textStatus){
				  				var result = $("results result:eq(0)",data).text();
								if (result == "true"){
									$('.respuesta').html('Gracias por contactar. En breve, recibirá nuestra respuesta');
								}else{
									$('#campos').show();
									$('.respuesta').html('No ha sido posible enviar el formulario. Pruebe más tarde. Perdone las molestias.');
								}
				  			  }
				});
			}
		}
	);
	
	$('#lnkRss').bind('click',
		function(e){
			pageTracker._trackPageview('/rss.php');
		}
	);
			
});

function loadArchivo(){
	
	$('#body #structure #content #loadingArchivo').show();
	
	$.ajax({
	  url		: "http://"+location.host+"/ajax.php",
	  cache		: false,
	  dataType	: 'xml',
	  data		: {
	  				action	: 'archivo',
					month	: $('#mes').val(),
					year	: $('#any').val(),
					order	: orden,
					limit   : limit
	  			  },
	  type		: 'POST',
	  success	: function(data, textStatus){
	  				
					var totalRes = $("rows resultados:eq(0) total",data).text();
					
            		html = '<li>Páginas:</li>';
					
					for (var i = 0; i < parseInt(totalRes)/10; i++){
						html += '<li><a href="#" class="btnPaginado">'+(i + 1)+'</a></li>';
					}
					
					$('.listPaginasArchivo').html(html);
					
					$('.btnPaginado').bind('click',
						function(e){
							e.preventDefault();
							limit = (parseInt($(this).text())-1)*10;
							loadArchivo();
						}
					);
					
					var html = '<ul>';
					
					position = limit;
					
	  				$("rows row", data).each(function(o){
						var edicion = $("rows row", data).get(o);
						
						position++;
						
						html += '<li>';
                    	html += '<p class="titulo"><a href="#" rel="detArc_'+position+'">'+position+'. '+months[$("mes",edicion).text()]+' '+$("any",edicion).text()+'</a></p>';
                        html += '<div class="detailArchivo" id="detArc_'+position+'">';
                        html += '	<img src="http://'+location.host+'/imgUp/'+$("img",edicion).text()+'" width="169" alt="portada '+months[$("mes",edicion).text()]+' '+$("any",edicion).text()+'" />';
                        html += '    <div class="txt">';
                        html += '    	<p class="estrenos">Películas:</p>';
						html += '        <p class="links">';
						
						$('peliculas pelicula',edicion).each(function(o){
							
							var pelicula = $('peliculas pelicula',edicion).get(o);
							
							html += '        <a href="'+$('url', pelicula).text()+'" title="Ver ficha '+$('titulo', pelicula).text()+'">'+$('titulo', pelicula).text()+'</a>&nbsp;|&nbsp;';
								
						});
						html += '        </p>';
												
                        html += '        <p class="reportajes">Reportajes:</p>';
						
						html += '        <p class="links">';
						
						$('reportajes reportaje',edicion).each(function(o){
							
							var rep = $('reportajes reportaje',edicion).get(o);
							
							html += '        <a href="'+$('url', rep).text()+'" title="Ver reportaje '+$('titulo', rep).text()+'">'+$('titulo', rep).text()+'</a>&nbsp;|&nbsp;';
						});
						
						html += '        </p>';                       
						
                        html += '        <div class="clear"></div>';
                        html += '    </div>';
                        html += '    <div class="clear"></div>';
                        html += '</div>';
                    	html += '</li>';
					});
					
					if ($("rows row", data).length == 0){
						html += '<li><p class="error">No hay resultados</p></li>';
					}
					html += '</ul>';
					html += '<div class="clear"></div>';
					
					$('#resultadoArchivo').html(html);
					
					$('#body #structure #content #resultadoArchivo ul li .titulo a').click(function(){
						var outside='#'+$(this).attr('rel');
						$(outside).slideToggle("normal", 
							function(e){
								comprobarEstructura();
							});
						
						return false;
					});
					
					$('#body #structure #content #loadingArchivo').hide();
					
					comprobarEstructura();
					
	  			  }
	});
}

function showFotoInTheatre(position){
	for (var i = 0; i < $(".visorFotos ul li a.enlFoto").length; i++){
		if ($(".visorFotos ul li a.enlFoto")[i].text == position){
			var obj = $(".visorFotos ul li a.enlFoto")[i];
			$('.fotosTheatrerViewer').html('<a rel="prettyPhoto" href="'+obj.href+'"><img alt="'+obj.title+'" src="http://'+location.host+'/imgUp/'+obj.rel+'"/></a>');
			$("a[rel^='prettyPhoto']").prettyPhoto({theme:'dark_rounded'});
		}
	}
}

var numDays = new Array();
numDays[0] = 'Monday';
numDays[1] = 'Tuesday';
numDays[2] = 'Wednesday';
numDays[3] = 'Thursday';
numDays[4] = 'Friday';
numDays[5] = 'Saturday';
numDays[6] = 'Sunday';

var date = new Date();
var month = date.getMonth()+1;
var year = date.getFullYear();

var limit = 0;
var orden = 'DESC';

var months = new Array();
months[1] = 'enero';
months[2] = 'febrero';
months[3] = 'marzo';
months[4] = 'abril';
months[5] = 'mayo';
months[6] = 'junio';
months[7] = 'julio';
months[8] = 'agosto';
months[9] = 'septiembre';
months[10] = 'octubre';
months[11] = 'noviembre';
months[12] = 'diciembre';

function comprobarEstructura(){
	
	var obj = $('#body #structure');
	obj.height('auto');
	
	if (obj.height() < 907){
		obj.height(907);
	}
	
}