/* ***********************************************************************
* Plugins initialization
*/
function initPlugins(){
	loadjscssfile("js/plugins/vTip/vtip-min.js", "js"); 
	loadjscssfile("js/plugins/vTip/css/vtip.css", "css"); 
	
	loadjscssfile("js/plugins/jquery.easing.1.3-min.js", "js"); 
	loadjscssfile("js/plugins/jquery.scrollTo-min.js", "js"); 
	
	
	loadjscssfile("js/plugins/fcbkcomplete/style.css", "css") 
	
	loadjscssfile("js/plugins/jquery.tabs/style.css", "css") 
	
}


/*  Jquery Scroll TO */
function initScrollTo(){
    if ( jQuery(".scrollToID").length ) {
	    jQuery('.scrollToID').click(function(e){
	        jQuery.scrollTo($(this).attr('href'), 350, {easing:'easeInCubic'} );
	        return false;
	    });
	}	
}
function initColorbox(){
    if ( jQuery(".cbx-slide").length ) {
		$(".cbx-slide").colorbox({slideshow:true});
	}	
}

/*  Sliders */
function initSliderLogos(){
    if ( jQuery("#content-empresas-colaboradoras").length ) {
	    jQuery('#content-empresas-colaboradoras a.controler').click(function(e){
			$("#content-empresas-colaboradoras div.empresas").queue(function () {
		        $(this).fadeOut("slow");;
				$('#content-empresas-colaboradoras div.loading').show("fast");
		        $(this).dequeue();
		      });
			 $("#content-empresas-colaboradoras div.empresas").queue(function () {
				 $.ajax({
				   type: "POST",
				   url: "/wp-content/themes/cntv/ajax/colaboradoras.php",
				   complete: function() {
				    $('#content-empresas-colaboradoras div.empresas').fadeIn("slow");
				   },
				   success: function(msg){
					 $('#content-empresas-colaboradoras div.empresas').html(msg);
					 $('#content-empresas-colaboradoras div.loading').hide('slow');
				   }
				 });
				 $(this).dequeue();
			});
	        return false;
	    });
	}	
}
function initSliderVideo(){
    if ( jQuery("div.wrapper-video-player").length ) {
	    jQuery('div.wrapper-video-player a.controler').click(function(e){
			var categoria = $('#ComboCategory').val();
			var idPlayerSrc = new String ($('.data-player').attr('id'));
			var idPlayer = idPlayerSrc.split("-"); 
			$("#data-player-wrapper").queue(function () {
		        $('#data-player-wrapper').fadeOut("fast");
				$('div.wrapper-video-player div.loading').show("fast");
		        $(this).dequeue();
		      });
			 $("#data-player-wrapper").queue(function () {
				 $.ajax({
				   type: "POST",
				   url: "/wp-content/themes/cntv/ajax/carga-video.php",
				   data: "id="+idPlayer[1]+"&categoria="+categoria,
				   complete: function() {
				   	$('#data-player-wrapper').fadeIn("slow");
					initComentVideo();
				   },
				   success: function(msg){
					 $('#data-player-wrapper').html(msg);
					 $('div.wrapper-video-player div.loading').hide('slow');
				   }
				 });
				 $(this).dequeue();
			});
	        return false;
	    });
	}	
}


function  initHomeCategory () {
	 if ( jQuery("#cat-content").length ) {
	 	$("#cat-content .categoria").each(function(){
			if ($(this).hasClass("active") ) {
				$(this).addClass('active-new');
			}
			var cat_active = $(this).find('h3').attr('class');
        	$(this).hover(
		      function () {
					$(this).addClass('active');
					$('#content-videos-cat').addClass(cat_active);
					 
		      }, 
		      function () {
			  	$('#content-videos-cat').removeClass(cat_active);
		        if (!$(this).hasClass("active-new")) {
					$(this).removeClass('active');
				}
				if($(this).hasClass("active-new")){
					$(this).addClass('active');
				}
		      }
		    );
			
			//controlamos el evento click
			$(this).click(function () {
				
			  //capturamos la categoria activa
			  var cat_active = $(this).find('h3').attr('class');
			   //eliminamos las otras activas
			  $("#cat-content .categoria").each(function(){
			  		$(this).removeClass('active');
			  		$(this).removeClass('active-new');
			  });
			   $(this).addClass('active active-new');
			   
			   //llamadas a las funciones de carga ajax pasandoles la categoria
			   cambiarDestacados(cat_active);
			   //cambiarVideoPrincipal(cat_active);
		    });
        });
	 }	
}
function  initHomeCategorySimple () {
	 if ( jQuery("#cat-content").length ) {
	 	$("#cat-content .categoria").each(function(){
			if ($(this).hasClass("active") ) {
				$(this).addClass('active-new');
			}
			var cat_active = $(this).find('h3').attr('class');
        	$(this).hover(
		      function () {
					$(this).addClass('active');
					//$('#content-videos-cat').addClass(cat_active);
					 
		      }, 
		      function () {
			  	$('#content-videos-cat').removeClass(cat_active);
		        if (!$(this).hasClass("active-new")) {
					$(this).removeClass('active');
				}
				if($(this).hasClass("active-new")){
					$(this).addClass('active');
				}
		      }
		    );
			
			//controlamos el evento click
			$(this).click(function () {
				
			  //capturamos la categoria activa
			  var cat_active = $(this).find('h3').attr('class');
			  var url_cat= '';
			   // lanzamos la url correcta
				if(cat_active=='empresa'){
					url_cat ='empresa';
				} else if(cat_active=='noticia') {
					url_cat ='noticias';
				} else if(cat_active=='terciario') {
					url_cat ='terciario-avanzado';
				} else if(cat_active=='otras') {
					url_cat ='otras-instituciones';
				} else if(cat_active=='casos') {
					url_cat ='casos-exito';
				} else if(cat_active=='formacion') {
					url_cat ='formacion';
				}
				location.href='/videos?'+url_cat;
		    });
        });
	 }	
}

function cambiarDestacados(categoria) {
    if ( jQuery("#wrapper-videos-cat").length ) {
			$(".wrapper-videos-cat-loading").queue(function () {
		        $('.wrapper-videos-cat-loading').fadeOut("fast");
				$('#wrapper-videos-cat div.loading').show("fast");
		        $(this).dequeue();
		      });
			 $("#data-player-wrapper").queue(function () {
				 $.ajax({
				   type: "POST",
				   data: "cat="+categoria,
				   url: "/wp-content/themes/cntv/ajax/destacados.php",
				   complete: function() {
				   	$('.wrapper-videos-cat-loading').fadeIn("slow");
					initPaginadorCategorias(categoria);
				   },
				   success: function(msg){
					 $('.wrapper-videos-cat-loading').html(msg);
					 $('#wrapper-videos-cat div.loading').hide('slow');
				   }
				 });
				 $(this).dequeue();
			});
			
	}	
}

function cambiarVideoPrincipal(categoria) {
}


function initPaginadorCategorias(categoria) {
	if ( jQuery("#content-videos-cat-pager").length ) {
	    jQuery('#content-videos-cat-pager li.nums a').click(function(e){
			var num = $(this).html();
			$('#content-videos-cat .list-videos').queue(function () {
		        $(this).hide();
				$('#wrapper-videos-cat div.loading').show("fast");
		        $(this).dequeue();
		      });
			 $('#content-videos-cat .list-videos').queue(function () {
				 $.ajax({
				   type: "POST",
				   data: "cat="+categoria+"&pag="+num,
				   url: "/wp-content/themes/cntv/ajax/destacados-paginados.php",
				   complete: function() {
				   	$('#content-videos-cat .list-videos').fadeIn("slow");
				   },
				   success: function(msg){
					 $('#content-videos-cat .list-videos').html(msg);
					 $('#wrapper-videos-cat div.loading').hide('slow');
				   }
				 });
				 $(this).dequeue();
			});
			//cambiamos de lugar la clase activa
			$("#content-videos-cat-pager li.nums a").each(function(){
	        	$(this).removeClass("active");
	        });
			$(this).addClass("active");
			return false;
		 });
	 }
}

function initComentVideoValidate() {
	if (jQuery("#comentar-video").length) {
		$("#comentar-video").click(function(){
			 var logueado = $('ul.login .user-login-youtube').html();
			 if(logueado=='anónimo!'){
			 	alert('No estás logueado con tu cuenta de youtube, no puedes comentar este vídeo');
			 }
			 if (logueado != 'anónimo!') {
				initComentVideoValidate();
			 }
		});		
	}
	
}
function initComentVideo() {
	if ( jQuery("#comentar-video").length ) {
		$("#comentar-video").colorbox({width:"50%",height:"400px", inline:true, href:"#form-video-comment"});
		$("#form-video-comment").submit(function() {
			 var formOk = true;
			 var dataPost = '';
			 var idPlayerSrc = new String ($('.data-player').attr('id'));
			 var idPlayer = idPlayerSrc.split("-"); 
			
			 
			 if( $("#forn-comentarios").val()!='') {
			 		$('#forn-comentarios').css({'background-color' : '#F7F5F5 ', 'border' : '1px solid #9A9998' } );
			 		dataPost +=$('#forn-comentarios').attr('name')+'='+$('#forn-comentarios').val();
					$.ajax({
					   type: "POST",
					   data: "id="+idPlayer[1]+"&"+dataPost,
					   url: "/wp-content/themes/cntv/ajax/insert-comment-youtube.php",
					   success: function(msg){
					   	
						//si vacio esta todo ok alert(msg);
						//alert(msg);
					   }
					 });
			 } else {
					formOk= false;
					$('#forn-comentarios').css({'background-color' : 'red', 'border' : '1px solid red' } );
			 }
			//comprobacion del formulario
			if(formOk) {
				$('#msgFormComment').remove();
				$("#form-video-comment").html('<h2>Gracias por enviarnos su mensaje en breve será revisado por un administrador.</h2><p>Puede cerrar esta ventana</p>')
			} else {
				$('#msgFormComment').remove();
				$("#form-video-comment").before('<strong id="msgFormComment" style="color:red">Por favor debes rellenar todos los campos del formulario.</strong>');
			}
	      return false;
	    });	
	}
	return false;
}

function initDeleteComentVideo(){
	if (jQuery(".adminComment").length) {
		 $(".adminComment").click(function () {
		 	var comentario =  $(this);
		 	borrar=confirm("¿Deseas borrar este comentario?");
			if(borrar) {
				var dataComentarioSrc = new String ($(this).attr('title'));
				var dataComentario = dataComentarioSrc.split("-|"); 
				var comentarioText = dataComentario[1];
				var comentarioAutor = dataComentario[2];
				//id del video
				var idPlayerSrc = new String ($('.data-player').attr('id'));
				var idPlayer = idPlayerSrc.split("-"); 
				var idPlayerID = idPlayer[1];
				
				//alert('ID:'+idPlayerID+' autor: ' + comentarioAutor+ ' Comentario: '+comentarioText) ;
				$.ajax({
					   type: "POST",
					   data: "id="+idPlayerID+"&comentarioAutor="+comentarioAutor+"&comentarioText="+comentarioText,
					   url: "/wp-content/themes/cntv/ajax/delete-comment-youtube.php",
					   success: function(msg){
						//si vacio esta todo ok alert(msg);
						//alert(msg);
						if(msg=='Borrado'){
							comentario.parent().remove();
						}
					   }
					 });
			}
	    });
	}
}
function initComboBoxVideoCategory() {
	if ( jQuery("#ComboCategory").length ) {
		jQuery("#ComboCategory").selectdecorator(
			{
				DIVClass : "selectholderCustom",
				onChange : function(){
					jQuery('#MySelectVal').html('You selected ' + jQuery("#ComboCategory").val());		    			
				}	
			}									
		);
	}
}


function initFiveStar () {
	if (jQuery(".star").length) {
		$('input[type=radio].star').rating({ 
			 callback: function(value, link){
			 		var logueado = $('ul.login .user-login-youtube').html();
			 		if (logueado == 'anónimo!') {
			 			alert('No estás logueado con tu cuenta de youtube no puedes puntuar este vídeo, tu voto no será guardado. ');
			 			return false;
			 		}
			 	if (logueado != 'anónimo!') {
			 	
			 	
			 		var idPlayerSrc = new String($('.data-player').attr('id'));
			 		var idPlayer = idPlayerSrc.split("-");
			 		var idPlayerID = idPlayer[1];
			 		$.ajax({
			 			type: "POST",
			 			data: "id=" + idPlayerID + "&value=" + value,
			 			url: "/wp-content/themes/cntv/ajax/insert-vote-youtube.php",
			 			success: function(msg){
			 				//si vacio esta todo ok alert(msg);
								if (msg == '') {
									alert('Su voto se ha guardado correctamente.')
								}
							}
						});
					}
				}
		 });
	}
}

function initHandlerChangeCategoriVideo() {
	if (jQuery("#ComboCategory").length) {
		jQuery("#video-options .selectholderCustom li").click(function () {
			var categoria = $('#ComboCategory').val();
			var idPlayerSrc = new String ($('.data-player').attr('id'));
			var idPlayer = idPlayerSrc.split("-"); 
			$("#data-player-wrapper").queue(function () {
		        $('#data-player-wrapper').fadeOut("fast");
				$('div.wrapper-video-player div.loading').show("fast");
		        $(this).dequeue();
		      });
			 $("#data-player-wrapper").queue(function () {
				 $.ajax({
				   type: "POST",
				   url: "/wp-content/themes/cntv/ajax/carga-video.php",
				   data: "id="+idPlayer[1]+"&categoria="+categoria,
				   complete: function() {
				   	$('#data-player-wrapper').fadeIn("slow");
					initComentVideo();
				   },
				   success: function(msg){
					 $('#data-player-wrapper').html(msg);
					 $('div.wrapper-video-player div.loading').hide('slow');
				   }
				 });
				 $(this).dequeue();
			});
	        return false;
        });
	}
}

function initPanelLogin(){
	// Expand Panel
	$("#open").click(function(){
		$("div#panel").slideDown("slow");	
	});	
	
	// Collapse Panel
	$("#close").click(function(){
		$("div#panel").slideUp("slow");	
	});		
	
	// Switch buttons from "Log In | Register" to "Close Panel" on click
	$("#toggle a").click(function () {
		$("#toggle a").toggle();
	});
	
	$("#login-youtube").submit(function() {
		//alert('formulario');
     	var dataPost = '';
		var formOk = true;
		 $("#login-youtube input").each(function (i) {
		 	if($(this).val()!=''){
				//$(this).css({'background-color' : '#F7F5F5 ', 'border' : '1px solid #9A9998' } );
				dataPost +=$(this).attr('name')+'='+$(this).val()+'&';
			} else {
				formOk= false;
				//$(this).css({'background-color' : 'red', 'border' : '1px solid red' } );
			}
	      });
		  if(formOk) {
		  	$.ajax({
			   type: "POST",
			   data: dataPost,
			   dataType : 'json',
			   url: "/wp-content/themes/cntv/ajax/login-youtube.php",
			   success: function(json){
				//si vacio esta todo ok alert(msg);
				if(json.resultado=='ok'){
					$(".user-login-youtube").text(json.login);
					$("#bienvenida-youtube span").show();
					$("#bienvenida-youtube").show();
					$("#login-youtube").hide('slow');
					
					//cambiamos el boton login por logout
					$("#open").text('Abrir panel');
					$("#comentar-video").show();
					
				} else if(json.resultado=='error') {
					alert('No se ha podidio conectar con Youtube tus datos son incorrectos');
				}
				
			   }
			 });
		  } else {
		  	alert('debes introducir tus datos.')
		  }
      return false;
    });	
	
	$("#open-logout").click(function(){
		$.ajax({
			   type: "POST",
			   dataType : 'json',
			   url: "/wp-content/themes/cntv/ajax/logout-youtube.php",
			   success: function(json){
				//si vacio esta todo ok alert(msg);
				if (json.resultado == 'ok') {
					location.href='/';
				}
			   }
		});
		return false;
	});		
		
}

function initReloadAddIcon(){
	$.getScript("http://static.addtoany.com/menu/page.js", function(){
	  //alert("Script loaded and executed.");
	});
}
/* ***********************************************************************
* Secondary functions
*/

function debugConsole() {
	if($.browser.mozilla){
		//ability console log - firefox-firebug developer 
		$.enableConsole = true;
		$.fn.console = $.console = function(method){
			if (window.console && console[method] && $.enableConsole)
			console[method].apply(this, [].splice.call(arguments,1));
			return this;
		}
		/* sample uso  */
		//You can call any firebug functions through either the direct jQuery object, or in a chain:
		$.console('debug', 'Console debug is %s', 'active');
		// The best part is the ability to use the firebug console chain easily:
	}
}

function loadjscssfile(filename, filetype){
	 if (filetype=="js"){ //if filename is a external JavaScript file
	  var fileref=document.createElement('script')
	  fileref.setAttribute("type","text/javascript")
	  fileref.setAttribute("src", filename)
	 }
	 else if (filetype=="css"){ //if filename is an external CSS file
	  var fileref=document.createElement("link")
	  fileref.setAttribute("rel", "stylesheet")
	  fileref.setAttribute("type", "text/css")
	  fileref.setAttribute("href", filename)
	 }
	 if (typeof fileref!="undefined")
	  document.getElementsByTagName("head")[0].appendChild(fileref)
}

function handlePaginationClick(new_page_index, pagination_container) {
    // This selects 20 elements from a content array
	var ipp=8;
	var num_entries = $('#hiddenresult div.thunb').length;
	$('#Searchresult').empty();
    var max_elem = Math.min((new_page_index+1) * ipp, num_entries);
	for(var i=new_page_index*ipp;i<max_elem;i++) {
	var new_content = $('#hiddenresult div.thunb').eq(i).clone();;
    $('#Searchresult').append(new_content);
    }
	//$.scrollTo($('#wrapper').attr('href'), 0, {easing:'easeInCubic'} );
    return false;
}
           
function initPagination() {
    var num_entries = $('#hiddenresult div.thunb').length;
    // Create pagination element
    $("#Pagination").pagination(num_entries, {
        items_per_page:8,
        link_to:"#wrapper", 
		callback:handlePaginationClick
    });
 }
 

// pruebas
//loadjscssfile("myscript.js", "js") //dynamically load and add this .js file
//loadjscssfile("javascript.php", "js") //dynamically load "javascript.php" as a JavaScript file
//loadjscssfile("mystyle.css", "css") ////dynamically load and add this .css file


/* ***********************************************************************
* Event controllers
*/




runOnLoad(function(){
	//debugConsole();
	initSliderLogos();
	initSliderVideo();
	initHomeCategorySimple();
	initDeleteComentVideo();
	initHandlerChangeCategoriVideo();
	initFiveStar();
	//initPaginadorCategorias('empresa');
	initComentVideo();
	if ( $("#hiddenresult").length ) {
		 initPagination();
	}
	initPanelLogin();
});
/*
$(document).ready(function(){
	 domloader();    
	 windowloader();
	 windowOnResize();
});
*/







