$(document).ready(function () {

	
/*
 * Lightbox opcional (solo si lib esta cargada y hay elementos con esa clase)
 */
	if (typeof $.fn.lightbox == 'function') {
		$("a.lightbox").lightbox(); 
	}	
	
	
/*
 * Marcador de limpiar inputs para dejar la escritura limpia
 */
	$('input.clearinput').each(function() {
		$(this)
			.data('q', $(this).val())
			
			.click(function() {
				if ($(this).val() == $(this).data('q')) {
					$(this).val('');
				}
			})
			
			.blur(function() {
				if ($(this).val() == '') {
					$(this).val($(this).data('q'));
				}
			});
	});

/*
 * Areas colapsables (enlace de control con <id> y elemento con <id>-content con contenido.
 */
	$('a.collapsible')
		.each(function() {
			if ($(this).hasClass('collapsed')) {
				$('#' + $(this).attr('id') + '-content').css('display', 'none').addClass('collapsed');
			}
		})

		.click(function() {
			$(this).toggleClass('collapsed');
			$('#' + $(this).attr('id') + '-content')
				.toggleClass('collapsed')
				.slideToggle(1000, function() {
						var id = $(this).attr('id');
						var alt = $('#' + id.substr(0, id.length - 8));
						var alt_text = collapsible_text[alt.text()];
						if (alt_text) {
							$(alt).html(alt_text);
						}
					});
			return false;
		});
	var collapsible_text = {
		'<span>Mostrar contenido</span>' : '<span>Ocultar contenido</span>',
		'<span>Ocultar contenido</span>' : '<span>Mostrar contenido</span>',
		'Abrir' : 'Cerrar',
		'Cerrar' : 'Abrir',
		'Choose language' : 'Hide language',
		'Hide language' : 'Choose language'
	};

/*
 * Banners de portada
 */
	$('#controls').each(function() {
				// Cargamos el JSON con las definiciones
		jQuery.ajax({
			url: 'js/banners/' + idioma + '.js',
			dataType: 'json',
			success: function(data, textStatus) {
				if (data.items.length > 1) {
					var controls = $('#controls');
					controls.data('backgroundItems', data.items);
					controls.data('backgroundCurrentItem', 0);
					controls.data('backgroundCurrentImage', 0);
	
					$('#imagcontainer').prepend('<img id="imgcarrousel2" />');
	
					var pager = '<p id="img-selector">';
					pager += '	<a href="#" title="Imagen anterior" class="prev"><span>Anterior</span></a> <span>|</span>';
	
					for (var i = 0; i < data.items.length; i++) {
						pager += '<a href="#" id="carrousel-' + i + '" class="page' + ((i == 0)? ' selected' : '') + '" title="' + data.items[i].title + '"><span>Imagen' + i + '</span></a> <span>|</span>';
					}
					pager += '<a href="#" title="Imagen siguiente" class="next"><span>Siguiente</span></a>';
					pager += '</p>';
					pager += '<a href="#" class="stop active">' + detenerDiapositivas + '</a> <span class="sep">|</span>';
	
					controls.prepend(pager);
	
					$('#controls a.stop').click(function() {
						if ($(this).hasClass('active')) {
							var timer = controls.data('carrousel_timer');
							if (timer) {
								clearTimeout(timer);
								controls.removeData('carrousel_timer');
							}
							$(this).text(iniciarDiapositivas);
						} else {
							setupCarrousel();
							$(this).text(detenerDiapositivas);
						}
						$(this).toggleClass('active');
					});
	
					$('#controls a.prev').click(function(evt) {
						var backgroundCurrentItem = controls.data('backgroundCurrentItem');
						var backgroundItems = controls.data('backgroundItems');
						var index = (backgroundCurrentItem + backgroundItems.length - 1) % backgroundItems.length;
						showCarrousel(index);
						return false;
					});
	
					$('#controls a.next').click(function(evt) {
						var backgroundCurrentItem = controls.data('backgroundCurrentItem');
						var backgroundItems = controls.data('backgroundItems');
						var index = (backgroundCurrentItem + 1) % backgroundItems.length;
						showCarrousel(index);
						return false;
					});
	
					$('#controls a.page').each(function(pos) {
						$(this).data('index', pos);
					}).click(function (evt) {
						var index = $(this).data('index');
						showCarrousel(index);
						return false;
					});
	
					setupCarrousel();
				}
			},
			error: function(xht, textStatus, errorThrown) {
			},
			cache : false
		});
	});

/*
 * Menu superior
 */
	$('#top-navigation a.menu').each(function() {
		var menuitem = $(this);
		var id = menuitem.attr('id').substr(7);
		var idioma = menuitem.attr('id').substr(5, 2);

		jQuery.get('smenu/' + idioma + '/supermenu' + id + '.html', function(data, textStatus) {
				menuitem.after(data);
				$('#supermenu' + id).hover(menu_clear_timeout, menu_set_timeout);
			}, 'html');
		
		menuitem.hover(
			function() {
				menu_clear_timeout();
				if (!menuitem.hasClass('active')) {
					$('#top-navigation a.menu, #top-navigation div.subnav').removeClass('active');

					menuitem.addClass('active');
					$('#supermenu' + id).addClass('active');
					$('#supermenu' + id).show();
				}
			},
			menu_set_timeout
		);
			
	});


/*
 * Destacadas de portada
 */
	$('body#frontpage ul#note').each(function() {
		var note = $(this);
		var item_count = $('ul#note li').length;
		var item_current = 0;

		note.addClass('scroll');
		note.css('width', (item_count*233) + 'px');
		note.before('<a id="note-prev" href="#" title="Noticia anterior" class="prev disabled-prev"><span>Anterior</span></a>');
		note.after('<a id="note-next" href="#" title="Noticia siguiente" class="next' + (item_count < 2? ' disabled-next' : '') + '"><span>Siguiente</span></a>');
		note.wrap('<div class="note-container"></div>');

		$('#note-prev').click(function() {
			if (item_current > 0) {
				item_current--;
				if (item_current == 0) {
					$(this).addClass('disabled-prev');
				}
				$('#note-next').removeClass('disabled-next');
				note.animate({'marginLeft' : (-item_current*233) + 'px'}, 1000);
			}
			return false;
		});

		$('#note-next').click(function() {
			if (item_current < item_count -1) {
				item_current++;
				$('#note-prev').removeClass('disabled-prev');
				if (item_current == item_count -1) {
					$(this).addClass('disabled-next');
				}
				note.animate({'marginLeft' : (-item_current*233) + 'px'}, 1000);
			}
			return false;
		});


	});


/*
 * Galeria de imagen simple
 */
	$('#img-gallery').carrousel({
		'linksSelector' : '#gallery-control a',
		'labelSelector' : '#gallery-info p em',
		'imgSelector' : '#img-active',
		'prevNextArrows' : true,
		'zoomSelector' : '#img-gallery a.imgzoom'
	});


/*
 * Eventos de calendario
 */
	$('a.event').hover(
		function() {
			var id = $(this).attr('id').substr(5);
			$('div.vevent').removeClass('active');
			$('#event-detail' + id).addClass('active');
		},
		function() {
			event_set_timeout();
		}
	);
	$('div.vevent').hover(
		function() {
			event_clear_timeout();
		},
		function() {
			$('div.vevent').removeClass('active');
			event_clear_timeout();
		}
	);

/*
 * Banner ampliable a video en la portada
 */
	$('#mainvideoplay, #videocontrol').click(function() {
		if (!$('#videocontrol').hasClass('processing')) {

			$('#videocontrol').addClass('processing');
			
			if ($('#videocontrol').hasClass('open')) {
				$('#videocontrol').hide();

				$('#player').replaceWith('<div id="videoplayer" style="height:528px;"><img src="img/misc/videoprev2.jpg"/></div>');
				$('#videoplayer').animate({'height' : '160px', 'width' : '940px'}, 1000, 'linear', function () {
					$('#mainvideoplay').show();
					$(this).remove();
					$('#pre-content').removeClass('videoopen');
					$('#videocontrol').removeClass('open').text('Abrir').fadeIn(500);
				});
			} else {
				$('#videocontrol').hide();
				
				$('#mainvideoplay').before('<div id="videoplayer" style="height:163px; overflow: hidden; position: absolute; display:none;"><img src="img/misc/videoprev2.jpg"/></div>');
				
				$('#videoplayer').fadeIn(1000, function() {
						$('#mainvideoplay').hide();		
						$(this).css('position', 'relative').animate({'height' : '528px'}, 1000, function() {
								$(this).replaceWith('<img id="mainvideoprev" src="img/misc/videoprev2.jpg" />');
								$('#mainvideoprev').animate({'height' : '528px', 'width' : '940px'}, 1000, 'linear', function () {
										$(this).replaceWith('<object id="player" classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" name="player" width="940" height="528">\
												<param name="movie" value="js/player-viral.swf" />\
												<param name="allowfullscreen" value="true" />\
												<param name="allowscriptaccess" value="always" />\
												<param name="wmode" value="transparent" />\
												<param name="controlbar" value="none" />\
												<param name="flashvars" value="file=/arona_travel_maquetacion_accesible/html/video.flv&image=img/misc/videoprev2.jpg&controlbar=none&autostart=true" />\
												<embed\
													type="application/x-shockwave-flash"\
													id="player2"\
													name="player2"\
													src="js/player-viral.swf"\
													width="940"\
													height="528"\
													allowscriptaccess="always"\
													allowfullscreen="true"\
													wmode="transparent"\
													flashvars="file=/arona_travel_maquetacion_accesible/html/video.flv&image=img/misc/videoprev2.jpg&controlbar=none&autostart=true"\
												/>\
											</object>');

										$('#pre-content').addClass('videoopen');
										$('#videocontrol').addClass('open').text('Cerrar').fadeIn(500);
									});
							});
					});
			}
			
			$('#videocontrol').removeClass('processing');
		}
		return false;
	});


/*
 * Carrousel vertical de galerias laterales
 */

	if ($('#gallery-sidebar')) {
		var container = $('#gallery-sidebar-content');
		container.addClass('vertical-gallery').removeClass('vertical-gallery-noscript');
		
		var offset = 4;
		var count = $('#gallery-sidebar-content li').length;
		
		container.data('gallery-current', 0);
		container.data('gallery-count', count);
		
		$('p.gallery-counter').text('Se muestran ' + offset + ' de ' + count);

		$('#prev-gal').click(function() {
			if (!$(this).hasClass('disabled-prev')) {
				var current = container.data('gallery-current');
				if (current > 0) {
					current--;
					if (current == 0) {
						$(this).addClass('disabled-prev');
					}
					$('#next-gal').removeClass('disabled-next');
					container.data('gallery-current', current);
					$('#gallery-sidebar-content ul').animate({'marginTop' : (-current*132) + 'px'}, 1000);
				}
			}
			return false;
		});

		$('#next-gal').click(function() {
			if (!$(this).hasClass('disabled-next')) {
				var current = container.data('gallery-current');
				var count = container.data('gallery-count');
				if (current < count -offset) {
					current++;
					$('#prev-gal').removeClass('disabled-prev');
					if (current == (count -offset)) {
						$(this).addClass('disabled-next');
					}
					container.data('gallery-current', current);
					$('#gallery-sidebar ul').animate({'marginTop' : (-current*132) + 'px'}, 1000);
				}
			}
			return false;
		});

	}

	$('li.fouc, input.fouc').removeClass('fouc');
});

function menu_clear_timeout() {
	var timer = $('#top-navigation').data('menu_timer');
	if (timer) {
		clearTimeout(timer);
		$('#top-navigation').removeData('menu_timer');
	};
}

function menu_set_timeout() {
	menu_clear_timeout();
	var timer = setTimeout(function() {
			$('#top-navigation a.menu, #top-navigation div.subnav').removeClass('active');
			menu_clear_timeout();			 
		}, 1000);
	$('#top-navigation').data('menu_timer', timer);
}

function setupCarrousel() {
        var timer = setTimeout(carrousel_timer, 16000);
        $('#controls').data('carrousel_timer', timer);
}

function carrousel_timer() {
	$('#controls a.next').click();
	setupCarrousel();
}

function showCarrousel(index) {
	var controls = $('#controls');
	var backgroundCurrentItem = controls.data('backgroundCurrentItem');
	var backgroundItems = controls.data('backgroundItems');

	if ($('#imgcarrousel1').is(':visible')) {
		$visible = $('#imgcarrousel1');
		$hidden = $('#imgcarrousel2');
	} else {
		$visible = $('#imgcarrousel2');
		$hidden = $('#imgcarrousel1');
	}
	

	if (typeof(backgroundItems[index].img) == 'undefined') {
		var img = new Image();
		$(img)
			.load(function () {
				backgroundItems[index].img = this;
				showCarrousel(index);
			})
		.error(function () {
			alert("error de transferencia de la imagen " + this.src);
		});
		img.src = backgroundItems[index].imgSrc;
	} else {
		$('#controls a.page').removeClass('selected');
		$('#carrousel-' + index).addClass('selected');

		$('#img-carrousel p.imglabel').fadeOut(500);

		var img1 = $('#imgcarrousel1');
		var img2 = $('#imgcarrousel2');
		
		if (img1.is(':visible')) {
			img2.attr({
					'src' : backgroundItems[index].img.src,
					'alt' : backgroundItems[index].desc
				});			
			img1.fadeOut(3000, function() {
					$('#img-carrousel p.imglabel').html('<a href="' + backgroundItems[index].targetUrl + '">' + backgroundItems[index].title + '</a>');
					$('#img-carrousel p.imglabel').fadeIn(500);
					controls.data('backgroundCurrentItem', index);
				});
		} else {
			img1.attr({
					'src' : backgroundItems[index].img.src,
					'alt' : backgroundItems[index].desc
				});			
			img1.fadeIn(3000, function() {
					$('#img-carrousel p.imglabel').html('<a href="' + backgroundItems[index].targetUrl + '">' + backgroundItems[index].title + '</a>');
					$('#img-carrousel p.imglabel').fadeIn(500);
					controls.data('backgroundCurrentItem', index);
				});
		}
	}
}

function event_clear_timeout() {
	var timer = $('#calendar').data('event_timer');
	if (timer) {
		clearTimeout(timer);
		$('#calendar').removeData('event_timer');
	};
}

function event_set_timeout() {
	event_clear_timeout();
	var timer = setTimeout(function() {
			$('div.vevent').removeClass('active');
			event_clear_timeout();
		}, 500);
	$('#calendar').data('event_timer', timer);
}

/*
 * Clase carrousel.
 * Carrousel de imágenes simple con imagen principal y cuadrados como minuaturas.
 */
(function($){
	var opts;
	$.fn.carrousel = function(options){
		if (this.length) {
			// build main options
			opts = $.extend({}, $.fn.carrousel.defaults, options);

			// initalize the carrousel
			$.fn.carrousel.initialize();

			return this.each(function(){
				$(this).click(function(){
					//$(this).carrousel.start(this);
					return false;
				});
			});
		}
		return this;
	};

	// carrousel functions
	$.fn.carrousel.initialize = function() {
		opts.links = $(opts.linksSelector);
		opts.img = $(opts.imgSelector);
		opts.label = opts.labelSelector? $(opts.labelSelector) : null;
		opts.zoom = opts.zoomSelector? $(opts.zoomSelector) : null;

		opts.items = new Array();
		opts.currentItem = 0;

		opts.links.each(function(i) {
			opts.items[i] = {
				'index' : i,
				'imgSrc' : this.href.replace('/ampliado/','/ficha/'),
				'largeImgSrc' : this.href.replace('/ficha/','/ampliado/'),
				'title' : this.title,
				'desc' : this.title
			};
			$(this)
				.data('index', i)
				.click($.fn.carrousel.clickItem);
		});

		if (opts.prevNextArrows && opts.links.length > 0) {
			$(opts.links[0]).before('<a href="#" title="Imagen anterior" class="prev"><span>Anterior</span></a> <span>|</span> <a href="#" title="Imagen siguiente" class="next"><span>Siguiente</span></a>');
			//$(opts.links[opts.links.length-1]).after('<span>|</span> ');

			opts.prev = $($(opts.links[0]).prev().prev().prev()[0]);
			opts.next = $($(opts.links[0]).prev()[0]);
			
			//opts.next = $($(opts.links[opts.links.length-1]).next().next()[0]);
			
			opts.prev.click($.fn.carrousel.prevItem);
			opts.next.click($.fn.carrousel.nextItem);
		}

		if (opts.label && opts.label.length > 0) {
			opts.label = $(opts.label[0]);
		} else {
			opts.label = null;
		}

		if (opts.zoom && opts.zoom.length > 0) {
			opts.zoom = $(opts.zoom[0]);
			opts.zoom.lightbox();
		} else {
			opts.zoom = null;
		}

	};

	$.fn.carrousel.clickItem = function(evt) {
		var next = $(this).data('index');
		$.fn.carrousel.showCarrousel(next);
		return false;
	};
	$.fn.carrousel.prevItem = function(evt) {
		var next = opts.currentItem - 1;
		if (next >= 0) {
			$.fn.carrousel.showCarrousel(next);
		}
		return false;
	};
	$.fn.carrousel.nextItem = function(evt) {
		var next = opts.currentItem + 1;		
		if (next < opts.items.length) {
			$.fn.carrousel.showCarrousel(next);
		}
		return false;
	};

	$.fn.carrousel.showCarrousel = function(next) {

		if (typeof(opts.items[next].img) == 'undefined') {
			// precarga de la imagen
			var img = new Image();
			$(img)
				.load(function () {
				        opts.items[next].img = this;
				        $.fn.carrousel.showCarrousel(next);
				})
				.error(function () {
				        alert("error de transferencia de la imagen " + this.src);
				 });
				img.src = opts.items[next].imgSrc;
		} else {
			opts.links.removeClass('selected');

			if (opts.zoom) opts.zoom.hide();
			if (opts.label) opts.label.fadeOut(500);

			opts.img.fadeOut(3000, function() {
				$(opts.links[next]).addClass('selected');
				opts.img.attr({
					'src' : opts.items[next].img.src,
					'alt' : opts.items[next].desc
				});
				opts.img.fadeIn(3000, function() {
					if (opts.label) {
						opts.label.text(opts.items[next].title);
						opts.label.fadeIn(500);
					}
					if (opts.zoom) {
						opts.zoom.attr('href', opts.items[next].largeImgSrc);
						opts.zoom.fadeIn(500);
					}
				});
				opts.currentItem = next;
			});

		}
	};

	$.fn.carrousel.showZoom = function() {
	};

	$.fn.carrousel.defaults = {
	};

})(jQuery);

