
$(document).ready(function(){
	$('#lomas div:not(.open) ul').hide();
	$('#lomas div:not(.open) h2').live('click', function(){
		$('#lomas .open ul').slideUp(500).parent().removeClass('open');
		var header = $(this);
		header.parent().addClass('open');
		var ul = header.siblings('ul');
		ul.slideDown(500);
	});
});	
(function() {
	$.fn.impactoSlider = function(tiempo){
		
		return this.each(function(){
			var $wrapper = $(this),
				  $slider = $wrapper.find('> div').css('position', 'absolute'),
				  $items = $slider.find('> div'),
				  $single = $items.filter(':first'),
				  
				  singleHeight = $single.outerHeight(),
				  currentPage = 1,
				  pages = $items.length,
				  totalHeight = pages * singleHeight;
				  
				  $slider.height(totalHeight + ( 2 * singleHeight ));
				  
				  $items.filter(':last').after($items.filter(':first').clone().addClass('cloned'));
				  $items.filter(':first').before($items.filter(':last').clone().addClass('cloned'));
				  $items = $slider.find('> div');
				  
				  $wrapper.scrollTop(singleHeight);
				  
				function gotoPage(page) {
					var dir = page < currentPage ? -1 : 1;
					var n = Math.abs(currentPage - page);
					var up = singleHeight * dir * n;

					$wrapper.filter(':not(:animated)').animate({
						scrollTop : '+=' + up
						}, 800, function() {
							if ( page > pages ) {
								$wrapper.scrollTop(singleHeight);
								page = 1;
							} else if ( page === 0 ){
								page = pages;
								$wrapper.scrollTop(totalHeight);
							}
							currentPage = page;
						});
					return false;
				}
			        
			        $(this).bind('goto', function (event, page){
						gotoPage(page);
			        });
			        $(this).bind('next', function () {
						gotoPage(currentPage + 1);
					});
					$(this).bind('back', function () {
						gotoPage(currentPage - 1);
					});
					
					var autoscrolling = true;
					
					$(this).mouseover(function() {
						autoscrolling = false;
					}).mouseout(function(){
						autoscrolling = true;
					});
					
					setInterval(function () {
						if (autoscrolling) {
							gotoPage(currentPage + 1);
						}
					}, tiempo);
		});
		
	};
})(jQuery);

$(document).ready(function() {

	$('#columnascontainer').impactoSlider(4000);
	$('#features').impactoSlider(4500);
	$('#entrevistas').impactoSlider(4500);

	var loaded = false;
	
	$('#cerrarOverlay').live('click', function(e){
		e = e || window.event;
		e.cancelBubble = true;
		if( e.stopPropagation ){
			e.stopPropagation();
		}
		$(this).parent().css('display', 'none');
		$(this).parent().prev().css('display','none');
		loaded = false;
	});
	

	function cl(cosa){
		if(window.console){
			console.log(cosa);
		}
	}

	$("#PDF").click(function(e){
		if( !loaded ){
			$.ajax({url:this.href, cache:true, complete:function(a,b){cl(b);}, dataType:'text',  success:function(pdfs){
				loaded = true;
				$('body').append('<div id="overlayFondo">&nbsp</div><div id="overlay"><div id="cerrarOverlay">cerrar</div><div id="pdfs"></div></div>');
				$('#pdfs').html(pdfs);
				$('#overlay').css('display', 'block');
                                $('#overlayFondo').css('display', 'block');
			}});
		}
		
		$('#overlay').css('display', 'block');
		$('#overlayFondo').css('display', 'block');

		return false;
	});
	
	$('#cerrarOverlay').live('click', function(e){
		e = e || window.event;
		e.cancelBubble = true;
		if( e.stopPropagation ){
			e.stopPropagation();
		}
		$(this).parent().css('display', 'none');
		$(this).parent().prev().css('display','none');
		loaded = false;
	});
	
	
	/*
var secciones = $('.secciones .seccion');
	var max = 0;
	var procesa = [];
	setTimeout(
		function(){
		$.each(secciones, function(i, seccion){
			var s = $(seccion);
			max = s.height()>max? s.height() : max;
			procesa.push(s);
			if( (i+1)%2===0 ){
				$.each(procesa, function(i, el){ $(el).css('min-height', max);});
				max = 0;
				procesa = [];
			}
		});
		}, 1000);
*/

});


var timer = 0;
function pad(str, lenght, width){
	var l = lenght===undefined? 2 : length;
	var w = width===undefined? '0' : width;
	var string = String(str);
	while(string.length < l){
		string = w+string;
	}
	return string;
}

function timecode(s){
	var mins = Math.floor(s/60);
	var segs = Math.floor(s%60);
	var tc = pad(mins)+':'+pad(segs);
	return tc;
}

$(document).ready(function(){
	var video = null;
	var iPad = window.navigator.platform=='iPad';
	var down = "mousedown"; var up = "mouseup"; 
	if ('createTouch' in document) { down = "touchstart"; up ="touchend"; }
	
	function pad(str, lenght, width){
		var l = lenght===undefined? 2 : length;
		var w = width===undefined? '0' : width;
		var string = String(str);
		while(string.length < l){
			string = w+string;
		}
		return string;
	}

	function timecode(s){
		var mins = Math.floor(s/60);
		var segs = Math.floor(s%60);
		var tc = pad(mins)+':'+pad(segs);
		return tc;
	}

	var updateScroll = true;
	
	function updateBar(){
		var pos = video.currentTime*$('#progress').width()/video.duration;
		$('#bar').width(pos);
		$('#van').html(timecode(video.currentTime));
		$('#quedan').html(timecode(video.duration-video.currentTime));
		
		if($('#scrub:not(:active)').length > 0 && updateScroll){
			$('#scrub').css({left:pos});
		}
	}
	
	function empiezaVideo(live){
		var html = null;
		var endStuff = false;
		
		if( iPad ){
			$("#controles #volumen").hide();
			$('#video-overlay').one('click', function(e){
				e.stopPropagation();
				video.play();
				$('#video-overlay').fadeOut(500);
			});
		} else {
			if( $('#player').length === 0 ){
				var src = $('#video-overlay').attr('data-src');
				var img = $('#video img').attr('src');
				var h = $('#video-overlay').height();
				var w = $('#video-overlay').width();
				
				html = '<video src="'+src+'/playlist.m3u8" width="'+w+'" height="'+h+'" autobuffer id="player" poster='+img+' type="video/mp4; codecs=\'avc1.42E01E, mp4a.40.2\'" preload></video>'+'<nav id="controles" class="hidden"><div id="play" class="button"></div><div id="progress"><div id="bar"></div><div id="van" class="tc">Cargando...</div><div id="quedan" class="tc"></div><div id="scrub"></div></div><div id="fullscreen" class="button"></div><div id="volumen" class="button"><div id="bar"></div></div></nav>';
				$('#video-overlay').after(html);
				if( $('#galeria_nota').length > 0 ){
					$('#elem-1 > p').fadeOut(500);
				}
			}
		}
		
		video = $('#player').get(0);		if( live != 'autoplay' ){
			$('#video-overlay .button').animate({opacity: 0}, 500, function(){
				$('#video-overlay').append('<div id="loading" class="loading">Cargando Video</div>');
				endStuff = $('#video img');
				$('#video img').fadeOut(500, function(){
					$(this).remove();
				});
			});
		}
		
		var toggleState = function(e){
			$(this).toggleClass('active');
		};
		
		$('nav#controles .button').bind({
			click: function(e){
				e.stopPropagation();
				$(this).toggleClass('state');
			},
			mousedown: toggleState,
			mouseout: toggleState
		});
		
		$('#scrub').draggable({
			axis: 'x',
			containment: 'parent',
			distance: 3,
			start: function(){
				updateScroll = false;
			},
			stop: function(e, ui){
				var end = ui.position.left;
				var time = end*video.duration/$('#progress').width();
				video.currentTime = time;
				updateScroll = true;
			}
		});
		
		$('#progress').click(function(e){
			var p = $('#progress').offset().left;
			var coord = e.pageX;
			var px = coord-p;
			var time = video.duration/$('#progress').width()*px;
			video.currentTime = time;
			$('#scrub').css({left:px});
		});
		
		var pleipaus = function(e){
			e.stopPropagation();
			if( video.paused ){
				$('#video-overlay').fadeOut(500);
				video.play();
			} else {
				$('#video-overlay .button').removeClass('play').addClass('pause').css('opacity',1).one('click', function(e){
					e.stopPropagation();
					video.play();
					$('#video-overlay').fadeOut(500);
				});
				$('#video-overlay').fadeIn(500);
				video.pause();
			}
		};
		
		var buffer = function(){
			try {
				var soFar = parseInt(((video.buffered.end(0) / video.duration) * 100),null);	
			} catch(poo){
				console.log(poo);
			}
		};
		
		var end = function(){
			console.log('end!');
			$('#video video, #video nav').fadeOut(500, function(){
				$(this).after(endStuff).remove();
				$('#video img').show();
			});
			$('#video-overlay').fadeIn(500);
			$('#video-overlay').removeClass('pause').addClass('play');
		};

		$('#controles #play').click(function(e){
			pleipaus(e);
		});
		
		if(live===true) {
			$('nav#controles #progress').html('Transmisión en vivo');
		} else if(live=='autoplay'){
			video.addEventListener('timeupdate', updateBar);
		} else {
			video.addEventListener('timeupdate', updateBar);
		}
		
		video.addEventListener('error',function(){
			console.error('pedo al cargar');
			console.log(video.error.code, video.src);
		},true);
		
		video.addEventListener('ontimeupdate', function(){
			console.log('timeupdate');
		});
		
		video.addEventListener('progress', function(e){
			console.log(e.loaded + " de " +e.total);
		});
		
		video.load();
		if( iPad ){
			video.load();
			video.play();
			$('video').css('z-index',0);
		}		video.addEventListener('loadedmetadata', function(){			$('#quedan').html(timecode(video.duration));
			$('#loading').remove();
			$('#controles').removeClass('hidden');			if( video.paused ){
				video.play();
			}
			$("#play").toggleClass('state');
			$('#video').click(function(e){ pleipaus(e); $("#play").toggleClass('state'); });
			$('nav#controles').click(function(e){
				e.stopPropagation();
				return false;
			});
			
			$('#video-overlay').fadeOut(500, function(){
				var loading = document.getElementsByClassName('loading')[0];
				if( loading ){
					loading.className = 'button';
					loading.innerText = '';
				}
			});
			$('#controles #fullscreen').bind(up, function(e){
				e.stopPropagation();
				if (document.querySelector("video").webkitSupportsFullscreen) {
					video.webkitEnterFullscreen();
				}

			});
			
		
			var controles = $('#controles');
			var to = 10000;
			if( iPad ){
				$('video').bind(up, function(e){
					controles = $('#controles');
					var hidden = controles.hasClass('hidden');
					if(hidden){
						controles.removeClass('hidden');
						setTimeout(function(){controles.addClass('hidden');}, 5000);
					} else {
						controles.addClass('hidden');
					}
					
				});
			} else {
				$('#controles #volumen').bind(up, function(e){
					e.stopPropagation();
					video.muted = !video.muted;
				});
				
				$('#video').bind({
					mouseover : function(){
						controles.removeClass('hidden');
					}, 
					mouseleave : function(){
						controles.addClass('hidden');
					}
				});
				to = 5000;
			}
			setTimeout(function(){controles.addClass('hidden');}, to);

			video.addEventListener('ended', end);
		});
	}
	
	if( $('#video.autoplay').length > 0 ){		empiezaVideo('autoplay');
	} else if( $('#video.live').length > 0 ){		empiezaVideo(true);
	} else {
		$("#video-overlay").one('click', function(){
			empiezaVideo(false);
		});
	}
	
});

