 $(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+'/cercador/0/'+$('#buscar').val();
		}
	);
	
	$('#buscar').bind('keypress',
    function(e){
			if (e.which == 13) {
				document.location = 'http://'+location.host+'/cercador/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 es pot deixar es camp Nom en blanc');
					ok = false;
				}
				if (ok == true && comEmail == '') {
					alert('No es pot deixar es camp Email en blanc');
					ok = false;
				}
				else {
					if (ok == true && !(/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(comEmail))) {
						alert('La direcció e-mail introduida no es vàlida');
						ok = false;
					}
				}
				if (ok == true && comText == '') {
					alert('No es pot deixar es camp Text en blanc');
					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('Gracies pel seu comentari. En breu, serà publicat');
							}
							else {
								alert("No s'ha enregistrat el seu comentari per qualque problema tècnic o perquè ha intentat enviar més d'un comentari en menys d'un minut. Perdoni les molèsties.");
							}							
							comentando = false;
							$('#comEnviar').html("Enviar");
						}
					});
				}
			}else{
				alert("S'està enviant el seu comentari. Esperi per 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 camp Nom es obligatori");
				ok = false;
			}
			if (ok ==true && $('#email').val() == ""){
				alert("El camp Email es obligatori");
				ok = false;
			}
			if (ok ==true && $('#texto').val() == ""){
				alert("El camp Comentari es obligatori");
				ok = false;
			}
			if (ok == true){
				
				$('.respuesta').html("Enviant..");
				$('.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('Gracies per contactar. En breu, rebrà la nostra resposta');
								}else{
									$('#campos').show();
									$('.respuesta').html('No ha estat possible enviar el formulari. Provi mes tard. Perdoni les molèsties');
								}
				  			  }
				});
			}
		}
	);
	
	$('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 camp Nom es obligatori");
				ok = false;
			}
			if (ok ==true && $('#email').val() == ""){
				alert("El camp Email es obligatori");
				ok = false;
			}
			if (ok ==true && $('#empresa').val() == ""){
				alert("El camp Empresa es obligatori");
				ok = false;
			}
			if (ok ==true && $('#telefono').val() == ""){
				alert("El camp Telèfon es obligatori");
				ok = false;
			}
			if (ok == true){
				
				$('.respuesta').html("Enviant..");
				$('.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('Gracies per contactar. En breu, rebrà la nostra resposta');
								}else{
									$('#campos').show();
									$('.respuesta').html('No ha estat possible enviar el formulari. Provi mes tard. Perdoni les molèsties');
								}
				  			  }
				});
			}
		}
	);
	
	$('#lnkRss').bind('click',
		function(e){
			pageTracker._trackPageview('/rss.php');
		}
	);
	
	loadCalendar();
			
});

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àgines:</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">Obres de teatre:</p>';
						html += '        <p class="links">';
						
						$('obras obra',edicion).each(function(o){
							
							var obra = $('obras obra',edicion).get(o);
							
							html += '        <a href="'+$('url', obra).text()+'" title="Veure fitxa '+$('titulo', obra).text()+'">'+$('titulo', obra).text()+'</a>&nbsp;|&nbsp;';
								
						});
						html += '        </p>';
												
                        html += '        <p class="reportajes">Reportatges:</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="Veure reportatge '+$('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 hi ha resultats</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] = 'gener';
months[2] = 'febrer';
months[3] = 'març';
months[4] = 'abril';
months[5] = 'maig';
months[6] = 'juny';
months[7] = 'juliol';
months[8] = 'agost';
months[9] = 'setembre';
months[10] = 'octubre';
months[11] = 'novembre';
months[12] = 'desembre';

//Objeto calendar
var calendar = $('#listCalendarObras');
var calendarDays = $('#calendarDays');
var loadingCalendar = $('#loadingCalendar');

function loadCalendar(){
	
	loadingCalendar.css('top',calendarDays.position().top-1);
	loadingCalendar.css('left',calendarDays.position().left-1);
	loadingCalendar.show();
	
	$('#datSel').html(months[month]+' '+year);
		
	$.ajax({
	  url		: "http://"+location.host+"/ajax.php",
	  cache		: false,
	  dataType	: 'xml',
	  data		: {
	  				action	: 'calendar',
					month	: month,
					year	: year
	  			  },
	  type		: 'POST',
	  success	: function(data, textStatus){
	  	
					var inicio = false;
					var content = '';
					var finish = false;
					
					var actualDay = 0;
					
					for (var week = 0; week < 6; week++){
						
						content += '<tr>';
						
						for (var day = 0; day < 7; day++){
						
							if (inicio == false){
								if (numDays[day] == $("rows row:eq("+parseInt(actualDay)+") numDayInWeek",data).text()){
									inicio = true;
								}
							}
							
							if (inicio == true){
								if ($("rows row:eq("+parseInt(actualDay)+") funciones",data).length == 0) {
									content += '<td class="normalDay">' + $("rows row:eq("+parseInt(actualDay)+") numDayInMonth",data).text() + '</td>';
								}else{
									content += '<td class="activeDay"><div class="showListCalendar">' + $("rows row:eq("+parseInt(actualDay)+") numDayInMonth",data).text() + '</div></td>';
								}
								actualDay++;
							}else{
								content += '<td></td>';
							}
							
							if ($("row",data).length == actualDay){
								day++;
								finish = true;
								break;
							}
						
						}
						
						if (finish == true){
							for (var i = day; i < 7; i++){
								content += '<td></td>';
							}
							content += '</tr>';
							break;
						}
						
						
					}
					
					$('#calendarDays').html(content);
					loadingCalendar.hide();
					
					//Cuando situemos el cursor por encima del día con funciones
					$('.showListCalendar').hover(
						function(e){
							var selDay = $(this).html();
							
							var html = '';
							
							//Cargamos todos los contenidos que tenga ese día
							for (i = 0; i < $("rows row:eq("+parseInt(selDay-1)+") funciones",data).length; i++){
								
								var titulo = $("rows row:eq("+parseInt(selDay-1)+") funciones:eq("+parseInt(i)+") titulo",data).text();
								var teatro = $("rows row:eq("+parseInt(selDay-1)+") funciones:eq("+parseInt(i)+") teatro",data).text();
								var hora = $("rows row:eq("+parseInt(selDay-1)+") funciones:eq("+parseInt(i)+") hora",data).text();
								var url = $("rows row:eq("+parseInt(selDay-1)+") funciones:eq("+parseInt(i)+") url",data).text();
								var compania = $("rows row:eq("+parseInt(selDay-1)+") funciones:eq("+parseInt(i)+") compania",data).text();
								var tipo = $("rows row:eq("+parseInt(selDay-1)+") funciones:eq("+parseInt(i)+") tipo",data).text();
								
								
								if (tipo == "L") {
									html += '<li>';
									html += '<p><a href="' + url + '" class="title" title="Obra de teatre ' + titulo + '">[+] ' + titulo + '</a></p>';
									html += '<p><a href="' + url + '" class="compania" title="Companyia de teatre ' + titulo + '">' + compania + '</a></p>';
									html += '<p><a href="' + url + '" class="teatro" title="Es podrà veure a ' + teatro + '">' + teatro + '</a></p>';
									if (hora != '') {
										html += '<p><a href="' + url + '" class="hora" title="Sirà a les ' + hora + '">' + hora + ' h</a></p>';
									}
									html += '</li>';
								}else{
									html += '<li>';
									html += '<p><span class="tituloSimple">' + titulo + '</span></p>';
									html += '<p><span class="companiaSimple">' + compania + '</span></p>';
									html += '<p><span class="hora">' + teatro + '</span></p>';
									if (hora != '') {
										html += '<p><span class="horaSimple">' + hora + ' h</span></p>';
									}
									html += '</li>';
								}	
							}
							
							$('#listCalendarObrasDetail').html(html);
							
							//Calculamos la posición y mostramos el calendario
							calendar.css('left', e.pageX - calendar.width());   
							calendar.css('top', e.pageY);
							calendar.show();
						},
						function(e){
							//Cuando quitemos el ratón por encima, dispararemos un evento para que en 300 milisegundos compruebe dónde tenemos el foco
							setTimeout("hideCalendar()",300);						 
						}
					);
				  }
	});
	
}

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

function hideCalendar(){
	
	//Objeto calendar
	var calendar = $('#listCalendarObras');
	
	//Si estamos con el foco encima de las obras del día
	calendar.hover(
		function(e){
			//Dejamos visible el calendario
			calendar.show();
		}, 
		function(e){
			//De lo contrario, lo escondemos
			calendar.hide();		
		}
	);
}