//Este archivo lleva las acciones que se han de ejecutar cuando esta cargado el dom y cuando está cargada la página
// configuracion por defecto de las tooltip para todo el portal
qTipDefaults = {
	position: {
		corner: {
			target: 'center',
			tooltip: 'topLeft'
		}
	},
	style: {
		name: 'light'
	},
	show: {
		// hay que sobrescribir el efecto para evitar que en ie nos aparezca el bug con el cleartype de las fuentes al aplicar filtros
		effect: {
			type: function(){
				if(!$.browser.msie){
					$(this).fadeIn();
				} else {
					$(this).show();	
				}
			}
		}
	},
	hide: {
		fixed: true,
		// hay que sobrescribir el efecto para evitar que en ie nos aparezca el bug con el cleartype de las fuentes al aplicar filtros
		effect: {
			type: function(){
				if(!$.browser.msie){
					$(this).fadeOut();
				} else {
					$(this).hide();	
				}
			}	
		}
	}
}

// Evento ready
$(document).ready(function(){


	// Settings que utilizamos para embeber el Flowplayer dentro del prettyPhoto
	var flpSettings = '"key": "5871714b266cf478df8",'+
					  '"logo": {'+
					  '    "url": "'+_rootWeb+'/imagenes/video/logo.png",'+
					  '    "bottom": 22,'+
					  '    "right": 22,'+
					  '    "width": 40,'+
					  '    "height": 40,'+
					  '    "opacity": 0.8,'+
					  '    "fullscreenOnly": false,'+
					  '    "displayTime": 10,'+
					  '    "fadeSpeed": 300'+
					  '},'+
					  '"plugins":  {'+
					  '    "controls": {'+
					  '        "autoHide": "always",'+
					  '        "stop": true,'+
					  '        "tooltips": {'+
					  '            "buttons": true, '+
                      '            "play" : "'+ FlowPlayer.TT['PLAY'] +'", '+
                      '            "pause" : "'+FlowPlayer.TT['PAUSE']+'", '+
                      '            "mute" : "'+FlowPlayer.TT['MUTE']+'", '+
                      '            "unmute" : "'+FlowPlayer.TT['UNMUTE']+'", '+
                      '            "stop" : "'+ FlowPlayer.TT['STOP']+'", '+
                      '            "fullscreen" : "'+FlowPlayer.TT['FULLSCREEN']+'", '+
                      '            "fullscreenExit" : "'+FlowPlayer.TT['FULLSCREEN_EXIT']+'", '+
                      '            "next" : "'+FlowPlayer.TT['NEXT']+'", '+
                      '            "previous" : "'+FlowPlayer.TT['PREVIOUS']+'"'+
					  '        }'+
					  '    }'+
					  '}, '+
					  '"clip": {'+
					  '    "url": "{path}",'+
					  '    "scaling": "orig",'+
					  '    "accelerated": false,'+
					  '    "linkWindow": "_blank"'+
					  '},'+
					  '"contextMenu": ['+
					  '    "Proxia CMS 6.3",'+
					  '    "Powered by Flowplayer"'+
					  ']';
	// plugin prettyPhoto para imagenes, videos, ....
	if(typeof($.fn.prettyPhoto) == 'function' && $("a[rel^='prettyPhoto']").size() > 0){
		// Invocamos al prettyPhoto con la inicialización de los datos
		// de flowplayer para que todo funcione bien.
		$("a[rel^='prettyPhoto']").prettyPhoto({
			flowplayerSettings: flpSettings
		});
	}

	if($('a.cmAutoVideo,a.cmAutoAudio,a.cmAutoVideoNoAlt').size() > 0) {
		// Activamos el flowplayer, en primer lugar nos aseguramos de que el funcionamiento
		// es el correcto limpiando y eliminado aquellos elemntos que no funcionan, el 
		// A debe estar vacío para que empiece el auto-play del video y el href no puede
		// tener caracteres &, puesto que esto afecta al parseado JSON del flowplayer.
		$('a.cmAutoAudio').addClass('cmAutoAudioShown');
		$('a.cmAutoVideoNoAlt').css('display','block'); // Aquellos videos que no tienen imagen de splash

		$('a.cmAutoAudio,a.cmAutoVideoNoAlt').empty();
	
		// Vamos a modificar la URL del href..., si tehemos un atributo
		// path quiere decir que tenemos que utilizar este en lugar
		// de extractar el idMmedia que es la opción que estamos aplicando
		// hasta ahora.
		$('a.cmAutoVideo,a.cmAutoAudio').attr('href',function() {
			// Recuperamos el índice base.
			var currentUrl = this.href
			var _baseIndex = currentUrl.indexOf('tkShowResource');
			// Comportamiento antiguo.
			if(_baseIndex != -1) {
				var hasPath = currentUrl.indexOf('path');
				if(hasPath!=-1) {
					// Ahora tenemos que encontrar el siguiente & o en su defecto el fin
					var _nextAmp = currentUrl.indexOf('&',hasPath);
					var url = false;
					if(_nextAmp!=-1) {
						url = currentUrl.substring(hasPath+5,_nextAmp);
					} else {
						url = currentUrl.substring(hasPath+5);
					}
					return url;
				} else {
					// Ahora, tenemos que obtener los datos 
					var _idMmediaIndx = currentUrl.indexOf('idMmedia=');
					// Ahora tenemos que encontrar el siguiente & o en su defecto el fin
					var _nextAmp = currentUrl.indexOf('&',_idMmediaIndx);
			
					var _url = currentUrl.substring(0,_baseIndex)+'images?idMmedia=';
					if(_nextAmp != -1) {
						_url+=currentUrl.substring(_idMmediaIndx+9,_nextAmp);
					} else {
						_url+=currentUrl.substring(_idMmediaIndx+9);
					}
					return _url;
				}
			} else {
				// En el comportamiento nuevo el nombre del recurso sera
				// del tipo path_base/s,id-fichero, tenemos que eliminar
				// el caracter s,
				var tmpImage = currentUrl;
				var baseImage = '';
				if(tmpImage.indexOf('/')!=-1) {
					baseImage = tmpImage.substring(0,tmpImage.lastIndexOf('/')+1);
					tmpImage = tmpImage.substring(tmpImage.lastIndexOf('/')+1);
				}
				if(tmpImage.indexOf('g,') == 0 || tmpImage.indexOf('s,') == 0 ||
				   tmpImage.indexOf('f,') == 0) {
					tmpImage = tmpImage.substring(2);
				}
						
				return baseImage+tmpImage;
			}
		});

		// Instanciamos los flowplayer.
		flowplayer("a.cmAutoVideo", _rootWeb+"/javaScript/flowplayer/flowplayer.unlimited-3.1.5.swf",{
			key: '5871714b266cf478df8',
			logo: {
				url: _rootWeb+'/imagenes/video/logo.png',
				bottom: 22,
				right: 22,
				width: 40,
				height: 40,
				opacity: 0.8,
				fullscreenOnly: false,
				displayTime: 10,
				fadeSpeed: 300
			},
			plugins:  {         
				controls: {     
					tooltipColor: '#70c6a9',
					tooltipTextColor: '#000000',
					sliderColor: '#70c6a9',
					volumeSliderColor: '#70c6a9',
					autoHide: 'always',
					stop: true,
					tooltips: {
						buttons: true,
						play: FlowPlayer.TT['PLAY'],
						pause: FlowPlayer.TT['PAUSE'],
						mute: FlowPlayer.TT['MUTE'],
						unmute: FlowPlayer.TT['UNMUTE'],
						stop: FlowPlayer.TT['STOP'],
						fullscreen: FlowPlayer.TT['FULLSCREEN'],
						fullscreenExit: FlowPlayer.TT['FULLSCREEN_EXIT'],
						next: FlowPlayer.TT['NEXT'],
						previous: FlowPlayer.TT['PREVIOUS']
					}
				}
			},
			clip: {
				scaling: 'orig',
				accelerated: false,
				linkWindow: '_blank'
			},
			contextMenu: [
				// Indicamos que es un video Powered by Proxia
				"Proxia CMS 6.3",
				"Powered by Flowplayer"
			]
		});

		flowplayer("a.cmAutoAudio", _rootWeb+"/javaScript/flowplayer/flowplayer.unlimited-3.1.5.swf",{
			key: '5871714b266cf478df8',
			plugins:  {         
				controls: {
					fullscreen: false,
					height: 30,
					tooltips: {
						buttons: true,
						play: FlowPlayer.TT['PLAY'],
						pause: FlowPlayer.TT['PAUSE'],
						mute: FlowPlayer.TT['MUTE'],
						unmute: FlowPlayer.TT['UNMUTE'],
						stop: FlowPlayer.TT['STOP'],
						fullscreen: FlowPlayer.TT['FULLSCREEN'],
						fullscreenExit: FlowPlayer.TT['FULLSCREEN_EXIT'],
						next: FlowPlayer.TT['NEXT'],
						previous: FlowPlayer.TT['PREVIOUS']
					}
				}
			},
			clip: {
				autoPlay: false
			},
			contextMenu: [
				// Indicamos que es un video Powered by Proxia
				"Proxia CMS 6.3",
				"Powered by Flowplayer"
			]
		});
	};

	// Plugin para el modelo videoteca
	if($("#videoteca").length != 0 && $("#videotecaPlayer").length != 0) {

		// Proporcionamos scrolling a la barra horizontal de videos
		$("#videoteca").scrollable({items:'div.entries', size:4, clickable:false});
	
		// Configuración del flowplayer
		flowplayer("videotecaPlayer", _rootWeb+"/javaScript/flowplayer/flowplayer.unlimited-3.1.5.swf", {
			key: '5871714b266cf478df8',
			logo: {
				url: _rootWeb+'/imagenes/video/logo.png',
				bottom: 22,
				right: 22,
				width: 40,
				height: 40,
				opacity: 0.8,
				fullscreenOnly: false,
				displayTime: 10,
				fadeSpeed: 300
			},
			plugins:  {         
				controls: {     
					autoHide: 'always',
					stop: true,
					tooltips: {
						buttons: true,
						play: FlowPlayer.TT['PLAY'],
						pause: FlowPlayer.TT['PAUSE'],
						mute: FlowPlayer.TT['MUTE'],
						unmute: FlowPlayer.TT['UNMUTE'],
						stop: FlowPlayer.TT['STOP'],
						fullscreen: FlowPlayer.TT['FULLSCREEN'],
						fullscreenExit: FlowPlayer.TT['FULLSCREEN_EXIT'],
						next: FlowPlayer.TT['NEXT'],
						previous: FlowPlayer.TT['PREVIOUS']
					}
				}
			},
			clip: {
				scaling: 'orig',
				accelerated: false,
				linkWindow: '_blank',
				baseUrl: _rootWeb + '/cm/'
			},
			contextMenu: [
				// Indicamos que es un video Powered by Proxia
				"Proxia CMS 6.3",
				"Powered by Flowplayer"
			]
		}).playlist("div.entries");
	}

	// En el caso de que el video no tenga imagen de inicio, decimos
	// que la reproducción no se inicie de forma automática...
	$('a.cmAutoVideoNoAlt').flowplayer().each(function() {
		this.onLoad(function() {
			this.getClip(0).update({autoPlay:false});
		});
	});
	
		
	// contenidos en modo calendario con tooltip
	var calendariosConTooltip = $(".calendarWithTooltip"); 
	if(calendariosConTooltip.length > 0){
		calendariosConTooltip.each(function(){
			var itemActual = $(this);
			$(this).addClass('activatedTooltip');
			// hay que quitar el title de los enlaces ya que el hover se hace sobre los td
			$('.cmCalendarTable .calendarDayWithEvents .cmEventInCalendar .cmContentLink span', itemActual).removeAttr('title');
			
			// el tooltip de cada celda con eventos
			$('.cmCalendarTable .calendarDayWithEvents', itemActual).each(function(){
				$(this).qtip({	
					// cogemos el contenido del tooltip
					content: { text: $($(this).find('.dayNumber a').attr('href')).html() },
					position: qTipDefaults.position, 
					style: qTipDefaults.style,
					show: qTipDefaults.show,
					hide: qTipDefaults.hide
				});
			});
		});
	}
	
	// contenidos en modo calendario con click que muestra / oculta el dia
	var calendariosConClick = $(".calendarWithClick");
	if(calendariosConClick.length > 0){
		calendariosConClick.each(function(){
			var itemActual = $(this);
			
			// escondemos todos los eventos
			$('.cmMonthEventsContainer li.cmCalendarDay', itemActual).hide();
			
			// el evento click de cada celda con eventos
			$('.cmCalendarTable .calendarDayWithEvents', itemActual).click(function(){
				// buscamos el id al que dirige el dia con evento
				var target = $(this).find('.dayNumber a').attr('href');
				
				// escondemos los posibles mensajes cuando no existen eventos en el día actual o el mes actual
				$('.cmCalendarNoEvents', itemActual).hide();
				
				// primeramente escondemos el item visible
				$('.cmMonthEventsContainer li.cmCalendarDay:visible', itemActual).hide();
				// mostramos los eventos del dia clickado
				$(target).show();
				
				return false;
			});

			// si el día de hoy tiene eventos los mostramos nada más cargar la página
			var eventosHoy = $('.cmCalendarTable .calendarToday a');
			if (eventosHoy.length > 0) {
				$('.cmCalendarNoEvents', itemActual).hide();
				$(eventosHoy.attr('href')).show();
			}
		});
	}
});

// Evento load
$(window).load(function(){
	
});

